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

$pageTitle = 'Restaurant Reservations';

if (!function_exists('h')) {
    function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($v): string { return number_format((float)$v, 2); }
}
if (!function_exists('rr_flash')) {
    function rr_flash(string $type, string $message): void {
        $_SESSION['restaurant_res_flash'][] = ['type' => $type, 'message' => $message];
    }
    function rr_get_flash(): array {
        $items = $_SESSION['restaurant_res_flash'] ?? [];
        unset($_SESSION['restaurant_res_flash']);
        return $items;
    }
}
if (!function_exists('rr_table_exists')) {
    function rr_table_exists(PDO $pdo, string $table): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :t");
        $stmt->execute([':t' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('rr_column_exists')) {
    function rr_column_exists(PDO $pdo, string $table, string $column): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = :t AND column_name = :c");
        $stmt->execute([':t' => $table, ':c' => $column]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('rr_current_user_id')) {
    function rr_current_user_id(): ?int {
        foreach (['user_id','ss_user_id','id','uid'] as $k) {
            if (isset($_SESSION[$k]) && (int)$_SESSION[$k] > 0) return (int)$_SESSION[$k];
        }
        return null;
    }
}
if (!function_exists('rr_order_no')) {
    function rr_order_no(PDO $pdo): string {
        $p = 'RST-' . date('ymd') . '-';
        $s = $pdo->prepare("SELECT COUNT(*) FROM restaurant_orders WHERE order_no LIKE :p");
        $s->execute([':p' => $p . '%']);
        return $p . str_pad((string)((int)$s->fetchColumn() + 1), 4, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('rr_csv_ids')) {
    function rr_csv_ids(array $ids): string {
        $clean = [];
        foreach ($ids as $id) {
            $id = (int)$id;
            if ($id > 0) $clean[$id] = $id;
        }
        return implode(',', array_values($clean));
    }
}
if (!function_exists('rr_parse_csv_ids')) {
    function rr_parse_csv_ids($csv): array {
        if ($csv === null || $csv === '') return [];
        $out = [];
        foreach (preg_split('/\s*,\s*/', (string)$csv) as $id) {
            $id = (int)$id;
            if ($id > 0) $out[$id] = $id;
        }
        return array_values($out);
    }
}
if (!function_exists('rr_table_ids_from_post')) {
    function rr_table_ids_from_post(): array {
        $ids = $_POST['table_ids'] ?? [];
        if (!is_array($ids)) $ids = [$ids];
        $single = (int)($_POST['table_id'] ?? 0);
        if ($single > 0) $ids[] = $single;
        $clean = [];
        foreach ($ids as $id) {
            $id = (int)$id;
            if ($id > 0) $clean[$id] = $id;
        }
        return array_values($clean);
    }
}
if (!function_exists('rr_fetch_tables_meta')) {
    function rr_fetch_tables_meta(PDO $pdo, array $tableIds): array {
        $tableIds = array_values(array_unique(array_map('intval', $tableIds)));
        $tableIds = array_filter($tableIds, fn($id) => $id > 0);
        if (!$tableIds) return [];
        $in = implode(',', array_fill(0, count($tableIds), '?'));
        $stmt = $pdo->prepare("
            SELECT t.*, a.area_name
            FROM restaurant_tables t
            LEFT JOIN restaurant_areas a ON a.id = t.area_id
            WHERE t.id IN ($in) AND t.is_active = 1
            ORDER BY a.sort_order, t.table_no
        ");
        $stmt->execute($tableIds);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
}
if (!function_exists('rr_tables_label')) {
    function rr_tables_label(array $tableRows): string {
        $labels = [];
        foreach ($tableRows as $t) {
            $labels[] = trim('Table ' . (string)($t['table_no'] ?? ''));
        }
        return implode(' + ', array_filter($labels));
    }
}
if (!function_exists('rr_tables_capacity')) {
    function rr_tables_capacity(array $tableRows): int {
        $seats = 0;
        foreach ($tableRows as $t) $seats += max(0, (int)($t['seats'] ?? 0));
        return $seats;
    }
}
if (!function_exists('rr_reservation_table_ids')) {
    function rr_reservation_table_ids(array $reservation): array {
        $ids = rr_parse_csv_ids($reservation['merged_table_ids'] ?? '');
        $primary = (int)($reservation['table_id'] ?? 0);
        if ($primary > 0) $ids[$primary] = $primary;
        return array_values(array_unique(array_map('intval', $ids)));
    }
}
if (!function_exists('rr_validate_table_combo')) {
    function rr_validate_table_combo(PDO $pdo, array $tableIds, int $covers, string $date, string $time, int $duration, int $excludeReservationId = 0): array {
        if (!$tableIds) {
            return ['primary_table_id' => null, 'merged_table_ids' => '', 'capacity' => 0, 'label' => 'Assign later', 'rows' => []];
        }

        $tableRows = rr_fetch_tables_meta($pdo, $tableIds);
        if (count($tableRows) !== count(array_unique($tableIds))) {
            throw new RuntimeException('One or more selected tables were not found or are inactive.');
        }

        $capacity = rr_tables_capacity($tableRows);
        if ($covers > $capacity) {
            throw new RuntimeException('Covers exceed combined table capacity of ' . $capacity . ' seats.');
        }

        $selectedSet = array_fill_keys(array_map('intval', $tableIds), true);
        // Important: use unique named placeholders. Reusing :new_time caused SQLSTATE[HY093]
        // only when table validation ran during reservation save.
        $stmt = $pdo->prepare("
            SELECT id, table_id, merged_table_ids, guest_name, reservation_time, duration_minutes
            FROM restaurant_reservations
            WHERE reservation_date = :reservation_date
              AND status IN ('booked','seated')
              AND id <> :exclude_id
              AND (
                  reservation_time < ADDTIME(:new_time_start, SEC_TO_TIME(:duration_minutes * 60))
                  AND ADDTIME(reservation_time, SEC_TO_TIME(duration_minutes * 60)) > :new_time_end
              )
        ");
        $stmt->execute([
            ':reservation_date' => $date,
            ':new_time_start' => $time,
            ':new_time_end' => $time,
            ':duration_minutes' => $duration,
            ':exclude_id' => $excludeReservationId,
        ]);

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $existingIds = rr_reservation_table_ids($row);
            foreach ($existingIds as $existingId) {
                if (isset($selectedSet[(int)$existingId])) {
                    throw new RuntimeException(
                        'Table already reserved during this time window by ' .
                        trim((string)($row['guest_name'] ?? 'another booking')) . '.'
                    );
                }
            }
        }

        $primary = (int)$tableIds[0];
        return [
            'primary_table_id' => $primary,
            'merged_table_ids' => rr_csv_ids($tableIds),
            'capacity' => $capacity,
            'label' => rr_tables_label($tableRows),
            'rows' => $tableRows,
        ];
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_areas (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        property_id INT UNSIGNED NULL,
        area_name VARCHAR(120) NOT NULL,
        sort_order INT NOT NULL DEFAULT 1,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_tables (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        property_id INT UNSIGNED NULL,
        area_id INT UNSIGNED NULL,
        table_no VARCHAR(40) NOT NULL,
        table_name VARCHAR(120) NULL,
        seats INT UNSIGNED NOT NULL DEFAULT 2,
        pos_x INT NOT NULL DEFAULT 0,
        pos_y INT NOT NULL DEFAULT 0,
        shape ENUM('round','square','rect') NOT NULL DEFAULT 'round',
        orientation ENUM('horizontal','vertical') NOT NULL DEFAULT 'horizontal',
        status ENUM('available','occupied','reserved','dirty','blocked') NOT NULL DEFAULT 'available',
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_rest_table_area(area_id),
        INDEX idx_rest_table_status(status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_orders (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        property_id INT UNSIGNED NULL,
        area_id INT UNSIGNED NULL,
        table_id INT UNSIGNED NULL,
        order_no VARCHAR(60) NOT NULL,
        order_type ENUM('table','room','walkin','takeaway') NOT NULL DEFAULT 'table',
        linked_order_id INT UNSIGNED NULL,
        linked_folio_id INT UNSIGNED NULL,
        guest_name VARCHAR(180) NULL,
        room_no VARCHAR(80) NULL,
        covers INT UNSIGNED NOT NULL DEFAULT 1,
        status ENUM('open','sent','closed','void') NOT NULL DEFAULT 'open',
        subtotal DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        tax_total DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        total_amount DECIMAL(14,2) NOT NULL DEFAULT 0.00,
        payment_status ENUM('unpaid','part_paid','paid','room_charged','void') NOT NULL DEFAULT 'unpaid',
        opened_by INT UNSIGNED NULL,
        closed_by INT UNSIGNED NULL,
        opened_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        closed_at DATETIME NULL,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_rest_order_no(order_no),
        INDEX idx_rest_order_table_status(table_id,status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_reservations (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        property_id INT UNSIGNED NULL,
        restaurant_area_id INT UNSIGNED NULL,
        table_id INT UNSIGNED NULL,
        order_id INT UNSIGNED NULL,
        guest_id INT UNSIGNED NULL,
        room_no VARCHAR(80) NULL,
        guest_name VARCHAR(180) NOT NULL,
        reservation_date DATE NOT NULL,
        reservation_time TIME NOT NULL,
        duration_minutes INT UNSIGNED NOT NULL DEFAULT 90,
        covers INT UNSIGNED NOT NULL DEFAULT 1,
        meal_period ENUM('breakfast','lunch','dinner','other') NOT NULL DEFAULT 'dinner',
        source ENUM('room_guest','walkin','external') NOT NULL DEFAULT 'room_guest',
        status ENUM('booked','seated','no_show','cancelled','completed') NOT NULL DEFAULT 'booked',
        notes TEXT NULL,
        restaurant_order_id BIGINT UNSIGNED NULL,
        created_by INT UNSIGNED NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_rest_res_date_time (reservation_date, reservation_time),
        INDEX idx_rest_res_table (table_id, reservation_date, reservation_time),
        INDEX idx_rest_res_order (order_id),
        INDEX idx_rest_res_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $neededCols = [
        'restaurant_order_id' => "ALTER TABLE restaurant_reservations ADD COLUMN restaurant_order_id BIGINT UNSIGNED NULL AFTER notes",
        'created_by' => "ALTER TABLE restaurant_reservations ADD COLUMN created_by INT UNSIGNED NULL AFTER restaurant_order_id",
        'merged_table_ids' => "ALTER TABLE restaurant_reservations ADD COLUMN merged_table_ids VARCHAR(255) NULL AFTER table_id",
        'merged_capacity' => "ALTER TABLE restaurant_reservations ADD COLUMN merged_capacity INT UNSIGNED NOT NULL DEFAULT 0 AFTER merged_table_ids",
    ];
    foreach ($neededCols as $col => $sql) {
        if (!rr_column_exists($pdo, 'restaurant_reservations', $col)) $pdo->exec($sql);
    }

    $orderNeededCols = [
        'merged_table_ids' => "ALTER TABLE restaurant_orders ADD COLUMN merged_table_ids VARCHAR(255) NULL AFTER table_id",
        'merged_capacity' => "ALTER TABLE restaurant_orders ADD COLUMN merged_capacity INT UNSIGNED NOT NULL DEFAULT 0 AFTER merged_table_ids",
    ];
    foreach ($orderNeededCols as $col => $sql) {
        if (!rr_column_exists($pdo, 'restaurant_orders', $col)) $pdo->exec($sql);
    }
} catch (Throwable $e) {
    $errors[] = 'Could not prepare restaurant reservation tables: ' . $e->getMessage();
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        if (function_exists('verify_csrf')) verify_csrf();
        $action = (string)($_POST['action'] ?? '');

        if ($action === 'save_reservation') {
            $id = (int)($_POST['id'] ?? 0);
            $propertyId = (int)($_POST['property_id'] ?? 0) ?: null;
            $areaId = (int)($_POST['restaurant_area_id'] ?? 0) ?: null;
            $tableIds = rr_table_ids_from_post();
            $tableId = $tableIds ? (int)$tableIds[0] : null;
            $orderId = (int)($_POST['order_id'] ?? 0) ?: null;
            $guestId = (int)($_POST['guest_id'] ?? 0) ?: null;
            $roomNo = trim((string)($_POST['room_no'] ?? '')) ?: null;
            $guestName = trim((string)($_POST['guest_name'] ?? ''));
            $date = trim((string)($_POST['reservation_date'] ?? date('Y-m-d')));
            $time = trim((string)($_POST['reservation_time'] ?? '19:00'));
            $duration = max(15, (int)($_POST['duration_minutes'] ?? 90));
            $covers = max(1, (int)($_POST['covers'] ?? 1));
            $meal = strtolower(trim((string)($_POST['meal_period'] ?? 'dinner')));
            $source = strtolower(trim((string)($_POST['source'] ?? 'room_guest')));
            $status = strtolower(trim((string)($_POST['status'] ?? 'booked')));
            $notes = trim((string)($_POST['notes'] ?? '')) ?: null;

            if ($guestName === '') throw new RuntimeException('Guest/customer name is required.');
            if (strtotime($date) === false) throw new RuntimeException('Invalid reservation date.');
            if (strtotime($time) === false) throw new RuntimeException('Invalid reservation time.');
            if (!in_array($meal, ['breakfast','lunch','dinner','other'], true)) $meal = 'dinner';
            if (!in_array($source, ['room_guest','walkin','external'], true)) $source = 'room_guest';
            if (!in_array($status, ['booked','seated','no_show','cancelled','completed'], true)) $status = 'booked';

            $tableCombo = rr_validate_table_combo($pdo, $tableIds, $covers, $date, date('H:i:s', strtotime($time)), $duration, $id);
            $tableId = $tableCombo['primary_table_id'];
            $mergedTableIds = $tableCombo['merged_table_ids'];
            $mergedCapacity = (int)$tableCombo['capacity'];

            $params = [
                ':property_id' => $propertyId,
                ':restaurant_area_id' => $areaId,
                ':table_id' => $tableId,
                ':merged_table_ids' => $mergedTableIds,
                ':merged_capacity' => $mergedCapacity,
                ':order_id' => $orderId,
                ':guest_id' => $guestId,
                ':room_no' => $roomNo,
                ':guest_name' => $guestName,
                ':reservation_date' => $date,
                ':reservation_time' => date('H:i:s', strtotime($time)),
                ':duration_minutes' => $duration,
                ':covers' => $covers,
                ':meal_period' => $meal,
                ':source' => $source,
                ':status' => $status,
                ':notes' => $notes,
            ];

            if ($id > 0) {
                $params[':id'] = $id;
                $pdo->prepare("
                    UPDATE restaurant_reservations
                    SET property_id=:property_id,
                        restaurant_area_id=:restaurant_area_id,
                        table_id=:table_id,
                        merged_table_ids=:merged_table_ids,
                        merged_capacity=:merged_capacity,
                        order_id=:order_id,
                        guest_id=:guest_id,
                        room_no=:room_no,
                        guest_name=:guest_name,
                        reservation_date=:reservation_date,
                        reservation_time=:reservation_time,
                        duration_minutes=:duration_minutes,
                        covers=:covers,
                        meal_period=:meal_period,
                        source=:source,
                        status=:status,
                        notes=:notes
                    WHERE id=:id
                ")->execute($params);
            } else {
                $params[':created_by'] = rr_current_user_id();
                $pdo->prepare("
                    INSERT INTO restaurant_reservations
                    (property_id, restaurant_area_id, table_id, merged_table_ids, merged_capacity, order_id, guest_id, room_no, guest_name,
                     reservation_date, reservation_time, duration_minutes, covers, meal_period, source, status, notes, created_by)
                    VALUES
                    (:property_id, :restaurant_area_id, :table_id, :merged_table_ids, :merged_capacity, :order_id, :guest_id, :room_no, :guest_name,
                     :reservation_date, :reservation_time, :duration_minutes, :covers, :meal_period, :source, :status, :notes, :created_by)
                ")->execute($params);
            }

            rr_flash('success', 'Restaurant reservation saved successfully.');
            header('Location: reservations.php?reservation_date=' . urlencode($date));
            exit;
        }

        if ($action === 'update_status') {
            $id = (int)($_POST['id'] ?? 0);
            $status = strtolower(trim((string)($_POST['status'] ?? '')));
            if ($id <= 0) throw new RuntimeException('Invalid reservation selected.');
            if (!in_array($status, ['booked','seated','no_show','cancelled','completed'], true)) {
                throw new RuntimeException('Invalid status selected.');
            }
            $pdo->prepare("UPDATE restaurant_reservations SET status=:status WHERE id=:id")
                ->execute([':status' => $status, ':id' => $id]);
            rr_flash('success', 'Reservation status updated.');
            header('Location: reservations.php?' . http_build_query($_GET));
            exit;
        }

        if ($action === 'seat_reservation') {
            $id = (int)($_POST['id'] ?? 0);
            if ($id <= 0) throw new RuntimeException('Invalid reservation selected.');

            $stmt = $pdo->prepare("SELECT * FROM restaurant_reservations WHERE id=:id LIMIT 1 FOR UPDATE");
            $pdo->beginTransaction();
            $stmt->execute([':id' => $id]);
            $res = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$res) throw new RuntimeException('Restaurant reservation not found.');
            if (in_array((string)$res['status'], ['cancelled','no_show','completed'], true)) {
                throw new RuntimeException('This reservation cannot be seated because it is ' . $res['status'] . '.');
            }
            $seatTableIds = rr_reservation_table_ids($res);
            if (!$seatTableIds) throw new RuntimeException('Assign at least one table before seating this reservation.');

            $in = implode(',', array_fill(0, count($seatTableIds), '?'));
            $stmt = $pdo->prepare("
                SELECT id
                FROM restaurant_orders
                WHERE status IN ('open','sent')
                  AND (
                      table_id IN ($in)
                      OR " . (rr_column_exists($pdo, 'restaurant_orders', 'merged_table_ids')
                          ? implode(' OR ', array_fill(0, count($seatTableIds), "FIND_IN_SET(?, merged_table_ids)"))
                          : "0=1") . "
                  )
                LIMIT 1
            ");
            $paramsOpen = array_merge($seatTableIds, rr_column_exists($pdo, 'restaurant_orders', 'merged_table_ids') ? $seatTableIds : []);
            $stmt->execute($paramsOpen);
            $existingOrderId = (int)$stmt->fetchColumn();
            if ($existingOrderId > 0) {
                throw new RuntimeException('One of the selected/merged tables already has an open restaurant order.');
            }

            $orderType = ((string)$res['source'] === 'room_guest') ? 'room' : 'walkin';
            $pdo->prepare("
                INSERT INTO restaurant_orders
                (property_id, area_id, table_id, merged_table_ids, merged_capacity, order_no, order_type, linked_order_id, guest_name, room_no, covers, status, opened_by)
                VALUES
                (:property_id, :area_id, :table_id, :merged_table_ids, :merged_capacity, :order_no, :order_type, :linked_order_id, :guest_name, :room_no, :covers, 'open', :opened_by)
            ")->execute([
                ':property_id' => $res['property_id'] ?: null,
                ':area_id' => $res['restaurant_area_id'] ?: null,
                ':table_id' => (int)$seatTableIds[0],
                ':merged_table_ids' => rr_csv_ids($seatTableIds),
                ':merged_capacity' => (int)($res['merged_capacity'] ?? 0),
                ':order_no' => rr_order_no($pdo),
                ':order_type' => $orderType,
                ':linked_order_id' => $res['order_id'] ?: null,
                ':guest_name' => $res['guest_name'],
                ':room_no' => $orderType === 'room' ? ($res['room_no'] ?: null) : null,
                ':covers' => max(1, (int)$res['covers']),
                ':opened_by' => rr_current_user_id(),
            ]);
            $restaurantOrderId = (int)$pdo->lastInsertId();

            $pdo->prepare("UPDATE restaurant_reservations SET status='seated', restaurant_order_id=:rid WHERE id=:id")
                ->execute([':rid' => $restaurantOrderId, ':id' => $id]);
            $inUpdate = implode(',', array_fill(0, count($seatTableIds), '?'));
            $updTables = $pdo->prepare("UPDATE restaurant_tables SET status='occupied' WHERE id IN ($inUpdate)");
            $updTables->execute($seatTableIds);
            $pdo->commit();

            rr_flash('success', 'Guest seated and restaurant order opened.');
            header('Location: planner.php?restaurant_order_id=' . $restaurantOrderId);
            exit;
        }

    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        rr_flash('danger', $e->getMessage());
        header('Location: reservations.php?' . http_build_query($_GET));
        exit;
    }
}

$today = date('Y-m-d');
$selectedDate = trim((string)($_GET['reservation_date'] ?? $today));
$propertyId = (int)($_GET['property_id'] ?? 0);
$statusFilter = trim((string)($_GET['status'] ?? ''));
$search = trim((string)($_GET['q'] ?? ''));
if (strtotime($selectedDate) === false) $selectedDate = $today;

$flashes = rr_get_flash();
$properties = [];
$areas = [];
$tables = [];
$inhouseGuests = [];
$reservations = [];
$editReservation = null;

try {
    if (rr_table_exists($pdo, 'properties')) {
        $properties = $pdo->query("SELECT id, name, code FROM properties WHERE COALESCE(is_active,1)=1 ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
    }
    $areas = $pdo->query("SELECT * FROM restaurant_areas WHERE is_active=1 ORDER BY sort_order, area_name")->fetchAll(PDO::FETCH_ASSOC);
    $tables = $pdo->query("
        SELECT t.*, a.area_name
        FROM restaurant_tables t
        LEFT JOIN restaurant_areas a ON a.id=t.area_id
        WHERE t.is_active=1
        ORDER BY a.sort_order, t.table_no
    ")->fetchAll(PDO::FETCH_ASSOC);

if (rr_table_exists($pdo, 'orders')) {
    if (rr_table_exists($pdo, 'order_rooming')) {
        $inhouseGuests = $pdo->query("
            SELECT DISTINCT
                o.id AS order_id,
                o.guest_id,
                o.order_no,
                CONCAT(COALESCE(g.firstname,''),' ',COALESCE(g.lastname,'')) AS guest_name,
                COALESCE(rmg.room_no, rm.room_no, '') AS room_no,
                COALESCE(rmg.check_in, o.check_in) AS check_in,
                COALESCE(rmg.check_out, o.check_out) AS check_out,
                p.name AS property_name,
                o.property_id
            FROM orders o
            LEFT JOIN guests g ON g.id = o.guest_id
            LEFT JOIN order_rooming rmg ON rmg.order_id = o.id
            LEFT JOIN rooms rm ON rm.id = rmg.room_id
            LEFT JOIN properties p ON p.id = o.property_id
            WHERE COALESCE(o.status,1) NOT IN (0,4)
              AND DATE(COALESCE(rmg.check_in,o.check_in)) <= CURDATE()
              AND DATE(COALESCE(rmg.check_out,o.check_out)) > CURDATE()
            ORDER BY room_no ASC, guest_name ASC
            LIMIT 350
        ")->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $inhouseGuests = $pdo->query("
            SELECT
                o.id AS order_id,
                o.guest_id,
                o.order_no,
                CONCAT(COALESCE(g.firstname,''),' ',COALESCE(g.lastname,'')) AS guest_name,
                '' AS room_no,
                o.check_in,
                o.check_out,
                p.name AS property_name,
                o.property_id
            FROM orders o
            LEFT JOIN guests g ON g.id = o.guest_id
            LEFT JOIN properties p ON p.id = o.property_id
            WHERE COALESCE(o.status,1) NOT IN (0,4)
              AND DATE(o.check_in) <= CURDATE()
              AND DATE(o.check_out) > CURDATE()
            ORDER BY guest_name ASC
            LIMIT 350
        ")->fetchAll(PDO::FETCH_ASSOC);
    }
}
} catch (Throwable $e) {
    $errors[] = 'Could not load setup data: ' . $e->getMessage();
}

$editId = (int)($_GET['edit_id'] ?? 0);
if ($editId > 0) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM restaurant_reservations WHERE id=:id LIMIT 1");
        $stmt->execute([':id' => $editId]);
        $editReservation = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (Throwable $e) {
        $errors[] = 'Could not load reservation for editing: ' . $e->getMessage();
    }
}

try {
    $where = "rr.reservation_date = :reservation_date";
    $params = [':reservation_date' => $selectedDate];
    if ($propertyId > 0) {
        $where .= " AND rr.property_id = :property_id";
        $params[':property_id'] = $propertyId;
    }
    if ($statusFilter !== '') {
        $where .= " AND rr.status = :status";
        $params[':status'] = $statusFilter;
    }
    if ($search !== '') {
        $where .= " AND (rr.guest_name LIKE :q OR rr.room_no LIKE :q OR o.order_no LIKE :q OR t.table_no LIKE :q OR t.table_name LIKE :q)";
        $params[':q'] = '%' . $search . '%';
    }

    $stmt = $pdo->prepare("
        SELECT
            rr.*,
            p.name AS property_name,
            p.code AS property_code,
            a.area_name,
            t.table_no,
            t.table_name,
            t.seats,
            o.order_no,
            ro.order_no AS restaurant_order_no,
            ro.status AS restaurant_order_status
        FROM restaurant_reservations rr
        LEFT JOIN properties p ON p.id=rr.property_id
        LEFT JOIN restaurant_areas a ON a.id=rr.restaurant_area_id
        LEFT JOIN restaurant_tables t ON t.id=rr.table_id
        LEFT JOIN orders o ON o.id=rr.order_id
        LEFT JOIN restaurant_orders ro ON ro.id=rr.restaurant_order_id
        WHERE $where
        ORDER BY rr.reservation_time ASC, rr.id ASC
    ");
    $stmt->execute($params);
    $reservations = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = 'Could not load restaurant reservations: ' . $e->getMessage();
}

$stats = ['booked'=>0,'seated'=>0,'no_show'=>0,'cancelled'=>0,'completed'=>0,'covers'=>0];
foreach ($reservations as $r) {
    $st = (string)($r['status'] ?? 'booked');
    if (isset($stats[$st])) $stats[$st]++;
    if (!in_array($st, ['cancelled','no_show'], true)) $stats['covers'] += (int)($r['covers'] ?? 0);
}

$fv = function(string $key, $default = '') use ($editReservation) {
    if ($editReservation && array_key_exists($key, $editReservation)) return $editReservation[$key];
    return $default;
};

$editTableIds = [];
if ($editReservation) {
    $editTableIds = rr_reservation_table_ids($editReservation);
}
if (!$editTableIds && (int)$fv('table_id', 0) > 0) {
    $editTableIds = [(int)$fv('table_id', 0)];
}
$editTableIdSet = array_fill_keys($editTableIds, true);

foreach ($reservations as &$reservationRow) {
    $ids = rr_reservation_table_ids($reservationRow);
    $rows = rr_fetch_tables_meta($pdo, $ids);
    $reservationRow['_table_label'] = $rows ? rr_tables_label($rows) : '';
    $reservationRow['_merged_capacity'] = $rows ? rr_tables_capacity($rows) : (int)($reservationRow['merged_capacity'] ?? 0);
}
unset($reservationRow);

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

<div class="hero-band compact-restaurant-hero">
    <div class="row align-items-center g-2">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-calendar2-check"></i> Restaurant Reservations</div>
            <div class="hero-title mt-1">Table Bookings</div>
            <div class="hero-subtitle mt-1">Book restaurant tables for lodge guests, walk-ins and external visitors.</div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <a href="planner.php" class="btn btn-light btn-sm"><i class="bi bi-grid-3x3-gap me-1"></i>Planner</a>
            <a href="restaurant_tables.php" class="btn btn-outline-light btn-sm"><i class="bi bi-table me-1"></i>Tables</a>
            <a href="menu.php" class="btn btn-outline-light btn-sm"><i class="bi bi-journal-text me-1"></i>Menu</a>
        </div>
    </div>
</div>

<?php foreach ($flashes as $f): ?>
    <div class="alert alert-<?php echo h($f['type']); ?> py-2"><?php echo h($f['message']); ?></div>
<?php endforeach; ?>

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

<div class="row g-2 mb-3 restaurant-res-metrics">
    <div class="col-md-2"><div class="res-metric"><span>Booked</span><strong><?php echo (int)$stats['booked']; ?></strong></div></div>
    <div class="col-md-2"><div class="res-metric"><span>Seated</span><strong><?php echo (int)$stats['seated']; ?></strong></div></div>
    <div class="col-md-2"><div class="res-metric"><span>Completed</span><strong><?php echo (int)$stats['completed']; ?></strong></div></div>
    <div class="col-md-2"><div class="res-metric"><span>No Show</span><strong><?php echo (int)$stats['no_show']; ?></strong></div></div>
    <div class="col-md-2"><div class="res-metric"><span>Cancelled</span><strong><?php echo (int)$stats['cancelled']; ?></strong></div></div>
    <div class="col-md-2"><div class="res-metric"><span>Covers</span><strong><?php echo (int)$stats['covers']; ?></strong></div></div>
</div>

<div class="row g-3">
    <div class="col-xl-4">
        <div class="card panel-card reservation-form-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><?php echo $editReservation ? 'Edit Reservation' : 'New Reservation'; ?></h5>
                <?php if ($editReservation): ?>
                    <a href="reservations.php?reservation_date=<?php echo h($selectedDate); ?>" class="btn btn-sm btn-outline-secondary">New</a>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <form method="post" id="restaurantReservationForm">
                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                    <input type="hidden" name="action" value="save_reservation">
                    <input type="hidden" name="id" value="<?php echo (int)$fv('id', 0); ?>">
                    <input type="hidden" name="guest_id" id="guestId" value="<?php echo h($fv('guest_id', '')); ?>">
                    <input type="hidden" name="order_id" id="orderId" value="<?php echo h($fv('order_id', '')); ?>">
                    <input type="hidden" name="room_no" id="roomNoHidden" value="<?php echo h($fv('room_no', '')); ?>">

                    <div class="row g-2">
                        <div class="col-md-6">
                            <label class="form-label">Date</label>
                            <input type="date" name="reservation_date" class="form-control" value="<?php echo h($fv('reservation_date', $selectedDate)); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Time</label>
                            <input type="time" name="reservation_time" class="form-control" value="<?php echo h(substr((string)$fv('reservation_time', '19:00'), 0, 5)); ?>" required>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Meal Period</label>
                            <select name="meal_period" class="form-select">
                                <?php foreach (['breakfast'=>'Breakfast','lunch'=>'Lunch','dinner'=>'Dinner','other'=>'Other'] as $k=>$v): ?>
                                    <option value="<?php echo h($k); ?>" <?php echo (string)$fv('meal_period','dinner') === $k ? 'selected' : ''; ?>><?php echo h($v); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Duration</label>
                            <select name="duration_minutes" class="form-select">
                                <?php foreach ([30,45,60,75,90,120,150,180] as $mins): ?>
                                    <option value="<?php echo $mins; ?>" <?php echo (int)$fv('duration_minutes',90) === $mins ? 'selected' : ''; ?>><?php echo $mins; ?> minutes</option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Source</label>
                            <select name="source" id="reservationSource" class="form-select">
                                <option value="room_guest" <?php echo (string)$fv('source','room_guest')==='room_guest'?'selected':''; ?>>Room Guest</option>
                                <option value="walkin" <?php echo (string)$fv('source','room_guest')==='walkin'?'selected':''; ?>>Walk-in</option>
                                <option value="external" <?php echo (string)$fv('source','room_guest')==='external'?'selected':''; ?>>External</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Covers</label>
                            <input type="number" name="covers" class="form-control" min="1" value="<?php echo h($fv('covers', 2)); ?>" required>
                        </div>

                        <div class="col-12 room-guest-row">
                            <label class="form-label">In-house Guest / Room</label>
                            <select id="inhouseGuestSelect" class="form-select">
                                <option value="">Select in-house guest</option>
                                <?php foreach ($inhouseGuests as $ig): ?>
                                    <?php
                                        $gname = trim((string)($ig['guest_name'] ?? '')) ?: 'Guest';
                                        $room = trim((string)($ig['room_no'] ?? ''));
                                        $label = ($room !== '' ? 'Room ' . $room . ' • ' : '') . $gname . ' • ' . (($ig['order_no'] ?? '') ?: '#' . $ig['order_id']);
                                    ?>
                                    <option value="<?php echo (int)$ig['order_id']; ?>"
                                            data-guest-id="<?php echo (int)($ig['guest_id'] ?? 0); ?>"
                                            data-guest="<?php echo h($gname); ?>"
                                            data-room="<?php echo h($room); ?>"
                                            data-property-id="<?php echo (int)($ig['property_id'] ?? 0); ?>"
                                            <?php echo (int)$fv('order_id',0)===(int)$ig['order_id'] ? 'selected' : ''; ?>>
                                        <?php echo h($label); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text">Choosing a room guest fills guest, room and property automatically.</div>
                        </div>

                        <div class="col-md-8">
                            <label class="form-label">Guest / Customer Name</label>
                            <input type="text" name="guest_name" id="guestName" class="form-control" value="<?php echo h($fv('guest_name', '')); ?>" required>
                        </div>
                        <div class="col-md-4 room-display-row">
                            <label class="form-label">Room</label>
                            <input type="text" id="roomNoDisplay" class="form-control" value="<?php echo h($fv('room_no', '')); ?>" readonly>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Property</label>
                            <select name="property_id" id="propertyId" class="form-select">
                                <option value="">Not set</option>
                                <?php foreach ($properties as $p): ?>
                                    <option value="<?php echo (int)$p['id']; ?>" <?php echo (int)$fv('property_id',0)===(int)$p['id'] ? 'selected' : ''; ?>>
                                        <?php echo h($p['name']); ?><?php echo !empty($p['code']) ? ' - ' . h($p['code']) : ''; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <?php foreach (['booked','seated','completed','no_show','cancelled'] as $st): ?>
                                    <option value="<?php echo h($st); ?>" <?php echo (string)$fv('status','booked')===$st ? 'selected' : ''; ?>><?php echo h(ucwords(str_replace('_',' ', $st))); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Area</label>
                            <select name="restaurant_area_id" id="areaId" class="form-select">
                                <option value="">Any Area</option>
                                <?php foreach ($areas as $a): ?>
                                    <option value="<?php echo (int)$a['id']; ?>" <?php echo (int)$fv('restaurant_area_id',0)===(int)$a['id'] ? 'selected' : ''; ?>><?php echo h($a['area_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Table</label>
                            <select name="table_ids[]" id="tableId" class="form-select" multiple size="5">
                                <?php foreach ($tables as $t): ?>
                                    <?php $tid = (int)$t['id']; ?>
                                    <option value="<?php echo $tid; ?>"
                                            data-area-id="<?php echo (int)($t['area_id'] ?? 0); ?>"
                                            data-seats="<?php echo (int)$t['seats']; ?>"
                                            <?php echo isset($editTableIdSet[$tid]) ? 'selected' : ''; ?>>
                                        <?php echo h(($t['area_name'] ? $t['area_name'] . ' • ' : '') . 'Table ' . $t['table_no'] . ' (' . (int)$t['seats'] . ' seats)'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text">Hold Ctrl/Cmd to select and combine more than one table. Capacity is added together.</div>
                            <div class="small mt-1 fw-bold" id="combinedCapacityHint"></div>
                        </div>

                        <div class="col-12">
                            <label class="form-label">Notes</label>
                            <textarea name="notes" class="form-control" rows="2" placeholder="Dietary requirements, celebration, preferred table..."><?php echo h($fv('notes', '')); ?></textarea>
                        </div>
                    </div>

                    <button class="btn btn-primary w-100 mt-3"><i class="bi bi-save me-1"></i>Save Reservation</button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-8">
        <div class="card panel-card mb-3 compact-filter-card">
            <div class="card-body p-2">
                <form method="get" class="row g-2 align-items-end">
                    <div class="col-md-3">
                        <label class="form-label">Date</label>
                        <input type="date" name="reservation_date" class="form-control" value="<?php echo h($selectedDate); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Property</label>
                        <select name="property_id" class="form-select">
                            <option value="0">All</option>
                            <?php foreach ($properties as $p): ?>
                                <option value="<?php echo (int)$p['id']; ?>" <?php echo $propertyId === (int)$p['id'] ? 'selected' : ''; ?>><?php echo h($p['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All</option>
                            <?php foreach (['booked','seated','completed','no_show','cancelled'] as $st): ?>
                                <option value="<?php echo h($st); ?>" <?php echo $statusFilter === $st ? 'selected' : ''; ?>><?php echo h(ucwords(str_replace('_',' ', $st))); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Search</label>
                        <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Guest, room, table...">
                    </div>
                    <div class="col-md-1 d-grid"><button class="btn btn-primary">Go</button></div>
                </form>
            </div>
        </div>

        <div class="card panel-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="mb-0">Reservations</h5>
                    <small><?php echo h($selectedDate); ?> table bookings</small>
                </div>
                <a href="planner.php" class="btn btn-sm btn-outline-primary"><i class="bi bi-grid-3x3-gap me-1"></i>Open Planner</a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive reservation-table-wrap">
                    <table class="table table-modern align-middle mb-0">
                        <thead>
                        <tr>
                            <th>Time</th>
                            <th>Guest</th>
                            <th>Table</th>
                            <th>Covers</th>
                            <th>Status</th>
                            <th>Source</th>
                            <th class="text-end">Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php if (!$reservations): ?>
                            <tr><td colspan="7" class="text-center text-muted py-5">No restaurant reservations found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($reservations as $r): ?>
                                <?php
                                    $status = (string)$r['status'];
                                    $badge = 'secondary';
                                    if ($status === 'booked') $badge = 'primary';
                                    if ($status === 'seated') $badge = 'warning';
                                    if ($status === 'completed') $badge = 'success';
                                    if ($status === 'cancelled' || $status === 'no_show') $badge = 'danger';
                                ?>
                                <tr>
                                    <td>
                                        <strong><?php echo h(substr((string)$r['reservation_time'],0,5)); ?></strong>
                                        <div class="small text-muted"><?php echo (int)$r['duration_minutes']; ?> min • <?php echo h(ucfirst($r['meal_period'])); ?></div>
                                    </td>
                                    <td>
                                        <strong><?php echo h($r['guest_name']); ?></strong>
                                        <?php if (!empty($r['room_no'])): ?><div class="small text-muted">Room <?php echo h($r['room_no']); ?></div><?php endif; ?>
                                        <?php if (!empty($r['order_no'])): ?><div class="small text-muted">Booking <?php echo h($r['order_no']); ?></div><?php endif; ?>
                                        <?php if (!empty($r['property_name'])): ?><div class="small text-muted"><?php echo h($r['property_name']); ?></div><?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($r['_table_label'])): ?>
                                            <strong><?php echo h($r['_table_label']); ?></strong>
                                            <div class="small text-muted"><?php echo h($r['area_name'] ?: 'Combined / selected tables'); ?> • <?php echo (int)$r['_merged_capacity']; ?> seats capacity</div>
                                        <?php elseif (!empty($r['table_no'])): ?>
                                            <strong><?php echo h('Table ' . $r['table_no']); ?></strong>
                                            <div class="small text-muted"><?php echo h($r['area_name'] ?: 'No area'); ?> • <?php echo (int)$r['seats']; ?> seats</div>
                                        <?php else: ?>
                                            <span class="text-muted">Assign later</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo (int)$r['covers']; ?></td>
                                    <td><span class="badge text-bg-<?php echo h($badge); ?>"><?php echo h(ucwords(str_replace('_',' ', $status))); ?></span></td>
                                    <td><?php echo h(ucwords(str_replace('_',' ', (string)$r['source']))); ?></td>
                                    <td class="text-end">
                                        <div class="d-inline-flex gap-1 flex-wrap justify-content-end">
                                            <a class="btn btn-sm btn-outline-primary" href="reservations.php?reservation_date=<?php echo h($selectedDate); ?>&edit_id=<?php echo (int)$r['id']; ?>">Edit</a>
                                            <?php if ($status === 'booked'): ?>
                                                <form method="post" class="d-inline" onsubmit="return confirm('Seat this reservation and open restaurant order?');">
                                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                    <input type="hidden" name="action" value="seat_reservation">
                                                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                                                    <button class="btn btn-sm btn-success">Seat</button>
                                                </form>
                                                <form method="post" class="d-inline">
                                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                    <input type="hidden" name="action" value="update_status">
                                                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                                                    <input type="hidden" name="status" value="no_show">
                                                    <button class="btn btn-sm btn-outline-danger">No Show</button>
                                                </form>
                                            <?php endif; ?>
                                            <?php if (!empty($r['restaurant_order_id'])): ?>
                                                <a class="btn btn-sm btn-outline-dark" href="planner.php?restaurant_order_id=<?php echo (int)$r['restaurant_order_id']; ?>">Order</a>
                                            <?php endif; ?>
                                            <?php if ($status !== 'cancelled' && $status !== 'completed'): ?>
                                                <form method="post" class="d-inline">
                                                    <?php if (function_exists('csrf_field')) echo csrf_field(); ?>
                                                    <input type="hidden" name="action" value="update_status">
                                                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                                                    <input type="hidden" name="status" value="cancelled">
                                                    <button class="btn btn-sm btn-outline-secondary">Cancel</button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.compact-restaurant-hero{padding:12px 16px!important;margin-bottom:10px!important}
.compact-restaurant-hero .btn{margin-left:3px;margin-bottom:3px}
.panel-card{border-radius:16px;box-shadow:0 12px 30px rgba(15,23,42,.07)}
.restaurant-res-metrics .res-metric{border:1px solid #e5e7eb;background:#fff;border-radius:14px;padding:10px 12px;box-shadow:0 8px 22px rgba(15,23,42,.045)}
.restaurant-res-metrics .res-metric span{display:block;font-size:.70rem;text-transform:uppercase;letter-spacing:.06em;color:#64748b;font-weight:800}
.restaurant-res-metrics .res-metric strong{display:block;font-size:1.2rem;color:#0f172a;line-height:1.1}
.reservation-form-card .form-label,.compact-filter-card .form-label{font-size:.74rem;font-weight:800;margin-bottom:.18rem;color:#334155}
.reservation-form-card .form-control,.reservation-form-card .form-select,.compact-filter-card .form-control,.compact-filter-card .form-select{min-height:34px;padding:.35rem .65rem;font-size:.86rem;border-radius:9px}
.table-modern thead th{font-size:.72rem;text-transform:uppercase;color:#64748b;background:#f8fafc;white-space:nowrap;position:sticky;top:0;z-index:4}
.table-modern td,.table-modern th{font-size:.85rem;padding:.58rem .66rem;border-bottom:1px solid #eef2f7;vertical-align:middle}
.reservation-table-wrap{max-height:calc(100vh - 310px);overflow:auto}
</style>

<script>
document.addEventListener('DOMContentLoaded', function(){
    const source = document.getElementById('reservationSource');
    const roomRow = document.querySelector('.room-guest-row');
    const roomDisplayRow = document.querySelector('.room-display-row');
    const inhouse = document.getElementById('inhouseGuestSelect');
    const guestName = document.getElementById('guestName');
    const guestId = document.getElementById('guestId');
    const orderId = document.getElementById('orderId');
    const roomNoHidden = document.getElementById('roomNoHidden');
    const roomNoDisplay = document.getElementById('roomNoDisplay');
    const propertyId = document.getElementById('propertyId');
    const areaId = document.getElementById('areaId');
    const tableId = document.getElementById('tableId');
    const combinedCapacityHint = document.getElementById('combinedCapacityHint');
    const coversInput = document.querySelector('input[name="covers"]');

    function updateCombinedCapacity(){
        if(!tableId || !combinedCapacityHint) return;
        let seats = 0;
        let count = 0;
        [...tableId.options].forEach(opt => {
            if(opt.selected && opt.value){
                seats += parseInt(opt.dataset.seats || '0', 10) || 0;
                count++;
            }
        });
        if(count > 0){
            combinedCapacityHint.textContent = count > 1
                ? ('Combined tables: ' + count + ' • Capacity: ' + seats + ' seats')
                : ('Selected table capacity: ' + seats + ' seats');
            const covers = coversInput ? (parseInt(coversInput.value || '0', 10) || 0) : 0;
            combinedCapacityHint.className = 'small mt-1 fw-bold ' + (covers > seats ? 'text-danger' : 'text-success');
        }else{
            combinedCapacityHint.textContent = 'No table assigned yet.';
            combinedCapacityHint.className = 'small mt-1 fw-bold text-muted';
        }
    }

    function syncSource(){
        const val = source ? source.value : 'room_guest';

        if(roomRow) {
            roomRow.style.display = val === 'room_guest' ? '' : 'none';
        }

        if(roomDisplayRow) {
            roomDisplayRow.style.display = val === 'room_guest' ? '' : 'none';
        }

        if(val !== 'room_guest'){
            if(orderId) orderId.value = '';
            if(guestId) guestId.value = '';
            if(roomNoHidden) roomNoHidden.value = '';
            if(roomNoDisplay) roomNoDisplay.value = '';
            if(guestName && guestName.value.trim() === '') {
                guestName.value = val === 'walkin' ? 'Direct Sale' : '';
            }
        }
    }

    function syncGuest(){
        const opt = inhouse ? inhouse.options[inhouse.selectedIndex] : null;
        if(!opt || !opt.value) return;
        if(orderId) orderId.value = opt.value;
        if(guestId) guestId.value = opt.dataset.guestId || '';
        if(guestName) guestName.value = opt.dataset.guest || '';
        if(roomNoHidden) roomNoHidden.value = opt.dataset.room || '';
        if(roomNoDisplay) roomNoDisplay.value = opt.dataset.room || '';
        if(propertyId && opt.dataset.propertyId && parseInt(opt.dataset.propertyId,10)>0) propertyId.value = opt.dataset.propertyId;
    }

    function filterTables(){
        if(!areaId || !tableId) return;
        const aid = areaId.value || '';
        [...tableId.options].forEach(opt => {
            if(!opt.value){ opt.hidden = false; return; }
            opt.hidden = aid !== '' && String(opt.dataset.areaId || '') !== String(aid);
            if(opt.hidden && opt.selected) opt.selected = false;
        });
        updateCombinedCapacity();
    }

    if(source) source.addEventListener('change', syncSource);
    if(inhouse) inhouse.addEventListener('change', syncGuest);
    if(areaId) areaId.addEventListener('change', filterTables);
    if(tableId) tableId.addEventListener('change', updateCombinedCapacity);
    if(coversInput) coversInput.addEventListener('input', updateCombinedCapacity);
    syncSource();
    filterTables();
    updateCombinedCapacity();
});
</script>

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