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

$pageTitle = 'Restaurant Reservation Calendar';

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('rrc_flash')) {
    function rrc_flash(string $type, string $message): void { $_SESSION['rrc_flash'][] = ['type'=>$type,'message'=>$message]; }
    function rrc_get_flash(): array { $x = $_SESSION['rrc_flash'] ?? []; unset($_SESSION['rrc_flash']); return $x; }
}
if (!function_exists('rrc_user_id')) {
    function rrc_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('rrc_table_exists')) {
    function rrc_table_exists(PDO $pdo, string $table): bool {
        static $cache = [];
        if (array_key_exists($table, $cache)) return $cache[$table];
        try {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
            $stmt->execute([':t'=>$table]);
            return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$table] = false;
        }
    }
}
if (!function_exists('rrc_column_exists')) {
    function rrc_column_exists(PDO $pdo, string $table, string $column): bool {
        static $cache = [];
        $key = $table.'.'.$column;
        if (array_key_exists($key, $cache)) return $cache[$key];
        try {
            $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 $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$key] = false;
        }
    }
}
if (!function_exists('rrc_add_col_if_missing')) {
    function rrc_add_col_if_missing(PDO $pdo, string $table, string $column, string $ddl): void {
        if (rrc_table_exists($pdo, $table) && !rrc_column_exists($pdo, $table, $column)) {
            $pdo->exec($ddl);
        }
    }
}
if (!function_exists('rrc_status_badge_class')) {
    function rrc_status_badge_class(string $status, string $type = 'reservation'): string {
        $status = strtolower(trim($status));
        if ($type === 'order') {
            return [
                'open' => 'text-bg-primary',
                'sent' => 'text-bg-warning text-dark',
                'preparing' => 'text-bg-info text-dark',
                'served' => 'text-bg-success',
                'bill_requested' => 'text-bg-dark',
                'closed' => 'text-bg-secondary',
                'void' => 'text-bg-danger',
            ][$status] ?? 'text-bg-light text-dark border';
        }
        if ($type === 'payment') {
            return [
                'unpaid' => 'text-bg-danger',
                'part_paid' => 'text-bg-warning text-dark',
                'paid' => 'text-bg-success',
                'room_charged' => 'text-bg-primary',
                'void' => 'text-bg-secondary',
            ][$status] ?? 'text-bg-light text-dark border';
        }
        if ($type === 'table') {
            return [
                'available' => 'text-bg-success',
                'occupied' => 'text-bg-danger',
                'reserved' => 'text-bg-primary',
                'dirty' => 'text-bg-warning text-dark',
                'blocked' => 'text-bg-dark',
            ][$status] ?? 'text-bg-light text-dark border';
        }
        return [
            'booked' => 'text-bg-primary',
            'seated' => 'text-bg-success',
            'completed' => 'text-bg-secondary',
            'no_show' => 'text-bg-warning text-dark',
            'cancelled' => 'text-bg-danger',
        ][$status] ?? 'text-bg-light text-dark border';
    }
}
if (!function_exists('rrc_reservation_no_overlap')) {
    function rrc_reservation_no_overlap(PDO $pdo, int $tableId, string $date, string $time, int $duration, int $excludeId = 0): bool {
        if ($tableId <= 0) return true;
        $sql = "
            SELECT COUNT(*)
            FROM restaurant_reservations
            WHERE table_id = :table_id
              AND reservation_date = :reservation_date
              AND status IN ('booked','seated')
              AND id <> :exclude_id
              AND (
                    reservation_time < ADDTIME(:reservation_time_a, SEC_TO_TIME(:duration_a * 60))
                AND ADDTIME(reservation_time, SEC_TO_TIME(duration_minutes * 60)) > :reservation_time_b
              )
        ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':table_id'=>$tableId,
            ':reservation_date'=>$date,
            ':reservation_time_a'=>$time,
            ':reservation_time_b'=>$time,
            ':duration_a'=>$duration,
            ':exclude_id'=>$excludeId,
        ]);
        return ((int)$stmt->fetchColumn() === 0);
    }
}
if (!function_exists('rrc_order_no')) {
    function rrc_order_no(PDO $pdo): string {
        $prefix = 'RST-' . date('ymd') . '-';
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM restaurant_orders WHERE order_no LIKE :p");
        $stmt->execute([':p'=>$prefix.'%']);
        return $prefix . str_pad((string)((int)$stmt->fetchColumn() + 1), 4, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('rrc_time_slot_floor')) {
    function rrc_time_slot_floor(?string $datetimeOrTime, int $slotMinutes = 30): string {
        $value = trim((string)$datetimeOrTime);
        if ($value === '' || strtotime($value) === false) return '06:00:00';
        $ts = strtotime($value);
        $hour = (int)date('H', $ts);
        $minute = (int)date('i', $ts);
        $floored = intdiv($minute, $slotMinutes) * $slotMinutes;
        return sprintf('%02d:%02d:00', $hour, $floored);
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_reservations (
        id BIGINT UNSIGNED 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");

    $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_name VARCHAR(180) NULL,
        meal_period VARCHAR(30) NULL,
        close_method VARCHAR(80) 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','preparing','served','bill_requested','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");

    rrc_add_col_if_missing($pdo, 'restaurant_reservations', 'restaurant_order_id', "ALTER TABLE restaurant_reservations ADD COLUMN restaurant_order_id BIGINT UNSIGNED NULL AFTER notes");
    rrc_add_col_if_missing($pdo, 'restaurant_orders', 'order_name', "ALTER TABLE restaurant_orders ADD COLUMN order_name VARCHAR(180) NULL AFTER order_no");
    rrc_add_col_if_missing($pdo, 'restaurant_orders', 'meal_period', "ALTER TABLE restaurant_orders ADD COLUMN meal_period VARCHAR(30) NULL AFTER order_name");
    rrc_add_col_if_missing($pdo, 'restaurant_orders', 'close_method', "ALTER TABLE restaurant_orders ADD COLUMN close_method VARCHAR(80) NULL AFTER meal_period");

    $pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_order_tables (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        restaurant_order_id BIGINT UNSIGNED NOT NULL,
        table_id INT UNSIGNED NOT NULL,
        joined_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        joined_by INT UNSIGNED NULL,
        UNIQUE KEY uq_rest_order_table(restaurant_order_id,table_id),
        INDEX idx_rest_order_tables_order(restaurant_order_id),
        INDEX idx_rest_order_tables_table(table_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare restaurant calendar tables: ' . $e->getMessage();
}

$selectedDate = trim((string)($_GET['date'] ?? date('Y-m-d')));
if (strtotime($selectedDate) === false) $selectedDate = date('Y-m-d');
$selectedDate = date('Y-m-d', strtotime($selectedDate));
$propertyId = (int)($_GET['property_id'] ?? 0);
$areaId = (int)($_GET['area_id'] ?? 0);
$mealPeriod = trim((string)($_GET['meal_period'] ?? ''));
$validMealPeriods = ['breakfast','lunch','dinner','other'];
if ($mealPeriod !== '' && !in_array($mealPeriod, $validMealPeriods, true)) $mealPeriod = '';

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

        if ($action === 'move_reservation') {
            $id = (int)($_POST['reservation_id'] ?? 0);
            $tableId = (int)($_POST['table_id'] ?? 0);
            $time = trim((string)($_POST['reservation_time'] ?? ''));
            $date = trim((string)($_POST['reservation_date'] ?? $selectedDate));
            if ($id <= 0 || $tableId <= 0 || strtotime($date) === false || strtotime($time) === false) {
                throw new RuntimeException('Invalid reservation move request.');
            }
            $date = date('Y-m-d', strtotime($date));
            $time = date('H:i:s', strtotime($time));
            $stmt = $pdo->prepare("SELECT duration_minutes FROM restaurant_reservations WHERE id=:id LIMIT 1");
            $stmt->execute([':id'=>$id]);
            $duration = max(15, (int)$stmt->fetchColumn());
            if (!rrc_reservation_no_overlap($pdo, $tableId, $date, $time, $duration, $id)) {
                throw new RuntimeException('Selected table is already booked for that time slot.');
            }
            $stmt = $pdo->prepare("UPDATE restaurant_reservations SET table_id=:table_id, reservation_date=:d, reservation_time=:t WHERE id=:id");
            $stmt->execute([':table_id'=>$tableId, ':d'=>$date, ':t'=>$time, ':id'=>$id]);
            header('Content-Type: application/json');
            echo json_encode(['ok'=>true]);
            exit;
        }

        if ($action === 'update_status') {
            $id = (int)($_POST['reservation_id'] ?? 0);
            $status = (string)($_POST['status'] ?? 'booked');
            if ($id <= 0 || !in_array($status, ['booked','seated','no_show','cancelled','completed'], true)) {
                throw new RuntimeException('Invalid status update.');
            }
            $stmt = $pdo->prepare("UPDATE restaurant_reservations SET status=:s WHERE id=:id");
            $stmt->execute([':s'=>$status, ':id'=>$id]);
            rrc_flash('success', 'Reservation status updated.');
            header('Location: reservation_calendar.php?date=' . urlencode($selectedDate));
            exit;
        }

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

            $stmt = $pdo->prepare("SELECT rr.*, rt.area_id, rt.property_id AS table_property_id FROM restaurant_reservations rr LEFT JOIN restaurant_tables rt ON rt.id=rr.table_id WHERE rr.id=:id LIMIT 1");
            $stmt->execute([':id'=>$id]);
            $res = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$res) throw new RuntimeException('Reservation not found.');
            if (empty($res['table_id'])) throw new RuntimeException('Please allocate a table before seating this reservation.');

            $chk = $pdo->prepare("SELECT ro.id FROM restaurant_orders ro LEFT JOIN restaurant_order_tables rot ON rot.restaurant_order_id=ro.id WHERE ro.status IN ('open','sent','preparing','served','bill_requested') AND (ro.table_id=:t_primary OR rot.table_id=:t_joined) LIMIT 1");
            $chk->execute([':t_primary'=>(int)$res['table_id'], ':t_joined'=>(int)$res['table_id']]);
            $restaurantOrderId = (int)$chk->fetchColumn();

            if ($restaurantOrderId <= 0) {
                $type = ($res['source'] === 'walkin' || $res['source'] === 'external') ? 'walkin' : 'room';
                $stmt = $pdo->prepare("INSERT INTO restaurant_orders(property_id,area_id,table_id,order_no,order_name,meal_period,order_type,linked_order_id,guest_name,room_no,covers,status,opened_by,notes) VALUES(:p,:a,:t,:no,:oname,:meal,:type,:oid,:guest,:room,:covers,'open',:u,:notes)");
                $stmt->execute([
                    ':p'=>$res['property_id'] ?: ($res['table_property_id'] ?? null),
                    ':a'=>$res['restaurant_area_id'] ?: ($res['area_id'] ?? null),
                    ':t'=>(int)$res['table_id'],
                    ':no'=>rrc_order_no($pdo),
                    ':oname'=>$res['guest_name'],
                    ':meal'=>$res['meal_period'] ?: null,
                    ':type'=>$type,
                    ':oid'=>$res['order_id'] ?: null,
                    ':guest'=>$res['guest_name'],
                    ':room'=>$res['source'] === 'room_guest' ? ($res['room_no'] ?: null) : null,
                    ':covers'=>(int)$res['covers'],
                    ':u'=>rrc_user_id(),
                    ':notes'=>'Opened from restaurant reservation #' . (int)$res['id'],
                ]);
                $restaurantOrderId = (int)$pdo->lastInsertId();
                $pdo->prepare("INSERT IGNORE INTO restaurant_order_tables(restaurant_order_id,table_id,joined_by) VALUES(:rid,:tid,:u)")->execute([
                    ':rid'=>$restaurantOrderId,
                    ':tid'=>(int)$res['table_id'],
                    ':u'=>rrc_user_id()
                ]);
                $pdo->prepare("UPDATE restaurant_tables SET status='occupied' WHERE id=:id")->execute([':id'=>(int)$res['table_id']]);
            }

            $pdo->prepare("UPDATE restaurant_reservations SET status='seated', restaurant_order_id=:rid WHERE id=:id")
                ->execute([':rid'=>$restaurantOrderId, ':id'=>$id]);
            header('Location: planner.php?restaurant_order_id=' . $restaurantOrderId);
            exit;
        }
    } catch (Throwable $e) {
        if (($_POST['action'] ?? '') === 'move_reservation') {
            header('Content-Type: application/json');
            echo json_encode(['ok'=>false, 'message'=>$e->getMessage()]);
            exit;
        }
        rrc_flash('danger', $e->getMessage());
        header('Location: reservation_calendar.php?date=' . urlencode($selectedDate));
        exit;
    }
}

$properties = [];
$areas = [];
$tables = [];
$reservations = [];
$activeOrdersByTable = [];
$ordersByTableSlot = [];
$flashes = rrc_get_flash();

try {
    if (rrc_table_exists($pdo, 'properties')) {
        $propsWhere = rrc_column_exists($pdo, 'properties', 'is_active') ? 'WHERE is_active=1' : '';
        $codeSel = rrc_column_exists($pdo, 'properties', 'code') ? ', code' : ', NULL AS code';
        $properties = $pdo->query("SELECT id, name {$codeSel} FROM properties {$propsWhere} ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
    }

    $areaWhere = "WHERE ra.is_active=1";
    $areaParams = [];
    if ($propertyId > 0) { $areaWhere .= " AND (ra.property_id=:pid OR ra.property_id IS NULL)"; $areaParams[':pid'] = $propertyId; }
    $stmt = $pdo->prepare("SELECT ra.* FROM restaurant_areas ra {$areaWhere} ORDER BY ra.sort_order ASC, ra.area_name ASC");
    $stmt->execute($areaParams);
    $areas = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $tableWhere = "WHERE rt.is_active=1 AND rt.status <> 'blocked'";
    $tableParams = [];
    if ($propertyId > 0) { $tableWhere .= " AND (rt.property_id=:pid OR rt.property_id IS NULL)"; $tableParams[':pid'] = $propertyId; }
    if ($areaId > 0) { $tableWhere .= " AND rt.area_id=:aid"; $tableParams[':aid'] = $areaId; }
    $stmt = $pdo->prepare("
        SELECT rt.*, ra.area_name
        FROM restaurant_tables rt
        LEFT JOIN restaurant_areas ra ON ra.id=rt.area_id
        {$tableWhere}
        ORDER BY COALESCE(ra.sort_order,999), ra.area_name, rt.table_no
    ");
    $stmt->execute($tableParams);
    $tables = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $ordersSql = "
        SELECT
            ro.id,
            ro.order_no,
            ro.order_name,
            ro.meal_period,
            ro.close_method,
            ro.table_id,
            ro.order_type,
            ro.guest_name,
            ro.room_no,
            ro.covers,
            ro.status,
            ro.payment_status,
            ro.total_amount,
            ro.opened_at,
            ro.closed_at,
            ro.created_at,
            GROUP_CONCAT(DISTINCT rot.table_id ORDER BY rot.table_id SEPARATOR ',') AS joined_table_ids,
            GROUP_CONCAT(DISTINCT CONCAT(rt2.table_no, ' (', rt2.seats, ')') ORDER BY rt2.table_no SEPARATOR ' + ') AS joined_table_labels
        FROM restaurant_orders ro
        LEFT JOIN restaurant_order_tables rot ON rot.restaurant_order_id=ro.id
        LEFT JOIN restaurant_tables rt2 ON rt2.id=rot.table_id
        WHERE DATE(ro.opened_at)=:opened_date
           OR DATE(ro.created_at)=:created_date
           OR (ro.status IN ('open','sent','preparing','served','bill_requested') AND ro.table_id IS NOT NULL)
        GROUP BY ro.id
        ORDER BY ro.opened_at ASC, ro.id ASC
    ";
    $stmt = $pdo->prepare($ordersSql);
    $stmt->execute([':opened_date'=>$selectedDate, ':created_date'=>$selectedDate]);
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $orow) {
        $ids = [];
        if (!empty($orow['joined_table_ids'])) {
            foreach (explode(',', (string)$orow['joined_table_ids']) as $tid) {
                $tid = (int)$tid;
                if ($tid > 0) $ids[$tid] = $tid;
            }
        }
        $primary = (int)($orow['table_id'] ?? 0);
        if ($primary > 0) $ids[$primary] = $primary;
        $orderTimeRaw = !empty($orow['opened_at']) ? (string)$orow['opened_at'] : (string)($orow['created_at'] ?? '');
        $orderSlot = rrc_time_slot_floor($orderTimeRaw, $slotMinutes ?? 30);
        foreach ($ids as $tid) {
            $activeOrdersByTable[$tid][] = $orow;
            $ordersByTableSlot[$tid][$orderSlot][] = $orow;
        }
    }

    $resWhere = "WHERE rr.reservation_date=:d";
    $resParams = [':d'=>$selectedDate];
    if ($propertyId > 0) { $resWhere .= " AND (rr.property_id=:pid OR rr.property_id IS NULL)"; $resParams[':pid'] = $propertyId; }
    if ($areaId > 0) { $resWhere .= " AND rr.restaurant_area_id=:aid"; $resParams[':aid'] = $areaId; }
    if ($mealPeriod !== '') { $resWhere .= " AND rr.meal_period=:meal"; $resParams[':meal'] = $mealPeriod; }

    $stmt = $pdo->prepare("
        SELECT
            rr.*,
            rt.table_no,
            rt.table_name,
            rt.seats,
            rt.status AS table_status,
            ra.area_name,
            p.name AS property_name,
            o.order_no AS booking_no,
            ro.order_no AS restaurant_order_no,
            ro.order_name AS restaurant_order_name,
            ro.meal_period AS restaurant_meal_period,
            ro.close_method AS restaurant_close_method,
            ro.status AS restaurant_order_status,
            ro.payment_status AS restaurant_payment_status,
            ro.total_amount AS restaurant_total_amount
        FROM restaurant_reservations rr
        LEFT JOIN restaurant_tables rt ON rt.id=rr.table_id
        LEFT JOIN restaurant_areas ra ON ra.id=rr.restaurant_area_id
        LEFT JOIN properties p ON p.id=rr.property_id
        LEFT JOIN orders o ON o.id=rr.order_id
        LEFT JOIN restaurant_orders ro ON ro.id=rr.restaurant_order_id
        {$resWhere}
        ORDER BY rr.reservation_time ASC, rr.id ASC
    ");
    $stmt->execute($resParams);
    $reservations = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $errors[] = $e->getMessage();
}

$startHour = 6;
$endHour = 23;
if ($mealPeriod === 'breakfast') { $startHour = 6; $endHour = 11; }
elseif ($mealPeriod === 'lunch') { $startHour = 11; $endHour = 16; }
elseif ($mealPeriod === 'dinner') { $startHour = 16; $endHour = 23; }
$slotMinutes = 30;
$timeSlots = [];
for ($m = $startHour * 60; $m <= $endHour * 60; $m += $slotMinutes) {
    $timeSlots[] = sprintf('%02d:%02d:00', intdiv($m, 60), $m % 60);
}

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

    $tid = (int)($res['table_id'] ?? 0);
    $slot = date('H:i:00', strtotime((string)$res['reservation_time']));
    if ($tid > 0) $resByTableSlot[$tid][$slot][] = $res;
    else $unallocated[] = $res;
}

$openOrderCount = 0;
$openOrderTotal = 0.0;
foreach ($activeOrdersByTable as $rows) {
    foreach ($rows as $orow) {
        if (in_array((string)($orow['status'] ?? ''), ['open','sent','preparing','served','bill_requested'], true)) {
            $openOrderCount++;
            $openOrderTotal += (float)($orow['total_amount'] ?? 0);
        }
    }
}

$prevDate = date('Y-m-d', strtotime($selectedDate . ' -1 day'));
$nextDate = date('Y-m-d', strtotime($selectedDate . ' +1 day'));
$todayDate = date('Y-m-d');
$queryBase = ['property_id'=>$propertyId, 'area_id'=>$areaId, 'meal_period'=>$mealPeriod];

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

<div class="hero-band restaurant-calendar-hero">
    <div class="row align-items-center g-2">
        <div class="col-lg-7">
            <div class="page-eyebrow text-white-50"><i class="bi bi-calendar-week"></i> Restaurant Reservations</div>
            <div class="hero-title mt-1">Reservation Calendar</div>
            <div class="hero-subtitle mt-1">Visual table calendar with table status, active orders, meal periods, close methods and guest details.</div>
        </div>
        <div class="col-lg-5 text-lg-end">
            <a class="btn btn-light btn-sm" href="reservation_form.php"><i class="bi bi-plus-circle me-1"></i>New Reservation</a>
            <a class="btn btn-outline-light btn-sm" href="reservations.php"><i class="bi bi-list-ul me-1"></i>Reservation List</a>
            <a class="btn btn-warning btn-sm" href="planner.php"><i class="bi bi-grid-3x3-gap me-1"></i>Table Planner</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"><strong>Please fix:</strong><ul class="mb-0"><?php foreach ($errors as $e): ?><li><?php echo h($e); ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>

<div class="row g-2 mb-3 calendar-metrics">
    <div class="col-md-2"><div class="metric-card"><span>Booked</span><strong><?php echo (int)$stats['booked']; ?></strong></div></div>
    <div class="col-md-2"><div class="metric-card"><span>Seated</span><strong><?php echo (int)$stats['seated']; ?></strong></div></div>
    <div class="col-md-2"><div class="metric-card"><span>Completed</span><strong><?php echo (int)$stats['completed']; ?></strong></div></div>
    <div class="col-md-2"><div class="metric-card"><span>Covers</span><strong><?php echo (int)$stats['covers']; ?></strong></div></div>
    <div class="col-md-2"><div class="metric-card"><span>Open Orders</span><strong><?php echo (int)$openOrderCount; ?></strong></div></div>
    <div class="col-md-2"><div class="metric-card"><span>Open Value</span><strong><?php echo money_fmt($openOrderTotal); ?></strong></div></div>
</div>

<div class="card panel-card mb-3 calendar-filter-card">
    <div class="card-body p-2">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-md-2">
                <label class="form-label">Date</label>
                <input type="date" name="date" class="form-control" value="<?php echo h($selectedDate); ?>">
            </div>
            <div class="col-md-2">
                <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']); ?><?php echo !empty($p['code']) ? ' - '.h($p['code']) : ''; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Area</label>
                <select name="area_id" class="form-select">
                    <option value="0">All</option>
                    <?php foreach ($areas as $a): ?>
                        <option value="<?php echo (int)$a['id']; ?>" <?php echo $areaId === (int)$a['id'] ? 'selected' : ''; ?>><?php echo h($a['area_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Meal</label>
                <select name="meal_period" class="form-select">
                    <option value="">All</option>
                    <?php foreach ($validMealPeriods as $mp): ?>
                        <option value="<?php echo h($mp); ?>" <?php echo $mealPeriod === $mp ? 'selected' : ''; ?>><?php echo h(ucfirst($mp)); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-1 d-grid"><button class="btn btn-primary">Go</button></div>
            <div class="col-md-3 text-md-end">
                <div class="btn-group btn-group-sm mt-4" role="group">
                    <a class="btn btn-outline-secondary" href="reservation_calendar.php?<?php echo h(http_build_query(array_merge($queryBase, ['date'=>$prevDate]))); ?>">&lt; Prev</a>
                    <a class="btn btn-outline-secondary" href="reservation_calendar.php?<?php echo h(http_build_query(array_merge($queryBase, ['date'=>$todayDate]))); ?>">Today</a>
                    <a class="btn btn-outline-secondary" href="reservation_calendar.php?<?php echo h(http_build_query(array_merge($queryBase, ['date'=>$nextDate]))); ?>">Next &gt;</a>
                </div>
            </div>
        </form>
    </div>
</div>

<?php if ($unallocated): ?>
<div class="card panel-card mb-3">
    <div class="card-header py-2"><strong><i class="bi bi-exclamation-circle me-1"></i>Unallocated Reservations</strong></div>
    <div class="card-body p-2 d-flex flex-wrap gap-2">
        <?php foreach ($unallocated as $res): ?>
            <div class="reservation-pill status-<?php echo h($res['status']); ?>" draggable="true" data-res-id="<?php echo (int)$res['id']; ?>">
                <strong><?php echo h(date('H:i', strtotime($res['reservation_time']))); ?> <?php echo h($res['guest_name']); ?></strong>
                <small><?php echo (int)$res['covers']; ?> pax • <?php echo h($res['meal_period']); ?> • <?php echo h($res['source']); ?></small>
            </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<div id="calendarCsrf" style="display:none"><?php if (function_exists('csrf_field')) echo csrf_field(); ?></div>

<div class="card panel-card calendar-card">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h5 class="mb-0">Calendar for <?php echo h(date('D, d M Y', strtotime($selectedDate))); ?></h5>
            <small class="text-muted">Drag cards to another table/time. Table columns now include table status and live restaurant order info.</small>
        </div>
        <div class="legend">
            <span class="status-booked">Booked</span><span class="status-seated">Seated</span><span class="status-completed">Completed</span><span class="status-no_show">No Show</span><span class="status-cancelled">Cancelled</span>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="calendar-grid-wrap">
            <table class="table calendar-grid mb-0">
                <thead>
                    <tr>
                        <th class="time-col">Time</th>
                        <?php foreach ($tables as $t): ?>
                            <?php
                                $tid = (int)$t['id'];
                                $tableStatus = (string)($t['status'] ?? 'available');
                                $ordersOnTable = $activeOrdersByTable[$tid] ?? [];
                            ?>
                            <th>
                                <div class="table-head">
                                    <div class="d-flex justify-content-between gap-2">
                                        <strong><?php echo h($t['table_no']); ?></strong>
                                        <span class="badge <?php echo h(rrc_status_badge_class($tableStatus, 'table')); ?>"><?php echo h(ucwords(str_replace('_',' ', $tableStatus))); ?></span>
                                    </div>
                                    <small><?php echo h($t['area_name'] ?: 'Area'); ?> • <?php echo (int)$t['seats']; ?> seats</small>
                                    <?php if ($ordersOnTable): ?>
                                        <?php foreach ($ordersOnTable as $oo): ?>
                                            <?php if (!in_array((string)$oo['status'], ['open','sent','preparing','served','bill_requested'], true)) continue; ?>
                                            <div class="table-order-chip">
                                                <div><strong><?php echo h($oo['order_no']); ?></strong> • <?php echo h($oo['guest_name'] ?: $oo['order_name'] ?: 'Guest'); ?></div>
                                                <div><?php echo h(ucwords(str_replace('_',' ', (string)$oo['status']))); ?> • <?php echo money_fmt($oo['total_amount']); ?><?php echo !empty($oo['joined_table_labels']) ? ' • Merged: '.h($oo['joined_table_labels']) : ''; ?></div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($timeSlots as $slot): ?>
                    <tr>
                        <td class="time-col"><strong><?php echo h(date('H:i', strtotime($slot))); ?></strong></td>
                        <?php foreach ($tables as $t): ?>
                            <?php
                                $tid = (int)$t['id'];
                                $slotRows = $resByTableSlot[$tid][$slot] ?? [];
                                $orderSlotRows = $ordersByTableSlot[$tid][$slot] ?? [];
                            ?>
                            <td class="calendar-cell" data-table-id="<?php echo $tid; ?>" data-time="<?php echo h($slot); ?>" data-date="<?php echo h($selectedDate); ?>">
                                <?php foreach ($orderSlotRows as $oo): ?>
                                    <?php
                                        $orderTimeRaw = !empty($oo['opened_at']) ? (string)$oo['opened_at'] : (string)($oo['created_at'] ?? '');
                                        $orderTime = strtotime($orderTimeRaw) !== false ? date('H:i', strtotime($orderTimeRaw)) : date('H:i', strtotime($slot));
                                        $orderStatus = (string)($oo['status'] ?? 'open');
                                        $paymentStatus = (string)($oo['payment_status'] ?? 'unpaid');
                                    ?>
                                    <div class="res-card live-order-card order-status-<?php echo h($orderStatus); ?>">
                                        <div class="res-card-top">
                                            <strong><?php echo h($oo['guest_name'] ?: $oo['order_name'] ?: 'Restaurant Order'); ?></strong>
                                            <span class="badge <?php echo h(rrc_status_badge_class($orderStatus, 'order')); ?>"><?php echo h(ucwords(str_replace('_',' ', $orderStatus))); ?></span>
                                        </div>
                                        <span><i class="bi bi-clock me-1"></i><?php echo h($orderTime); ?> • <?php echo h($oo['meal_period'] ?: 'Order'); ?></span>
                                        <span><i class="bi bi-receipt me-1"></i><?php echo h($oo['order_no']); ?> • <?php echo h(ucwords(str_replace('_',' ', $paymentStatus))); ?> • <?php echo money_fmt($oo['total_amount']); ?></span>
                                        <?php if (!empty($oo['room_no'])): ?><small>Room <?php echo h($oo['room_no']); ?></small><?php endif; ?>
                                        <?php if (!empty($oo['close_method'])): ?><small>Close: <?php echo h($oo['close_method']); ?></small><?php endif; ?>
                                        <?php if (!empty($oo['joined_table_labels'])): ?><small>Merged: <?php echo h($oo['joined_table_labels']); ?></small><?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                                <?php foreach ($slotRows as $res): ?>
                                    <?php
                                        $status = (string)$res['status'];
                                        $orderStatus = (string)($res['restaurant_order_status'] ?? '');
                                        $paymentStatus = (string)($res['restaurant_payment_status'] ?? '');
                                        $meta = [
                                            'id'=>(int)$res['id'],
                                            'guest_name'=>(string)$res['guest_name'],
                                            'room_no'=>(string)($res['room_no'] ?? ''),
                                            'booking_no'=>(string)($res['booking_no'] ?? ''),
                                            'covers'=>(int)$res['covers'],
                                            'time'=>date('H:i', strtotime($res['reservation_time'])),
                                            'duration'=>(int)$res['duration_minutes'],
                                            'meal_period'=>(string)$res['meal_period'],
                                            'source'=>(string)$res['source'],
                                            'status'=>$status,
                                            'notes'=>(string)($res['notes'] ?? ''),
                                            'table'=>trim((string)($res['table_no'] ?? '')),
                                            'area'=>(string)($res['area_name'] ?? ''),
                                            'property'=>(string)($res['property_name'] ?? ''),
                                            'order_id'=>(int)($res['order_id'] ?? 0),
                                            'restaurant_order_no'=>(string)($res['restaurant_order_no'] ?? ''),
                                            'restaurant_order_status'=>$orderStatus,
                                            'restaurant_payment_status'=>$paymentStatus,
                                            'restaurant_total_amount'=>(float)($res['restaurant_total_amount'] ?? 0),
                                            'restaurant_close_method'=>(string)($res['restaurant_close_method'] ?? ''),
                                        ];
                                    ?>
                                    <div class="res-card status-<?php echo h($status); ?>" draggable="true" data-res-id="<?php echo (int)$res['id']; ?>" data-meta='<?php echo h(json_encode($meta, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT)); ?>'>
                                        <div class="res-card-top">
                                            <strong><?php echo h($res['guest_name']); ?></strong>
                                            <span class="badge <?php echo h(rrc_status_badge_class($status)); ?>"><?php echo h(ucwords(str_replace('_',' ', $status))); ?></span>
                                        </div>
                                        <span><i class="bi bi-clock me-1"></i><?php echo h(date('H:i', strtotime($res['reservation_time']))); ?> • <?php echo (int)$res['duration_minutes']; ?> min • <?php echo h(ucfirst($res['meal_period'])); ?></span>
                                        <span><i class="bi bi-people me-1"></i><?php echo (int)$res['covers']; ?> pax • <?php echo h(ucwords(str_replace('_',' ', $res['source']))); ?></span>
                                        <?php if (!empty($res['room_no'])): ?><small>Room <?php echo h($res['room_no']); ?></small><?php endif; ?>
                                        <?php if (!empty($res['restaurant_order_no'])): ?>
                                            <small class="order-mini">Order <?php echo h($res['restaurant_order_no']); ?> • <?php echo h($orderStatus ?: '-'); ?> • <?php echo money_fmt($res['restaurant_total_amount']); ?></small>
                                        <?php endif; ?>
                                    </div>
                                <?php endforeach; ?>
                            </td>
                        <?php endforeach; ?>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="reservationActionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h5 class="modal-title" id="modalGuestName">Reservation</h5>
                    <div class="small text-muted" id="modalSubtitle">-</div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row g-3">
                    <div class="col-md-3"><div class="mini-info"><span>Time / Meal</span><strong id="modalTime">-</strong></div></div>
                    <div class="col-md-3"><div class="mini-info"><span>Covers</span><strong id="modalCovers">-</strong></div></div>
                    <div class="col-md-3"><div class="mini-info"><span>Table / Area</span><strong id="modalTable">-</strong></div></div>
                    <div class="col-md-3"><div class="mini-info"><span>Status</span><strong id="modalStatus">-</strong></div></div>
                    <div class="col-md-3"><div class="mini-info"><span>Source</span><strong id="modalSource">-</strong></div></div>
                    <div class="col-md-3"><div class="mini-info"><span>Booking</span><strong id="modalBooking">-</strong></div></div>
                    <div class="col-md-3"><div class="mini-info"><span>Restaurant Order</span><strong id="modalRestaurantOrder">-</strong></div></div>
                    <div class="col-md-3"><div class="mini-info"><span>Close Method</span><strong id="modalCloseMethod">-</strong></div></div>
                </div>
                <div class="alert alert-light border mt-3 mb-0" id="modalNotes">No notes.</div>
            </div>
            <div class="modal-footer flex-wrap justify-content-between">
                <div class="d-flex gap-2 flex-wrap">
                    <a href="#" class="btn btn-outline-primary" id="modalEditLink"><i class="bi bi-pencil-square me-1"></i>Edit</a>
                    <form method="post" id="seatForm" class="d-inline"><?php if (function_exists('csrf_field')) echo csrf_field(); ?><input type="hidden" name="action" value="seat_reservation"><input type="hidden" name="reservation_id" id="seatReservationId"><button class="btn btn-success"><i class="bi bi-person-check me-1"></i>Seat / Open Order</button></form>
                </div>
                <div class="d-flex gap-2 flex-wrap">
                    <?php foreach (['booked'=>'Booked','no_show'=>'No Show','cancelled'=>'Cancel','completed'=>'Complete'] as $st=>$label): ?>
                        <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="reservation_id" class="statusReservationId"><input type="hidden" name="status" value="<?php echo h($st); ?>"><button class="btn btn-sm btn-outline-secondary"><?php echo h($label); ?></button></form>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.restaurant-calendar-hero{padding:12px 16px!important;margin-bottom:10px!important}
.restaurant-calendar-hero .btn{margin-left:3px;margin-bottom:3px}
.panel-card{border-radius:16px;box-shadow:0 12px 30px rgba(15,23,42,.07)}
.calendar-filter-card .form-label{font-size:.72rem;font-weight:800;margin-bottom:2px}
.calendar-filter-card .form-control,.calendar-filter-card .form-select{min-height:34px;font-size:.84rem;padding:.35rem .55rem}
.calendar-metrics .metric-card{border:1px solid #e5e7eb;background:#fff;border-radius:14px;padding:10px 12px;box-shadow:0 8px 22px rgba(15,23,42,.045)}
.calendar-metrics .metric-card span{display:block;font-size:.68rem;text-transform:uppercase;letter-spacing:.06em;color:#64748b;font-weight:800}
.calendar-metrics .metric-card strong{display:block;font-size:1.05rem;color:#0f172a;line-height:1.2}
.calendar-grid-wrap{overflow:auto;max-height:calc(100vh - 340px)}
.calendar-grid{border-collapse:separate;border-spacing:0;min-width:1200px}
.calendar-grid th{position:sticky;top:0;z-index:12;background:#fff;border-bottom:2px solid #e5e7eb;vertical-align:top}
.calendar-grid .time-col{position:sticky;left:0;z-index:14;background:#fff;width:78px;min-width:78px;text-align:center;border-right:1px solid #e5e7eb}
.calendar-grid tbody .time-col{z-index:10;background:#f8fafc}
.calendar-grid td,.calendar-grid th{border-right:1px solid #e5e7eb;border-bottom:1px solid #eef2f7;padding:6px;min-width:190px}
.calendar-cell{height:88px;background:#fff;vertical-align:top}
.calendar-cell:hover{background:#f8fafc;outline:2px solid #bfdbfe;outline-offset:-2px}
.calendar-cell.is-drop{background:#eff6ff!important}
.table-head strong{display:block;font-size:.9rem;color:#0f172a}
.table-head small{display:block;font-size:.68rem;color:#64748b}
.table-order-chip{margin-top:5px;border-radius:10px;background:#f8fafc;border:1px solid #e2e8f0;padding:5px 7px;font-size:.66rem;color:#334155;line-height:1.2}
.res-card,.reservation-pill{border-radius:12px;padding:7px 8px;margin-bottom:4px;cursor:pointer;box-shadow:0 8px 18px rgba(15,23,42,.08);border:1px solid rgba(15,23,42,.08);font-size:.78rem}
.res-card-top{display:flex;align-items:flex-start;justify-content:space-between;gap:6px}
.res-card strong,.reservation-pill strong{display:block;font-size:.78rem;line-height:1.1}
.res-card span,.res-card small,.reservation-pill small{display:block;font-size:.66rem;opacity:.9;margin-top:2px}
.res-card .badge{font-size:.58rem;padding:3px 5px}
.order-mini{background:rgba(15,23,42,.055);border-radius:8px;padding:3px 5px;margin-top:4px}
.live-order-card{background:#fff7ed;color:#9a3412;border-color:#fed7aa;border-left:4px solid #f97316}
.live-order-card .badge{font-size:.58rem;padding:3px 5px}
.order-status-closed{background:#f8fafc;color:#475569;border-color:#cbd5e1;border-left-color:#64748b}
.order-status-sent,.order-status-preparing{background:#fffbeb;color:#92400e;border-color:#fde68a;border-left-color:#f59e0b}
.order-status-served{background:#ecfdf5;color:#047857;border-color:#a7f3d0;border-left-color:#10b981}
.order-status-bill_requested{background:#eff6ff;color:#1d4ed8;border-color:#bfdbfe;border-left-color:#2563eb}
.status-booked{background:#eff6ff;color:#1d4ed8}
.status-seated{background:#ecfdf5;color:#047857}
.status-completed{background:#f1f5f9;color:#475569}
.status-no_show{background:#fff7ed;color:#c2410c}
.status-cancelled{background:#fef2f2;color:#b91c1c;text-decoration:line-through}
.legend{display:flex;gap:6px;flex-wrap:wrap}
.legend span{font-size:.7rem;font-weight:800;border-radius:999px;padding:4px 8px;border:1px solid rgba(15,23,42,.08)}
.mini-info{border:1px solid #e5e7eb;border-radius:14px;padding:10px;background:#fff}
.mini-info span{display:block;font-size:.68rem;color:#64748b;text-transform:uppercase;font-weight:800;letter-spacing:.05em}
.mini-info strong{display:block;font-size:.9rem;color:#0f172a;line-height:1.2}
.layout-toast{position:fixed;right:18px;bottom:18px;z-index:99999;background:#0f172a;color:#fff;border-radius:12px;padding:10px 14px;font-size:.82rem;box-shadow:0 18px 45px rgba(15,23,42,.28);display:none}
.layout-toast.is-show{display:block}
</style>

<script>
document.addEventListener('DOMContentLoaded', function(){
    const csrfBox = document.getElementById('calendarCsrf');
    const modalEl = document.getElementById('reservationActionModal');
    const modal = modalEl && window.bootstrap ? new bootstrap.Modal(modalEl) : null;
    let draggedRes = null;
    let toastTimer = null;

    function csrfFields(){ const fields=[]; if(!csrfBox) return fields; csrfBox.querySelectorAll('input').forEach(i=>fields.push([i.name,i.value])); return fields; }
    function toast(message){ let el=document.getElementById('layoutToast'); if(!el){el=document.createElement('div');el.id='layoutToast';el.className='layout-toast';document.body.appendChild(el);} el.textContent=message;el.classList.add('is-show');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('is-show'),2400); }
    function escapeHtml(value){ return String(value||'').replace(/[&<>'"]/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#039;','"':'&quot;'}[ch] || ch)); }

    document.querySelectorAll('.res-card,.reservation-pill').forEach(card => {
        card.addEventListener('dragstart', e => { draggedRes = card; e.dataTransfer.effectAllowed='move'; e.dataTransfer.setData('text/plain', card.dataset.resId || ''); });
        card.addEventListener('click', () => openModal(card));
    });

    document.querySelectorAll('.calendar-cell').forEach(cell => {
        cell.addEventListener('dragover', e => { if(!draggedRes) return; e.preventDefault(); cell.classList.add('is-drop'); });
        cell.addEventListener('dragleave', () => cell.classList.remove('is-drop'));
        cell.addEventListener('drop', e => {
            if(!draggedRes) return;
            e.preventDefault(); cell.classList.remove('is-drop');
            const fd = new FormData();
            fd.append('action','move_reservation');
            fd.append('reservation_id', draggedRes.dataset.resId || '0');
            fd.append('table_id', cell.dataset.tableId || '0');
            fd.append('reservation_time', cell.dataset.time || '');
            fd.append('reservation_date', cell.dataset.date || '');
            csrfFields().forEach(([k,v]) => fd.append(k,v));
            fetch('reservation_calendar.php?date=<?php echo h($selectedDate); ?>', {method:'POST', body:fd, credentials:'same-origin', cache:'no-store'})
                .then(r=>r.json())
                .then(data => { if(!data || !data.ok) throw new Error(data && data.message ? data.message : 'Move failed'); cell.appendChild(draggedRes); toast('Reservation moved'); setTimeout(()=>location.reload(), 500); })
                .catch(err => toast(err.message));
        });
    });

    function openModal(card){
        if(!modal) return;
        let meta = {};
        try { meta = JSON.parse(card.dataset.meta || '{}') || {}; } catch(e) {}
        const id = meta.id || card.dataset.resId || '';
        document.getElementById('modalGuestName').textContent = meta.guest_name || 'Reservation';
        document.getElementById('modalSubtitle').textContent =
            (meta.room_no ? 'Room ' + meta.room_no + ' • ' : '') +
            (meta.booking_no ? 'Booking ' + meta.booking_no + ' • ' : '') +
            (meta.property ? meta.property + ' • ' : '') +
            (meta.source || '');
        document.getElementById('modalTime').textContent = (meta.time || '-') + ' / ' + (meta.duration || 90) + ' mins • ' + (meta.meal_period || '-');
        document.getElementById('modalCovers').textContent = (meta.covers || 1) + ' pax';
        document.getElementById('modalTable').textContent = (meta.table || 'Unallocated') + (meta.area ? ' / ' + meta.area : '');
        document.getElementById('modalStatus').textContent = meta.status || '-';
        document.getElementById('modalSource').textContent = meta.source || '-';
        document.getElementById('modalBooking').textContent = meta.booking_no || '-';
        document.getElementById('modalRestaurantOrder').textContent =
            meta.restaurant_order_no
                ? (meta.restaurant_order_no + ' • ' + (meta.restaurant_order_status || '-') + ' • ' + Number(meta.restaurant_total_amount || 0).toFixed(2))
                : '-';
        document.getElementById('modalCloseMethod').textContent = meta.restaurant_close_method || meta.restaurant_payment_status || '-';
        document.getElementById('modalNotes').innerHTML = meta.notes ? escapeHtml(meta.notes) : 'No notes.';
        document.getElementById('modalEditLink').href = 'reservation_form.php?id=' + encodeURIComponent(id);
        document.getElementById('seatReservationId').value = id;
        document.querySelectorAll('.statusReservationId').forEach(i => i.value = id);
        modal.show();
    }
});
</script>

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