<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Rate Plans';

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('money_fmt')) {
    function money_fmt($amount): string
    {
        return number_format((float)$amount, 2);
    }
}

if (!function_exists('agent_display_name')) {
    function agent_display_name(array $row): string
    {
        $name = trim((string)($row['firstname'] ?? '') . ' ' . (string)($row['lastname'] ?? ''));
        return $name !== '' ? $name : ('Agent #' . (int)($row['id'] ?? 0));
    }
}

if (!function_exists('property_label')) {
    function property_label(array $row): string
    {
        $name = trim((string)($row['name'] ?? ''));
        $code = trim((string)($row['code'] ?? ''));
        return $code !== '' ? ($name . ' - ' . $code) : $name;
    }
}

if (!function_exists('season_badge_class')) {
    function season_badge_class(?string $color): string
    {
        $allowed = ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'dark'];
        $color = strtolower(trim((string)$color));
        return in_array($color, $allowed, true) ? $color : 'secondary';
    }
}

/*
   Shared meal plan list. FB (Full Board) added alongside HB/BB - Semper
   contracts such as "STO FB" and "Rack FB" already exist, and previously
   any value that was not BB silently became HB.
*/
if (!function_exists('roomz_meal_plans')) {
    function roomz_meal_plans(): array
    {
        return [
            'BB' => 'BB - Bed + Breakfast',
            'HB' => 'HB - Half Board',
            'FB' => 'FB - Full Board',
        ];
    }
}

if (!function_exists('safe_meal_plan')) {
    function safe_meal_plan($value): string
    {
        $value = strtoupper(trim((string)$value));
        return in_array($value, ['HB', 'BB', 'FB'], true) ? $value : 'HB';
    }
}

if (!function_exists('fetch_room_types_by_property')) {
    function fetch_room_types_by_property(PDO $pdo, int $propertyId): array
    {
        if ($propertyId <= 0) {
            return [];
        }

        $stmt = $pdo->prepare("
            SELECT id, title, shortcode
            FROM room_types
            WHERE property_id = :property_id
            ORDER BY title ASC
        ");
        $stmt->execute([':property_id' => $propertyId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

/*
 * Meal Plan is now part of the uniqueness/overlap condition.
 * This means HB can overlap BB for the same room type/date/agent,
 * but HB cannot overlap another HB in that same scope.
 */
if (!function_exists('find_overlapping_rate_plan')) {
    function find_overlapping_rate_plan(
        PDO $pdo,
        int $roomTypeId,
        ?int $agentId,
        string $mealPlan,
        string $validFrom,
        string $validTo,
        int $excludeId = 0
    ): ?array {
        $sql = "
            SELECT rp.*, rt.title AS room_type_title
            FROM room_type_rate_plans rp
            INNER JOIN room_types rt ON rt.id = rp.room_type_id
            WHERE rp.room_type_id = :room_type_id
              AND rp.id <> :exclude_id
              AND rp.meal_plan = :meal_plan
              AND rp.valid_from <= :valid_to
              AND rp.valid_to >= :valid_from
        ";

        $params = [
            ':room_type_id' => $roomTypeId,
            ':exclude_id'   => $excludeId,
            ':meal_plan'    => safe_meal_plan($mealPlan),
            ':valid_from'   => $validFrom,
            ':valid_to'     => $validTo,
        ];

        if ($agentId !== null && $agentId > 0) {
            $sql .= " AND rp.agent_id = :agent_id ";
            $params[':agent_id'] = $agentId;
        } else {
            $sql .= " AND rp.agent_id IS NULL ";
        }

        $sql .= " ORDER BY rp.valid_from ASC, rp.id ASC LIMIT 1 ";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row ?: null;
    }
}

if (!function_exists('bulk_rows_overlap_each_other')) {
    function bulk_rows_overlap_each_other(array $a, array $b): bool
    {
        if ((int)$a['room_type_id'] !== (int)$b['room_type_id']) return false;
        if ((int)$a['agent_id'] !== (int)$b['agent_id']) return false;
        if (safe_meal_plan($a['meal_plan']) !== safe_meal_plan($b['meal_plan'])) return false;

        return strtotime($a['valid_from']) <= strtotime($b['valid_to'])
            && strtotime($a['valid_to']) >= strtotime($b['valid_from']);
    }
}

if (!function_exists('insert_rate_plan')) {
    function insert_rate_plan(PDO $pdo, array $row): void
    {
        $stmt = $pdo->prepare("
            INSERT INTO room_type_rate_plans
            (
                room_type_id,
                agent_id,
                title,
                season_label,
                season_color,
                meal_plan,
                valid_from,
                valid_to,
                sharing_rate,
                single_rate,
                single_supplement,
                child_rate_percent,
                currency,
                status
            )
            VALUES
            (
                :room_type_id,
                :agent_id,
                :title,
                :season_label,
                :season_color,
                :meal_plan,
                :valid_from,
                :valid_to,
                :sharing_rate,
                :single_rate,
                :single_supplement,
                :child_rate_percent,
                :currency,
                :status
            )
        ");
        $stmt->execute([
            ':room_type_id'       => (int)$row['room_type_id'],
            ':agent_id'           => (int)$row['agent_id'] > 0 ? (int)$row['agent_id'] : null,
            ':title'              => $row['title'],
            ':season_label'       => $row['season_label'] !== '' ? $row['season_label'] : null,
            ':season_color'       => $row['season_color'] !== '' ? $row['season_color'] : null,
            ':meal_plan'          => safe_meal_plan($row['meal_plan']),
            ':valid_from'         => $row['valid_from'],
            ':valid_to'           => $row['valid_to'],
            ':sharing_rate'       => round((float)$row['sharing_rate'], 2),
            ':single_rate'        => round((float)$row['single_rate'], 2),
            ':single_supplement'  => round((float)$row['single_supplement'], 2),
            ':child_rate_percent' => round((float)$row['child_rate_percent'], 2),
            ':currency'           => strtoupper(trim((string)$row['currency'])),
            ':status'             => (int)$row['status'],
        ]);
    }
}

$form = [
    'id'                  => 0,
    'property_id'         => '',
    'room_type_id'        => '',
    'agent_id'            => '',
    'title'               => '',
    'season_label'        => '',
    'season_color'        => 'secondary',
    'meal_plan'           => 'HB',
    'valid_from'          => date('Y-m-d'),
    'valid_to'            => date('Y-m-d', strtotime('+1 year')),
    'sharing_rate'        => '0.00',
    'single_rate'         => '0.00',
    'single_supplement'   => '0.00',
    'child_rate_percent'  => '50.00',
    'currency'            => 'USD',
    'status'              => '1',
];

$seasonOptions = ['Peak', 'High', 'Mid', 'Low', 'Special', 'Festive', 'Promo'];
$seasonColors = ['primary', 'secondary', 'success', 'danger', 'warning', 'info', 'dark'];

$errors = [];
$success = '';
$editing = false;
$isCopyMode = false;

if (isset($_GET['saved']) && (int)$_GET['saved'] === 1) {
    $count = (int)($_GET['count'] ?? 1);
    $success = $count > 1 ? $count . ' rate plans saved successfully.' : 'Rate plan saved successfully.';
}
if (isset($_GET['deleted']) && (int)$_GET['deleted'] === 1) {
    $success = 'Rate plan deleted successfully.';
}

$properties = $pdo->query("
    SELECT id, name, code, currency_code
    FROM properties
    WHERE is_active = 1
    ORDER BY name ASC
")->fetchAll(PDO::FETCH_ASSOC);

$agents = $pdo->query("
    SELECT id, firstname, lastname
    FROM agents
    ORDER BY firstname ASC, lastname ASC
")->fetchAll(PDO::FETCH_ASSOC);

$propertyFilter = (int)($_GET['property_id'] ?? 0);
$roomTypeFilter = (int)($_GET['room_type_id'] ?? 0);
$agentFilter    = (int)($_GET['agent_id'] ?? 0);
$statusFilter   = trim((string)($_GET['status'] ?? ''));
$search         = trim((string)($_GET['q'] ?? ''));

if (isset($_GET['ajax']) && $_GET['ajax'] === 'room_types') {
    header('Content-Type: application/json; charset=utf-8');
    $propertyId = (int)($_GET['property_id'] ?? 0);

    echo json_encode([
        'ok'   => true,
        'rows' => fetch_room_types_by_property($pdo, $propertyId),
    ]);
    exit;
}

/*
 * Bulk save: add many rate plans and save once.
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_bulk_rate_plans'])) {
    $bulkPropertyId = (int)($_POST['bulk_property_id'] ?? 0);
    $bulkAgentId    = (int)($_POST['bulk_agent_id'] ?? 0);
    $rowsRaw        = $_POST['bulk_rows'] ?? [];
    $bulkRows       = [];
    $propertyFilter = $bulkPropertyId;

    if ($bulkPropertyId <= 0) {
        $errors[] = 'Please select a property for bulk rate plans.';
    }

    if (!is_array($rowsRaw) || !$rowsRaw) {
        $errors[] = 'Add at least one rate plan row.';
    }

    foreach ($rowsRaw as $idx => $raw) {
        if (!is_array($raw)) continue;

        $lineNo = (int)$idx + 1;
        $row = [
            'line_no'            => $lineNo,
            'property_id'        => $bulkPropertyId,
            'room_type_id'       => (int)($raw['room_type_id'] ?? 0),
            'agent_id'           => $bulkAgentId,
            'title'              => trim((string)($raw['title'] ?? '')),
            'season_label'       => trim((string)($raw['season_label'] ?? '')),
            'season_color'       => trim((string)($raw['season_color'] ?? 'secondary')),
            'meal_plan'          => safe_meal_plan($raw['meal_plan'] ?? 'HB'),
            'valid_from'         => trim((string)($raw['valid_from'] ?? '')),
            'valid_to'           => trim((string)($raw['valid_to'] ?? '')),
            'sharing_rate'       => trim((string)($raw['sharing_rate'] ?? '0')),
            'single_rate'        => trim((string)($raw['single_rate'] ?? '0')),
            'single_supplement'  => trim((string)($raw['single_supplement'] ?? '0')),
            'child_rate_percent' => trim((string)($raw['child_rate_percent'] ?? '50')),
            'currency'           => strtoupper(trim((string)($raw['currency'] ?? 'USD'))),
            'status'             => (int)($raw['status'] ?? 1),
        ];

        $isCompletelyBlank = $row['room_type_id'] <= 0
            && $row['title'] === ''
            && $row['valid_from'] === ''
            && $row['valid_to'] === ''
            && (float)$row['sharing_rate'] == 0.0
            && (float)$row['single_rate'] == 0.0;

        if ($isCompletelyBlank) {
            continue;
        }

        if ($row['room_type_id'] <= 0) {
            $errors[] = 'Row ' . $lineNo . ': Please select a room type.';
        }
        if ($row['title'] === '') {
            $errors[] = 'Row ' . $lineNo . ': Title is required.';
        }
        if (!in_array($row['meal_plan'], ['HB', 'BB', 'FB'], true)) {
            $errors[] = 'Row ' . $lineNo . ': Meal Plan must be BB, HB or FB.';
        }
        if ($row['valid_from'] === '' || $row['valid_to'] === '') {
            $errors[] = 'Row ' . $lineNo . ': Valid from and valid to are required.';
        } elseif (strtotime($row['valid_to']) < strtotime($row['valid_from'])) {
            $errors[] = 'Row ' . $lineNo . ': Valid to cannot be before valid from.';
        }

        foreach (['sharing_rate', 'single_rate', 'single_supplement', 'child_rate_percent'] as $field) {
            if ($row[$field] === '' || !is_numeric($row[$field])) {
                $errors[] = 'Row ' . $lineNo . ': ' . ucwords(str_replace('_', ' ', $field)) . ' must be a valid number.';
            }
        }

        if ($row['currency'] === '') {
            $errors[] = 'Row ' . $lineNo . ': Currency is required.';
        }

        /* sharing_rate is PER ADULT - zero on an active plan bills a couple 0.00. */
        if ((int)$row['status'] === 1
            && is_numeric($row['sharing_rate'])
            && round((float)$row['sharing_rate'], 2) <= 0) {
            $errors[] = 'Row ' . $lineNo . ': Sharing rate must be greater than zero on an active plan '
                      . '(it is charged per adult, so zero would bill two adults 0.00 per night).';
        }

        $bulkRows[] = $row;
    }

    if (!$bulkRows && !$errors) {
        $errors[] = 'No valid rate plan rows were entered.';
    }

    if (!$errors) {
        try {
            $roomTypeCheck = $pdo->prepare("
                SELECT id
                FROM room_types
                WHERE id = :room_type_id
                  AND property_id = :property_id
                LIMIT 1
            ");

            foreach ($bulkRows as $row) {
                $roomTypeCheck->execute([
                    ':room_type_id' => (int)$row['room_type_id'],
                    ':property_id'  => $bulkPropertyId,
                ]);

                if (!$roomTypeCheck->fetch(PDO::FETCH_ASSOC)) {
                    $errors[] = 'Row ' . $row['line_no'] . ': Selected room type does not belong to the selected property.';
                }
            }
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }

    if (!$errors) {
        for ($i = 0; $i < count($bulkRows); $i++) {
            for ($j = $i + 1; $j < count($bulkRows); $j++) {
                if (bulk_rows_overlap_each_other($bulkRows[$i], $bulkRows[$j])) {
                    $errors[] = 'Rows ' . $bulkRows[$i]['line_no'] . ' and ' . $bulkRows[$j]['line_no'] .
                        ' overlap for the same room type, agent scope, meal plan ' . safe_meal_plan($bulkRows[$i]['meal_plan']) .
                        ', and date range.';
                }
            }
        }
    }

    if (!$errors) {
        try {
            foreach ($bulkRows as $row) {
                $overlap = find_overlapping_rate_plan(
                    $pdo,
                    (int)$row['room_type_id'],
                    $bulkAgentId > 0 ? $bulkAgentId : null,
                    $row['meal_plan'],
                    $row['valid_from'],
                    $row['valid_to'],
                    0
                );

                if ($overlap) {
                    $scopeLabel = ((int)($overlap['agent_id'] ?? 0) > 0) ? 'agent-specific' : 'default';
                    $errors[] = 'Row ' . $row['line_no'] . ': This ' . $scopeLabel .
                        ' ' . safe_meal_plan($row['meal_plan']) . ' rate plan overlaps with existing plan "' .
                        $overlap['title'] . '" for ' . ($overlap['room_type_title'] ?? 'selected room type') .
                        ' (' . $overlap['valid_from'] . ' to ' . $overlap['valid_to'] . ').';
                }
            }
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }

    if (!$errors) {
        try {
            $pdo->beginTransaction();
            foreach ($bulkRows as $row) {
                insert_rate_plan($pdo, $row);
            }
            $pdo->commit();

            header('Location: rate_plans.php?saved=1&count=' . count($bulkRows) . '&property_id=' . $bulkPropertyId);
            exit;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $errors[] = $e->getMessage();
        }
    }
}

/*
 * Single save: edit/copy/one-off rate plan.
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_rate_plan'])) {
    $form['id']                 = (int)($_POST['id'] ?? 0);
    $form['property_id']        = trim((string)($_POST['property_id'] ?? ''));
    $form['room_type_id']       = trim((string)($_POST['room_type_id'] ?? ''));
    $form['agent_id']           = trim((string)($_POST['agent_id'] ?? ''));
    $form['title']              = trim((string)($_POST['title'] ?? ''));
    $form['season_label']       = trim((string)($_POST['season_label'] ?? ''));
    $form['season_color']       = trim((string)($_POST['season_color'] ?? 'secondary'));
    $form['meal_plan']          = safe_meal_plan($_POST['meal_plan'] ?? 'HB');
    $form['valid_from']         = trim((string)($_POST['valid_from'] ?? ''));
    $form['valid_to']           = trim((string)($_POST['valid_to'] ?? ''));
    $form['sharing_rate']       = trim((string)($_POST['sharing_rate'] ?? '0'));
    $form['single_rate']        = trim((string)($_POST['single_rate'] ?? '0'));
    $form['single_supplement']  = trim((string)($_POST['single_supplement'] ?? '0'));
    $form['child_rate_percent'] = trim((string)($_POST['child_rate_percent'] ?? '50'));
    $form['currency']           = strtoupper(trim((string)($_POST['currency'] ?? 'USD')));
    $form['status']             = (string)((int)($_POST['status'] ?? 1));

    $editing = $form['id'] > 0;
    $propertyFilter = (int)$form['property_id'];

    if ((int)$form['property_id'] <= 0) {
        $errors[] = 'Please select a property.';
    }
    if ((int)$form['room_type_id'] <= 0) {
        $errors[] = 'Please select a room type.';
    }
    if ($form['title'] === '') {
        $errors[] = 'Title is required.';
    }
    if (!in_array($form['meal_plan'], ['HB', 'BB', 'FB'], true)) {
        $errors[] = 'Meal Plan is required and must be BB, HB or FB.';
    }
    if ($form['valid_from'] === '' || $form['valid_to'] === '') {
        $errors[] = 'Valid from and valid to dates are required.';
    } elseif (strtotime($form['valid_to']) < strtotime($form['valid_from'])) {
        $errors[] = 'Valid to date cannot be before valid from date.';
    }

    foreach (['sharing_rate', 'single_rate', 'single_supplement', 'child_rate_percent'] as $field) {
        if ($form[$field] === '' || !is_numeric($form[$field])) {
            $errors[] = ucwords(str_replace('_', ' ', $field)) . ' must be a valid number.';
        }
    }

    /*
       sharing_rate is charged PER ADULT for 2+ adults. A live plan with
       sharing_rate = 0 therefore bills a couple 0.00 per night - the room is
       given away silently, and nothing else in RoomZ flags it. Several
       Semper plans arrived in exactly this state, so block it at the source.
    */
    if ((int)$form['status'] === 1
        && is_numeric($form['sharing_rate'])
        && round((float)$form['sharing_rate'], 2) <= 0) {
        $errors[] = 'Sharing rate must be greater than zero on an active plan. '
                  . 'It is charged per adult, so a zero sharing rate would bill two adults 0.00 per night. '
                  . 'Set a real rate, or set the plan to Inactive.';
    }

    /* A single_supplement is dead config whenever single_rate is set: RoomZ
       uses single_rate and ignores the supplement entirely. */
    if (is_numeric($form['single_rate']) && is_numeric($form['single_supplement'])
        && round((float)$form['single_rate'], 2) > 0
        && round((float)$form['single_supplement'], 2) > 0) {
        $errors[] = 'Set either a Single Rate or a Single Supplement, not both. '
                  . 'When a Single Rate is present RoomZ uses it and ignores the supplement.';
    }

    if ($form['currency'] === '') {
        $errors[] = 'Currency is required.';
    }

    if (!$errors) {
        try {
            $stmt = $pdo->prepare("
                SELECT rt.id
                FROM room_types rt
                WHERE rt.id = :room_type_id
                  AND rt.property_id = :property_id
                LIMIT 1
            ");
            $stmt->execute([
                ':room_type_id' => (int)$form['room_type_id'],
                ':property_id'  => (int)$form['property_id'],
            ]);

            if (!$stmt->fetch(PDO::FETCH_ASSOC)) {
                $errors[] = 'Selected room type does not belong to the selected property.';
            }
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }

    if (!$errors) {
        try {
            $overlap = find_overlapping_rate_plan(
                $pdo,
                (int)$form['room_type_id'],
                (int)$form['agent_id'] > 0 ? (int)$form['agent_id'] : null,
                $form['meal_plan'],
                $form['valid_from'],
                $form['valid_to'],
                (int)$form['id']
            );

            if ($overlap) {
                $scopeLabel = ((int)($overlap['agent_id'] ?? 0) > 0)
                    ? 'agent-specific'
                    : 'default';

                $errors[] = 'This ' . $scopeLabel . ' ' . $form['meal_plan'] .
                    ' rate plan overlaps with existing plan "' . $overlap['title'] .
                    '" for ' . ($overlap['room_type_title'] ?? 'selected room type') .
                    ' (' . $overlap['valid_from'] . ' to ' . $overlap['valid_to'] . ').';
            }
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }

    if (!$errors) {
        try {
            if ($editing) {
                $stmt = $pdo->prepare("
                    UPDATE room_type_rate_plans
                    SET room_type_id = :room_type_id,
                        agent_id = :agent_id,
                        title = :title,
                        season_label = :season_label,
                        season_color = :season_color,
                        meal_plan = :meal_plan,
                        valid_from = :valid_from,
                        valid_to = :valid_to,
                        sharing_rate = :sharing_rate,
                        single_rate = :single_rate,
                        single_supplement = :single_supplement,
                        child_rate_percent = :child_rate_percent,
                        currency = :currency,
                        status = :status
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':room_type_id'       => (int)$form['room_type_id'],
                    ':agent_id'           => (int)$form['agent_id'] > 0 ? (int)$form['agent_id'] : null,
                    ':title'              => $form['title'],
                    ':season_label'       => $form['season_label'] !== '' ? $form['season_label'] : null,
                    ':season_color'       => $form['season_color'] !== '' ? $form['season_color'] : null,
                    ':meal_plan'          => $form['meal_plan'],
                    ':valid_from'         => $form['valid_from'],
                    ':valid_to'           => $form['valid_to'],
                    ':sharing_rate'       => round((float)$form['sharing_rate'], 2),
                    ':single_rate'        => round((float)$form['single_rate'], 2),
                    ':single_supplement'  => round((float)$form['single_supplement'], 2),
                    ':child_rate_percent' => round((float)$form['child_rate_percent'], 2),
                    ':currency'           => $form['currency'],
                    ':status'             => (int)$form['status'],
                    ':id'                 => (int)$form['id'],
                ]);
            } else {
                insert_rate_plan($pdo, $form);
            }

            header('Location: rate_plans.php?saved=1&property_id=' . (int)$form['property_id']);
            exit;
        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}

if (isset($_GET['delete']) && (int)$_GET['delete'] > 0) {
    $deleteId = (int)$_GET['delete'];

    try {
        $stmt = $pdo->prepare("DELETE FROM room_type_rate_plans WHERE id = :id");
        $stmt->execute([':id' => $deleteId]);

        header('Location: rate_plans.php?deleted=1&property_id=' . $propertyFilter);
        exit;
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    $editId = (int)$_GET['edit'];

    try {
        $stmt = $pdo->prepare("
            SELECT
                rp.*,
                rt.property_id
            FROM room_type_rate_plans rp
            INNER JOIN room_types rt ON rt.id = rp.room_type_id
            WHERE rp.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $editId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $editing = true;
            $form = [
                'id'                  => (int)$row['id'],
                'property_id'         => (string)($row['property_id'] ?? ''),
                'room_type_id'        => (string)$row['room_type_id'],
                'agent_id'            => (string)($row['agent_id'] ?? ''),
                'title'               => (string)$row['title'],
                'season_label'        => (string)($row['season_label'] ?? ''),
                'season_color'        => (string)($row['season_color'] ?? 'secondary'),
                'meal_plan'           => safe_meal_plan($row['meal_plan'] ?? 'HB'),
                'valid_from'          => (string)$row['valid_from'],
                'valid_to'            => (string)$row['valid_to'],
                'sharing_rate'        => (string)$row['sharing_rate'],
                'single_rate'         => (string)$row['single_rate'],
                'single_supplement'   => (string)$row['single_supplement'],
                'child_rate_percent'  => (string)$row['child_rate_percent'],
                'currency'            => (string)$row['currency'],
                'status'              => (string)(int)$row['status'],
            ];
            $propertyFilter = (int)$form['property_id'];
        } else {
            $errors[] = 'Rate plan not found.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

if (isset($_GET['copy']) && (int)$_GET['copy'] > 0) {
    $copyId = (int)$_GET['copy'];

    try {
        $stmt = $pdo->prepare("
            SELECT
                rp.*,
                rt.property_id
            FROM room_type_rate_plans rp
            INNER JOIN room_types rt ON rt.id = rp.room_type_id
            WHERE rp.id = :id
            LIMIT 1
        ");
        $stmt->execute([':id' => $copyId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $isCopyMode = true;
            $editing = false;
            $form = [
                'id'                  => 0,
                'property_id'         => (string)($row['property_id'] ?? ''),
                'room_type_id'        => (string)$row['room_type_id'],
                'agent_id'            => (string)($row['agent_id'] ?? ''),
                'title'               => (string)$row['title'] . ' Copy',
                'season_label'        => (string)($row['season_label'] ?? ''),
                'season_color'        => (string)($row['season_color'] ?? 'secondary'),
                'meal_plan'           => safe_meal_plan($row['meal_plan'] ?? 'HB'),
                'valid_from'          => (string)$row['valid_from'],
                'valid_to'            => (string)$row['valid_to'],
                'sharing_rate'        => (string)$row['sharing_rate'],
                'single_rate'         => (string)$row['single_rate'],
                'single_supplement'   => (string)$row['single_supplement'],
                'child_rate_percent'  => (string)$row['child_rate_percent'],
                'currency'            => (string)$row['currency'],
                'status'              => (string)(int)$row['status'],
            ];
            $propertyFilter = (int)$form['property_id'];
        } else {
            $errors[] = 'Rate plan to copy not found.';
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$roomTypes = fetch_room_types_by_property($pdo, (int)($form['property_id'] ?: $propertyFilter));

$sql = "
    SELECT
        rp.*,
        rt.title AS room_type_title,
        rt.shortcode AS room_type_shortcode,
        p.id AS property_id,
        p.name AS property_name,
        p.code AS property_code,
        CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) AS agent_name
    FROM room_type_rate_plans rp
    INNER JOIN room_types rt ON rt.id = rp.room_type_id
    LEFT JOIN properties p ON p.id = rt.property_id
    LEFT JOIN agents a ON a.id = rp.agent_id
    WHERE 1=1
";
$params = [];

if ($propertyFilter > 0) {
    $sql .= " AND rt.property_id = :property_id ";
    $params[':property_id'] = $propertyFilter;
}

if ($roomTypeFilter > 0) {
    $sql .= " AND rp.room_type_id = :room_type_id ";
    $params[':room_type_id'] = $roomTypeFilter;
}

if ($agentFilter > 0) {
    $sql .= " AND rp.agent_id = :agent_id ";
    $params[':agent_id'] = $agentFilter;
} elseif (isset($_GET['agent_id']) && $_GET['agent_id'] === '0') {
    $sql .= " AND rp.agent_id IS NULL ";
}

if ($statusFilter !== '') {
    $sql .= " AND rp.status = :status ";
    $params[':status'] = (int)$statusFilter;
}

if ($search !== '') {
    $searchLike = '%' . $search . '%';
    $sql .= "
        AND (
            rp.title LIKE :search_1
            OR rp.season_label LIKE :search_2
            OR rt.title LIKE :search_3
            OR rt.shortcode LIKE :search_4
            OR p.name LIKE :search_5
            OR p.code LIKE :search_6
            OR CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) LIKE :search_7
            OR rp.currency LIKE :search_8
            OR rp.meal_plan LIKE :search_9
        )
    ";
    for ($i = 1; $i <= 9; $i++) {
        $params[':search_' . $i] = $searchLike;
    }
}

$sql .= " ORDER BY p.name ASC, rt.title ASC, rp.meal_plan ASC, rp.valid_from DESC, rp.id DESC ";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$ratePlans = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-cash-coin"></i> Masters</div>
            <div class="hero-title mt-2">Rate Plans</div>
            <div class="hero-subtitle mt-2">
                Maintain invoice pricing by property, room type, meal plan, date range, season, and optionally by agent.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="rate_plans.php<?php echo $propertyFilter > 0 ? '?property_id=' . (int)$propertyFilter : ''; ?>" class="btn btn-outline-light">
                <i class="bi bi-plus-circle me-2"></i>New Rate Plan
            </a>
        </div>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success"><?php echo h($success); ?></div>
<?php endif; ?>

<?php if ($errors): ?>
    <div class="alert alert-danger">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo h($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if ($isCopyMode): ?>
    <div class="alert alert-info">
        You are copying an existing rate plan. Adjust the dates, title, season, rates, meal plan, or agent, then save as a new plan.
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-5">
        <?php if (!$editing && !$isCopyMode): ?>
            <div class="form-section mb-4">
                <div class="form-section-title">
                    <i class="bi bi-layers"></i>
                    Add Multiple Rate Plans
                </div>

                <form method="post" id="bulkRatePlanForm">
                    <div class="row g-3 mb-3">
                        <div class="col-md-7">
                            <label class="form-label">Property</label>
                            <select name="bulk_property_id" id="bulk_property_id" class="form-select" required>
                                <option value="">Select property</option>
                                <?php foreach ($properties as $p): ?>
                                    <option value="<?php echo (int)$p['id']; ?>" <?php echo $propertyFilter === (int)$p['id'] ? 'selected' : ''; ?>>
                                        <?php echo h(property_label($p)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-5">
                            <label class="form-label">Agent</label>
                            <select name="bulk_agent_id" class="form-select">
                                <option value="">Default / All agents</option>
                                <?php foreach ($agents as $agent): ?>
                                    <option value="<?php echo (int)$agent['id']; ?>">
                                        <?php echo h(agent_display_name($agent)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="alert alert-light border small">
                        Overlap check now includes <strong>Meal Plan</strong>. HB and BB can share the same dates, but two HB plans cannot overlap for the same room type and agent scope.
                    </div>

                    <div class="table-responsive rate-plan-bulk-wrap">
                        <table class="table table-sm align-middle table-bordered mb-2" id="bulkRateTable">
                            <thead class="table-light">
                                <tr>
                                    <th style="min-width:170px;">Room Type</th>
                                    <th style="min-width:170px;">Title</th>
                                    <th style="min-width:110px;">Meal</th>
                                    <th style="min-width:125px;">Season</th>
                                    <th style="min-width:115px;">Color</th>
                                    <th style="min-width:130px;">From</th>
                                    <th style="min-width:130px;">To</th>
                                    <th style="min-width:110px;">Sharing</th>
                                    <th style="min-width:110px;">Single</th>
                                    <th style="min-width:110px;">Supp</th>
                                    <th style="min-width:110px;">Child %</th>
                                    <th style="min-width:85px;">Curr</th>
                                    <th style="min-width:100px;">Status</th>
                                    <th style="width:55px;"></th>
                                </tr>
                            </thead>
                            <tbody id="bulkRateRows"></tbody>
                        </table>
                    </div>

                    <div class="d-flex flex-wrap gap-2 mt-3">
                        <button type="button" class="btn btn-outline-primary" id="addBulkRow">
                            <i class="bi bi-plus-circle me-2"></i>Add Row
                        </button>
                        <button type="submit" name="save_bulk_rate_plans" value="1" class="btn btn-primary">
                            <i class="bi bi-save me-2"></i>Save All Rate Plans
                        </button>
                    </div>
                </form>
            </div>
        <?php endif; ?>

        <div class="form-section">
            <div class="form-section-title">
                <i class="bi bi-journal-plus"></i>
                <?php
                if ($isCopyMode) {
                    echo 'Copy Rate Plan';
                } else {
                    echo $editing ? 'Edit Rate Plan' : 'Single Rate Plan';
                }
                ?>
            </div>

            <form method="post" class="row g-3">
                <input type="hidden" name="id" value="<?php echo (int)$form['id']; ?>">

                <div class="col-12">
                    <label class="form-label">Property</label>
                    <select name="property_id" id="property_id" class="form-select" required>
                        <option value="">Select property</option>
                        <?php foreach ($properties as $p): ?>
                            <option value="<?php echo (int)$p['id']; ?>" <?php echo (int)$form['property_id'] === (int)$p['id'] ? 'selected' : ''; ?>>
                                <?php echo h(property_label($p)); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12">
                    <label class="form-label">Room Type</label>
                    <select name="room_type_id" id="room_type_id" class="form-select" required>
                        <option value="">Select room type</option>
                        <?php foreach ($roomTypes as $rt): ?>
                            <option value="<?php echo (int)$rt['id']; ?>" <?php echo (int)$form['room_type_id'] === (int)$rt['id'] ? 'selected' : ''; ?>>
                                <?php echo h($rt['title']); ?><?php echo !empty($rt['shortcode']) ? ' - ' . h($rt['shortcode']) : ''; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12">
                    <label class="form-label">Agent</label>
                    <select name="agent_id" class="form-select">
                        <option value="">Default / All agents</option>
                        <?php foreach ($agents as $agent): ?>
                            <option value="<?php echo (int)$agent['id']; ?>" <?php echo (int)$form['agent_id'] === (int)$agent['id'] ? 'selected' : ''; ?>>
                                <?php echo h(agent_display_name($agent)); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-text">
                        Leave blank for the default plan. Agent-specific plans override the default for that same room type, meal plan, and date range.
                    </div>
                </div>

                <div class="col-12">
                    <label class="form-label">Plan Title</label>
                    <input type="text" name="title" class="form-control" value="<?php echo h($form['title']); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Season Label</label>
                    <select name="season_label" class="form-select">
                        <option value="">None</option>
                        <?php foreach ($seasonOptions as $season): ?>
                            <option value="<?php echo h($season); ?>" <?php echo $form['season_label'] === $season ? 'selected' : ''; ?>>
                                <?php echo h($season); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Season Color</label>
                    <select name="season_color" class="form-select">
                        <?php foreach ($seasonColors as $color): ?>
                            <option value="<?php echo h($color); ?>" <?php echo $form['season_color'] === $color ? 'selected' : ''; ?>>
                                <?php echo ucfirst(h($color)); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Meal Plan</label>
                    <select name="meal_plan" class="form-select" required>
                        <?php foreach (roomz_meal_plans() as $mpCode => $mpLabel): ?>
                            <option value="<?php echo h($mpCode); ?>" <?php echo $form['meal_plan'] === $mpCode ? 'selected' : ''; ?>><?php echo h($mpLabel); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Valid From</label>
                    <input type="date" name="valid_from" class="form-control" value="<?php echo h($form['valid_from']); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Valid To</label>
                    <input type="date" name="valid_to" class="form-control" value="<?php echo h($form['valid_to']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Sharing Rate</label>
                    <input type="number" step="0.01" min="0" name="sharing_rate" class="form-control" value="<?php echo h($form['sharing_rate']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Single Rate</label>
                    <input type="number" step="0.01" min="0" name="single_rate" class="form-control" value="<?php echo h($form['single_rate']); ?>" required>
                </div>

                <div class="col-md-4">
                    <label class="form-label">Single Supplement</label>
                    <input type="number" step="0.01" min="0" name="single_supplement" class="form-control" value="<?php echo h($form['single_supplement']); ?>" required>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Child Rate %</label>
                    <input type="number" step="0.01" min="0" name="child_rate_percent" class="form-control" value="<?php echo h($form['child_rate_percent']); ?>" required>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Currency</label>
                    <input type="text" name="currency" class="form-control" value="<?php echo h($form['currency']); ?>" required>
                </div>

                <div class="col-md-3">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="1" <?php echo $form['status'] === '1' ? 'selected' : ''; ?>>Active</option>
                        <option value="0" <?php echo $form['status'] === '0' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>

                <div class="col-12 d-flex gap-2">
                    <button type="submit" name="save_rate_plan" value="1" class="btn btn-primary">
                        <i class="bi bi-save me-2"></i>
                        <?php
                        if ($isCopyMode) {
                            echo 'Save Copy';
                        } else {
                            echo $editing ? 'Update Rate Plan' : 'Save Single Plan';
                        }
                        ?>
                    </button>
                    <a href="rate_plans.php<?php echo $propertyFilter > 0 ? '?property_id=' . (int)$propertyFilter : ''; ?>" class="btn btn-light">Reset</a>
                </div>
            </form>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card panel-card">
            <div class="card-header">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2">
                    <h5 class="mb-0">Rate Plans</h5>

                    <form method="get" class="d-flex flex-wrap gap-2">
                        <select name="property_id" id="property_filter" class="form-select">
                            <option value="0">All properties</option>
                            <?php foreach ($properties as $p): ?>
                                <option value="<?php echo (int)$p['id']; ?>" <?php echo $propertyFilter === (int)$p['id'] ? 'selected' : ''; ?>>
                                    <?php echo h(property_label($p)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <select name="room_type_id" id="room_type_filter" class="form-select">
                            <option value="0">All room types</option>
                            <?php foreach (fetch_room_types_by_property($pdo, $propertyFilter) as $rt): ?>
                                <option value="<?php echo (int)$rt['id']; ?>" <?php echo $roomTypeFilter === (int)$rt['id'] ? 'selected' : ''; ?>>
                                    <?php echo h($rt['title']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <select name="agent_id" class="form-select">
                            <option value="">All plans</option>
                            <option value="0" <?php echo (isset($_GET['agent_id']) && $_GET['agent_id'] === '0') ? 'selected' : ''; ?>>Default only</option>
                            <?php foreach ($agents as $agent): ?>
                                <option value="<?php echo (int)$agent['id']; ?>" <?php echo $agentFilter === (int)$agent['id'] ? 'selected' : ''; ?>>
                                    <?php echo h(agent_display_name($agent)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <select name="status" class="form-select">
                            <option value="">All status</option>
                            <option value="1" <?php echo $statusFilter === '1' ? 'selected' : ''; ?>>Active</option>
                            <option value="0" <?php echo $statusFilter === '0' ? 'selected' : ''; ?>>Inactive</option>
                        </select>

                        <input type="text" name="q" class="form-control" placeholder="Search plans..." value="<?php echo h($search); ?>">
                        <button class="btn btn-outline-secondary">Search</button>
                    </form>
                </div>
            </div>

            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Plan</th>
                                <th>Meal Plan</th>
                                <th>Property / Room Type</th>
                                <th>Agent</th>
                                <th>Validity</th>
                                <th>Rates</th>
                                <th>Status</th>
                                <th class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!$ratePlans): ?>
                                <tr>
                                    <td colspan="9" class="text-center text-muted py-4">No rate plans found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($ratePlans as $row): ?>
                                    <tr>
                                        <td><?php echo (int)$row['id']; ?></td>
                                        <td>
                                            <div class="fw-semibold"><?php echo h($row['title']); ?></div>
                                            <div class="small text-muted">
                                                <?php echo h($row['currency']); ?>
                                                <?php if (!empty($row['season_label'])): ?>
                                                    &middot; <span class="badge text-bg-<?php echo h(season_badge_class($row['season_color'] ?? 'secondary')); ?>">
                                                        <?php echo h($row['season_label']); ?>
                                                    </span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge text-bg-info"><?php echo h(safe_meal_plan($row['meal_plan'] ?? 'HB')); ?></span>
                                        </td>
                                        <td>
                                            <div><?php echo h($row['property_name'] ?? ''); ?><?php echo !empty($row['property_code']) ? ' - ' . h($row['property_code']) : ''; ?></div>
                                            <div class="small text-muted">
                                                <?php echo h($row['room_type_title']); ?><?php echo !empty($row['room_type_shortcode']) ? ' - ' . h($row['room_type_shortcode']) : ''; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php echo trim((string)($row['agent_name'] ?? '')) !== '' ? h($row['agent_name']) : '<span class="text-muted">Default / All</span>'; ?>
                                        </td>
                                        <td>
                                            <div class="small">
                                                <strong>From:</strong> <?php echo h($row['valid_from']); ?><br>
                                                <strong>To:</strong> <?php echo h($row['valid_to']); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="small">
                                                <strong>Sharing:</strong> <?php echo money_fmt($row['sharing_rate']); ?><br>
                                                <strong>Single:</strong> <?php echo money_fmt($row['single_rate']); ?><br>
                                                <strong>Supp:</strong> <?php echo money_fmt($row['single_supplement']); ?><br>
                                                <strong>Child %:</strong> <?php echo money_fmt($row['child_rate_percent']); ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if ((int)$row['status'] === 1): ?>
                                                <span class="badge text-bg-success">Active</span>
                                            <?php else: ?>
                                                <span class="badge text-bg-secondary">Inactive</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="d-inline-flex gap-2 flex-wrap justify-content-end">
                                                <a href="rate_plans.php?edit=<?php echo (int)$row['id']; ?>&property_id=<?php echo (int)$row['property_id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                                <a href="rate_plans.php?copy=<?php echo (int)$row['id']; ?>&property_id=<?php echo (int)$row['property_id']; ?>" class="btn btn-sm btn-outline-secondary">Copy</a>
                                                <a href="rate_plans.php?delete=<?php echo (int)$row['id']; ?>&property_id=<?php echo (int)$propertyFilter; ?>"
                                                   class="btn btn-sm btn-outline-danger"
                                                   onclick="return confirm('Delete this rate plan?');">
                                                    Delete
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<template id="bulkRateRowTemplate">
    <tr>
        <td>
            <select name="bulk_rows[__INDEX__][room_type_id]" class="form-select form-select-sm bulk-room-type" required>
                <option value="">Select room</option>
            </select>
        </td>
        <td><input type="text" name="bulk_rows[__INDEX__][title]" class="form-control form-control-sm" required></td>
        <td>
            <select name="bulk_rows[__INDEX__][meal_plan]" class="form-select form-select-sm" required>
                <?php foreach (array_keys(roomz_meal_plans()) as $mpCode): ?>
                    <option value="<?php echo h($mpCode); ?>"><?php echo h($mpCode); ?></option>
                <?php endforeach; ?>
            </select>
        </td>
        <td>
            <select name="bulk_rows[__INDEX__][season_label]" class="form-select form-select-sm">
                <option value="">None</option>
                <?php foreach ($seasonOptions as $season): ?>
                    <option value="<?php echo h($season); ?>"><?php echo h($season); ?></option>
                <?php endforeach; ?>
            </select>
        </td>
        <td>
            <select name="bulk_rows[__INDEX__][season_color]" class="form-select form-select-sm">
                <?php foreach ($seasonColors as $color): ?>
                    <option value="<?php echo h($color); ?>" <?php echo $color === 'secondary' ? 'selected' : ''; ?>><?php echo ucfirst(h($color)); ?></option>
                <?php endforeach; ?>
            </select>
        </td>
        <td><input type="date" name="bulk_rows[__INDEX__][valid_from]" class="form-control form-control-sm" value="<?php echo h(date('Y-m-d')); ?>" required></td>
        <td><input type="date" name="bulk_rows[__INDEX__][valid_to]" class="form-control form-control-sm" value="<?php echo h(date('Y-m-d', strtotime('+1 year'))); ?>" required></td>
        <td><input type="number" step="0.01" min="0" name="bulk_rows[__INDEX__][sharing_rate]" class="form-control form-control-sm" value="0.00" required></td>
        <td><input type="number" step="0.01" min="0" name="bulk_rows[__INDEX__][single_rate]" class="form-control form-control-sm" value="0.00" required></td>
        <td><input type="number" step="0.01" min="0" name="bulk_rows[__INDEX__][single_supplement]" class="form-control form-control-sm" value="0.00" required></td>
        <td><input type="number" step="0.01" min="0" name="bulk_rows[__INDEX__][child_rate_percent]" class="form-control form-control-sm" value="50.00" required></td>
        <td><input type="text" name="bulk_rows[__INDEX__][currency]" class="form-control form-control-sm" value="USD" required></td>
        <td>
            <select name="bulk_rows[__INDEX__][status]" class="form-select form-select-sm">
                <option value="1" selected>Active</option>
                <option value="0">Inactive</option>
            </select>
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-sm btn-outline-danger removeBulkRow">&times;</button>
        </td>
    </tr>
</template>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const propertyField = document.getElementById('property_id');
    const roomTypeField = document.getElementById('room_type_id');
    const propertyFilterField = document.getElementById('property_filter');
    const roomTypeFilterField = document.getElementById('room_type_filter');

    const bulkPropertyField = document.getElementById('bulk_property_id');
    const bulkRowsBody = document.getElementById('bulkRateRows');
    const addBulkRowBtn = document.getElementById('addBulkRow');
    const bulkTpl = document.getElementById('bulkRateRowTemplate');

    let bulkIndex = 0;
    let bulkRoomTypes = [];

    async function fetchRoomTypes(propertyId) {
        if (!propertyId) return [];
        const resp = await fetch('rate_plans.php?ajax=room_types&property_id=' + encodeURIComponent(propertyId), {
            credentials: 'same-origin'
        });
        const json = await resp.json();
        return json.rows || [];
    }

    function refillSelect(selectEl, rows, firstLabel, selectedValue, firstValue) {
        if (!selectEl) return;
        selectEl.innerHTML = '';
        const first = document.createElement('option');
        first.value = firstValue;
        first.textContent = firstLabel;
        selectEl.appendChild(first);

        rows.forEach(function (row) {
            const opt = document.createElement('option');
            opt.value = row.id;
            opt.textContent = row.title + (row.shortcode ? ' - ' + row.shortcode : '');
            if (String(selectedValue) === String(row.id)) {
                opt.selected = true;
            }
            selectEl.appendChild(opt);
        });
    }

    function refillBulkRoomTypeSelect(selectEl) {
        refillSelect(selectEl, bulkRoomTypes, 'Select room', '', '');
    }

    function addBulkRow() {
        if (!bulkRowsBody || !bulkTpl) return;

        const html = bulkTpl.innerHTML.replaceAll('__INDEX__', String(bulkIndex++));
        const temp = document.createElement('tbody');
        temp.innerHTML = html.trim();
        const row = temp.firstElementChild;

        bulkRowsBody.appendChild(row);
        refillBulkRoomTypeSelect(row.querySelector('.bulk-room-type'));
    }

    async function refreshBulkRoomTypes(resetRows) {
        if (!bulkPropertyField) return;
        bulkRoomTypes = await fetchRoomTypes(bulkPropertyField.value);

        if (resetRows && bulkRowsBody) {
            bulkRowsBody.innerHTML = '';
            addBulkRow();
        } else if (bulkRowsBody) {
            bulkRowsBody.querySelectorAll('.bulk-room-type').forEach(refillBulkRoomTypeSelect);
        }
    }

    if (propertyField && roomTypeField) {
        propertyField.addEventListener('change', async function () {
            const rows = await fetchRoomTypes(this.value);
            refillSelect(roomTypeField, rows, 'Select room type', '', '');
        });
    }

    if (propertyFilterField && roomTypeFilterField) {
        propertyFilterField.addEventListener('change', async function () {
            const rows = await fetchRoomTypes(this.value);
            refillSelect(roomTypeFilterField, rows, 'All room types', '', '0');
        });
    }

    if (bulkPropertyField) {
        bulkPropertyField.addEventListener('change', function () {
            refreshBulkRoomTypes(true);
        });
        refreshBulkRoomTypes(false).then(function () {
            if (bulkRowsBody && bulkRowsBody.children.length === 0) {
                addBulkRow();
            }
        });
    }

    if (addBulkRowBtn) {
        addBulkRowBtn.addEventListener('click', addBulkRow);
    }

    if (bulkRowsBody) {
        bulkRowsBody.addEventListener('click', function (e) {
            if (e.target && e.target.classList.contains('removeBulkRow')) {
                const row = e.target.closest('tr');
                if (row) row.remove();
                if (bulkRowsBody.children.length === 0) addBulkRow();
            }
        });
    }
});
</script>

<style>
.rate-plan-bulk-wrap {
    max-height: 460px;
    overflow: auto;
}
.rate-plan-bulk-wrap table {
    min-width: 1550px;
}
.rate-plan-bulk-wrap thead th {
    position: sticky;
    top: 0;
    z-index: 2;
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
