<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

require_once __DIR__ . "/includes/auth.php";
ensure_manager();
require_once __DIR__ . "/includes/functions.php";

/* ======================
   CONTEXT
====================== */
$restaurant_id = (int)($_SESSION['restaurant_id'] ?? 0);
$role          = $_SESSION['manager_role'] ?? 'editor';
$lang          = $_SESSION['panel_lang'] ?? ($_SESSION['lang'] ?? 'ar');
if(!in_array($lang, ['ar','en','ku'])) $lang='ar';
$tr            = require __DIR__ . "/lang/$lang.php";

if(!in_array($role, ['manager','editor'])) die("No permission");

/* ======================
   HELPERS
====================== */
function e($v){
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}
function time12($t){
    if(!$t) return '-';
    return date("h:i A", strtotime($t));
}
function clean_phone_digits($p){
    $d = preg_replace('/\D+/', '', (string)$p);
    $d = ltrim($d, '0');
    if($d === '') return '';
    // WhatsApp: digits only, no +
    return '964'.$d;
}

/* ======================
   WHERE (REPORT FILTER)
   IMPORTANT: use alias r to avoid ambiguous restaurant_id
====================== */
$type = $_GET['type'] ?? 'all';  // all | month | day
$date = $_GET['date'] ?? null;

$where  = " r.restaurant_id = ? ";
$params = [$restaurant_id];

if($type==='month' && $date){
    $where .= " AND DATE_FORMAT(r.reservation_date,'%Y-%m') = ? ";
    $params[] = $date;
}elseif($type==='day' && $date){
    $where .= " AND r.reservation_date = ? ";
    $params[] = $date;
}

/* ======================
   AJAX: LIVE TABLE ONLY
   returns JSON: {html, live_count, play_sound}
====================== */
if(isset($_GET['ajax']) && $_GET['ajax']==='live'){
    header("Content-Type: application/json; charset=UTF-8");

    // Live rows (pending+confirmed) with items aggregated
    $live_rows = fetch_all("
        SELECT
            r.*,
            GROUP_CONCAT(
                CONCAT(
                    COALESCE(i.name_ar, i.name, ''),
                    ' x',
                    COALESCE(NULLIF(ri.qty,0), NULLIF(ri.quantity,0), 1)
                )
                SEPARATOR ' / '
            ) AS items_text
        FROM reservations r
        LEFT JOIN reservation_items ri ON ri.reservation_id = r.id
        LEFT JOIN items i ON i.id = ri.item_id
        WHERE r.restaurant_id = ?
          AND r.status IN('pending','confirmed')
        GROUP BY r.id
        ORDER BY r.created_at DESC
    ", [$restaurant_id]);

    $live_count = count($live_rows);

    $play_sound = false;
    if(!isset($_SESSION['last_live_count'])) $_SESSION['last_live_count'] = $live_count;
    if($live_count > (int)$_SESSION['last_live_count']) $play_sound = true;
    $_SESSION['last_live_count'] = $live_count;

    ob_start();
    foreach($live_rows as $r){
        $rid = (int)$r['id'];
        $phone_wa = clean_phone_digits($r['customer_phone']);
        $status = (string)($r['status'] ?? 'pending');

        // badge text (fallback to status)
        $badge_text = $tr[$status] ?? $status;

        // WhatsApp message (EDIT HERE LATER)
        $wa_text =
            ($tr['reservation_msg_title'] ?? "Thank you for your reservation.
Your booking details are as follows:")."\n".
            ($tr['customer_name'] ?? "Name").": ".($r['customer_name'] ?? "")."\n".
            ($tr['date'] ?? "Date").": ".($r['reservation_date'] ?? "")."\n".
            ($tr['time'] ?? "Time").": ".(time12($r['reservation_time'] ?? ''))."\n".
            ($tr['total'] ?? "Total").": ".($r['total_price'] ?? 0)." IQD\n".
            ($tr['items'] ?? "Items").": ".($r['items_text'] ?? "");

        ?>
        <tr>
            <td><?= e($r['customer_name']) ?></td>
            <td><?= e($r['customer_phone']) ?></td>
            <td><?= e($r['reservation_date']) ?></td>
            <td><?= time12($r['reservation_time']) ?></td>
            <td><?= e($r['items_text'] ?? '') ?></td>
            <td><?= number_format((float)($r['total_price'] ?? 0),0) ?></td>
            <td>
                <span class="badge <?= e($status) ?>"><?= e($badge_text) ?></span>
            </td>
            <td>
                <?php if($phone_wa !== ''): ?>
                <a class="btn btn-dark" target="_blank"
                   href="https://wa.me/<?= e($phone_wa) ?>?text=<?= urlencode($wa_text) ?>">
                    WhatsApp
                </a>
                <?php endif; ?>

                <?php if($status==='pending'): ?>
                    <button class="btn btn-green" onclick="openConfirmModal(<?= $rid ?>)">✔ <?= e($tr['accept'] ?? 'قبول') ?></button>
                    <button class="btn btn-red" onclick="openCancelModal(<?= $rid ?>)">✖ <?= e($tr['cancel'] ?? 'إلغاء') ?></button>
                <?php elseif($status==='confirmed'): ?>
                    <button class="btn btn-green" onclick="openCompleteModal(<?= $rid ?>)">✔ <?= e($tr['complete'] ?? 'مكتمل') ?></button>
                    <button class="btn btn-red" onclick="openCancelModal(<?= $rid ?>)">✖ <?= e($tr['cancel'] ?? 'إلغاء') ?></button>
                <?php endif; ?>
            </td>
        </tr>
        <?php
    }
    $html = ob_get_clean();

    echo json_encode([
        "html" => $html,
        "live_count" => $live_count,
        "play_sound" => $play_sound
    ], JSON_UNESCAPED_UNICODE);

    exit;
}

/* ======================
   EXPORT (CSV) - BEFORE OUTPUT
====================== */
if(isset($_GET['export']) && $_GET['export']==='excel'){
    header("Content-Type: text/csv; charset=UTF-8");
    header("Content-Disposition: attachment; filename=reservations.csv");
    echo "\xEF\xBB\xBF";

    $out = fopen("php://output","w");
    fputcsv($out, [
        ($tr['customer_name'] ?? 'الاسم'),
        ($tr['phone'] ?? 'الهاتف'),
        ($tr['date'] ?? 'التاريخ'),
        ($tr['time'] ?? 'الوقت'),
        ($tr['items'] ?? 'الإيتمات'),
        ($tr['total'] ?? 'السعر الإجمالي'),
        ($tr['status'] ?? 'الحالة'),
        ($tr['notes'] ?? 'ملاحظات'),
        ($tr['created_at'] ?? 'تاريخ الإنشاء')
    ]);

    $rows = fetch_all("
        SELECT
            r.*,
            GROUP_CONCAT(
                CONCAT(
                    COALESCE(i.name_ar, i.name, ''),
                    ' x',
                    COALESCE(NULLIF(ri.qty,0), NULLIF(ri.quantity,0), 1)
                )
                SEPARATOR ' / '
            ) AS items_text
        FROM reservations r
        LEFT JOIN reservation_items ri ON ri.reservation_id = r.id
        LEFT JOIN items i ON i.id = ri.item_id
        WHERE $where
        GROUP BY r.id
        ORDER BY r.reservation_date DESC, r.reservation_time DESC, r.created_at DESC
    ", $params);

    foreach($rows as $r){
        fputcsv($out, [
            (string)($r['customer_name'] ?? ''),
            (string)($r['customer_phone'] ?? ''),
            (string)($r['reservation_date'] ?? ''),
            time12($r['reservation_time'] ?? ''),
            (string)($r['items_text'] ?? ''),
            (string)($r['total_price'] ?? 0),
            (string)($r['status'] ?? ''),
            (string)($r['notes'] ?? ''),
            (string)($r['created_at'] ?? '')
        ]);
    }

    fclose($out);
    exit;
}

/* ======================
   ACTIONS (NO AJAX) - POST
====================== */
if($_SERVER['REQUEST_METHOD']==='POST'){
    $action = $_POST['action'] ?? '';

    // SETTINGS CRUD
    if($action==='add_setting' && $role==='manager'){
        $from = $_POST['from_time'] ?? '10:00';
        $to   = $_POST['to_time']   ?? '23:00';
        $mins = (int)($_POST['slot_minutes'] ?? 30);
        if($mins < 5) $mins = 5;
        $active = isset($_POST['active']) ? 1 : 0;

        db()->prepare("
            INSERT INTO reservation_settings (restaurant_id, from_time, to_time, slot_minutes, active)
            VALUES (?,?,?,?,?)
        ")->execute([$restaurant_id,$from,$to,$mins,$active]);

        header("Location: reservations.php"); exit;
    }

    if($action==='update_setting' && $role==='manager'){
        $id = (int)$_POST['id'];
        $from = $_POST['from_time'] ?? '10:00';
        $to   = $_POST['to_time']   ?? '23:00';
        $mins = (int)($_POST['slot_minutes'] ?? 30);
        if($mins < 5) $mins = 5;
        $active = isset($_POST['active']) ? 1 : 0;

        db()->prepare("
            UPDATE reservation_settings
            SET from_time=?, to_time=?, slot_minutes=?, active=?
            WHERE id=? AND restaurant_id=?
        ")->execute([$from,$to,$mins,$active,$id,$restaurant_id]);

        header("Location: reservations.php"); exit;
    }

    if($action==='delete_setting' && $role==='manager'){
        $id = (int)$_POST['id'];
        db()->prepare("DELETE FROM reservation_settings WHERE id=? AND restaurant_id=?")
          ->execute([$id,$restaurant_id]);

        header("Location: reservations.php"); exit;
    }

    // ADD MANUAL RESERVATION
    if($action==='add_manual' && $role==='manager'){
        $name  = clean($_POST['customer_name'] ?? '');
        $phone = clean($_POST['customer_phone'] ?? '');
        $rdate = $_POST['reservation_date'] ?? '';
        $rtime = $_POST['reservation_time'] ?? '';
        if(preg_match('/^\d{2}:\d{2}$/', $rtime)) $rtime .= ':00';

        if($name && $phone && $rdate && $rtime){
            db()->prepare("
                INSERT INTO reservations
                (restaurant_id, customer_name, customer_phone, reservation_date, reservation_time, total_price, status, notes, created_at)
                VALUES (?,?,?,?,?,0,'pending','',NOW())
            ")->execute([$restaurant_id,$name,$phone,$rdate,$rtime]);
        }

        header("Location: reservations.php"); exit;
    }

    // STATUS FLOW
    if($action==='confirm_reservation' && $role==='manager'){
        $res_id = (int)$_POST['res_id'];
        $time   = $_POST['reservation_time'] ?? '';
        if(preg_match('/^\d{2}:\d{2}$/', $time)) $time .= ':00';

        db()->prepare("
            UPDATE reservations
            SET status='confirmed', reservation_time=?
            WHERE id=? AND restaurant_id=? AND status='pending'
        ")->execute([$time,$res_id,$restaurant_id]);

        header("Location: reservations.php"); exit;
    }

    if($action==='complete_reservation' && $role==='manager'){
        $res_id = (int)$_POST['res_id'];
        $notes  = trim($_POST['notes'] ?? '');

        db()->prepare("
            UPDATE reservations
            SET status='completed', notes=?
            WHERE id=? AND restaurant_id=? AND status='confirmed'
        ")->execute([$notes,$res_id,$restaurant_id]);

        header("Location: reservations.php"); exit;
    }

    if($action==='cancel_reservation' && $role==='manager'){
        $res_id = (int)$_POST['res_id'];
        db()->prepare("
            UPDATE reservations
            SET status='cancelled'
            WHERE id=? AND restaurant_id=? AND status IN('pending','confirmed')
        ")->execute([$res_id,$restaurant_id]);

        header("Location: reservations.php"); exit;
    }
}

/* ======================
   SETTINGS LIST (for modal)
====================== */
$settings_list = fetch_all("
    SELECT * FROM reservation_settings
    WHERE restaurant_id=?
    ORDER BY id DESC
", [$restaurant_id]);

/* ======================
   LIVE RESERVATIONS (initial render)
====================== */
$live_rows = fetch_all("
    SELECT
        r.*,
        GROUP_CONCAT(
            CONCAT(
                COALESCE(i.name_ar, i.name, ''),
                ' x',
                COALESCE(NULLIF(ri.qty,0), NULLIF(ri.quantity,0), 1)
            )
            SEPARATOR ' / '
        ) AS items_text
    FROM reservations r
    LEFT JOIN reservation_items ri ON ri.reservation_id = r.id
    LEFT JOIN items i ON i.id = ri.item_id
    WHERE r.restaurant_id = ?
      AND r.status IN('pending','confirmed')
    GROUP BY r.id
    ORDER BY r.created_at DESC
", [$restaurant_id]);

/* ======================
   REPORT DATA (filtered)
====================== */
$report_rows = fetch_all("
    SELECT
        r.*,
        GROUP_CONCAT(
            CONCAT(
                COALESCE(i.name_ar, i.name, ''),
                ' x',
                COALESCE(NULLIF(ri.qty,0), NULLIF(ri.quantity,0), 1)
            )
            SEPARATOR ' / '
        ) AS items_text
    FROM reservations r
    LEFT JOIN reservation_items ri ON ri.reservation_id = r.id
    LEFT JOIN items i ON i.id = ri.item_id
    WHERE $where
    GROUP BY r.id
    ORDER BY r.reservation_date DESC, r.reservation_time DESC, r.created_at DESC
", $params);

$report_total = count($report_rows);
$report_pending = 0; $report_confirmed = 0; $report_completed = 0; $report_cancelled = 0;
foreach($report_rows as $rr){
    $st = (string)($rr['status'] ?? '');
    if($st==='pending') $report_pending++;
    elseif($st==='confirmed') $report_confirmed++;
    elseif($st==='completed') $report_completed++;
    elseif($st==='cancelled') $report_cancelled++;
}

$top_time = fetch_one("
    SELECT r.reservation_time, COUNT(*) AS total
    FROM reservations r
    WHERE $where AND r.reservation_time IS NOT NULL AND r.reservation_time <> ''
    GROUP BY r.reservation_time
    ORDER BY total DESC
    LIMIT 1
", $params);

$repeat_customers = fetch_all("
    SELECT r.customer_phone, r.customer_name, COUNT(*) AS total
    FROM reservations r
    WHERE $where
      AND r.customer_phone IS NOT NULL AND r.customer_phone <> ''
    GROUP BY r.customer_phone, r.customer_name
    HAVING total >= 2
    ORDER BY total DESC
    LIMIT 10
", $params);

/* ======================
   UI
====================== */
$page_title = $tr['reservations'] ?? "إدارة الحجوزات";
require_once __DIR__ . "/includes/header.php";
?>

<style>
h1{margin-top:0;font-size:28px;}
.cards{display:grid;grid-template-columns:repeat(4,1fr);gap:20px;margin-bottom:30px;}
.card{background:#1c1c1c;padding:22px;border-radius:12px;border:1px solid #333;}
.card h3{margin:0;font-size:18px;color:#ccc;}
.card .num{font-size:34px;color:#ff7a00;margin-top:10px;font-weight:bold;}

.table-box{background:#1c1c1c;padding:20px;border-radius:14px;border:1px solid #333;margin-top:20px;}
table{width:100%;border-collapse:collapse;}
th,td{padding:12px;border-bottom:1px solid #333;vertical-align:top;}
th{background:#222;color:#ff7a00;font-size:15px;text-align:right;}

.filter-box{
    background:#1c1c1c;padding:15px;border-radius:12px;border:1px solid #333;margin-bottom:18px;
    display:flex; gap:10px; align-items:end; flex-wrap:wrap;
}
.filter-box label{display:block;margin-bottom:6px;color:#ccc;font-size:14px;}
.filter-box select,.filter-box input,.filter-box textarea{
    width:220px;max-width:100%;padding:10px;background:#111;border:1px solid #333;border-radius:8px;color:#fff;
}
.filter-box .full{width:100%}
.filter-box button,.filter-box a.btnlink{
    display:inline-block;background:#ff7a00;padding:10px 18px;border:none;border-radius:8px;color:#000;font-weight:bold;cursor:pointer;
    text-decoration:none;
}
.filter-box button:hover,.filter-box a.btnlink:hover{background:#e06b00;}

.btn{padding:8px 12px;border-radius:8px;border:none;cursor:pointer;font-weight:bold;text-decoration:none;display:inline-block;}
.btn-dark{background:#333;color:#fff}
.btn-green{background:#28a745;color:#fff}
.btn-red{background:#dc3545;color:#fff}
.badge{padding:6px 10px;border-radius:6px;font-size:13px;font-weight:bold}
.pending{background:#ff9800;color:#000}
.confirmed{background:#28a745;color:#fff}
.completed{background:#0dcaf0;color:#000}
.cancelled{background:#dc3545;color:#fff}

/* MODAL */
.modal-backdrop{display:none; position:fixed; inset:0; background:rgba(0,0,0,.65); z-index:999;}
.modal{
    width:min(720px, 94vw);
    background:#1c1c1c;border:1px solid #333;border-radius:14px;
    padding:16px;
    margin:8vh auto 0 auto;
}
.modal h3{margin:0 0 12px 0;color:#ff7a00}
.modal .row{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.modal small{color:#aaa}
.modal .actions{display:flex;gap:10px;justify-content:flex-end;margin-top:12px}

/* responsive cards */
@media(max-width:900px){ .cards{grid-template-columns:repeat(2,1fr);} }
@media(max-width:600px){ .cards{grid-template-columns:repeat(1,1fr);} }
</style>

<h1>📅 <?= e($tr['reservations'] ?? "إدارة الحجوزات") ?></h1>

<!-- TOP BUTTONS -->
<div class="filter-box">
    <div>
        <label>&nbsp;</label>
        <button type="button" onclick="openModal('modalSlots')">
            ⏰ <?= e($tr['available_times'] ?? 'أوقات الحجز المتاحة') ?>
        </button>
    </div>

    <?php if($role==='manager'): ?>
    <div>
        <label>&nbsp;</label>
        <button type="button" onclick="openModal('modalAddManual')">
            ➕ <?= e($tr['add_reservation'] ?? 'إضافة حجز') ?>
        </button>
    </div>
    <?php endif; ?>

    <div style="margin-left:auto;">
        <label><?= e($tr['live_status'] ?? 'الحجوزات اللحظية') ?></label>
        <div style="color:#ccc">
            <?= e($tr['auto_refresh_note'] ?? '.') ?>
        </div>
    </div>
</div>

<!-- LIVE TABLE -->
<div class="table-box">
    <h2>📥 <?= e($tr['live_reservations'] ?? 'الحجوزات الحالية') ?></h2>

    <table>
        <thead>
        <tr>
            <th><?= e($tr['customer_name'] ?? 'الاسم') ?></th>
            <th><?= e($tr['phone'] ?? 'الهاتف') ?></th>
            <th><?= e($tr['date'] ?? 'التاريخ') ?></th>
            <th><?= e($tr['time'] ?? 'الوقت') ?></th>
            <th><?= e($tr['items'] ?? 'الإيتمات') ?></th>
            <th><?= e($tr['total'] ?? 'السعر') ?></th>
            <th><?= e($tr['status'] ?? 'الحالة') ?></th>
            <th><?= e($tr['actions'] ?? 'تحكم') ?></th>
        </tr>
        </thead>

        <tbody id="liveTbody">
        <?php foreach($live_rows as $r):
            $rid = (int)$r['id'];
            $phone_wa = clean_phone_digits($r['customer_phone']);
            $status = (string)($r['status'] ?? 'pending');
            $badge_text = $tr[$status] ?? $status;

            // WhatsApp message (EDIT HERE LATER)
            $wa_text =
                ($tr['reservation_msg_title'] ?? "Reservation Details")."\n".
                ($tr['customer_name'] ?? "Name").": ".($r['customer_name'] ?? "")."\n".
                ($tr['date'] ?? "Date").": ".($r['reservation_date'] ?? "")."\n".
                ($tr['time'] ?? "Time").": ".(time12($r['reservation_time'] ?? ''))."\n".
                ($tr['total'] ?? "Total").": ".($r['total_price'] ?? 0)." IQD\n".
                ($tr['items'] ?? "Items").": ".($r['items_text'] ?? "");
        ?>
        <tr>
            <td><?= e($r['customer_name']) ?></td>
            <td><?= e($r['customer_phone']) ?></td>
            <td><?= e($r['reservation_date']) ?></td>
            <td><?= time12($r['reservation_time']) ?></td>
            <td><?= e($r['items_text'] ?? '') ?></td>
            <td><?= number_format((float)($r['total_price'] ?? 0),0) ?></td>
            <td><span class="badge <?= e($status) ?>"><?= e($badge_text) ?></span></td>
            <td>
                <?php if($phone_wa !== ''): ?>
                <a class="btn btn-dark" target="_blank"
                   href="https://wa.me/<?= e($phone_wa) ?>?text=<?= urlencode($wa_text) ?>">
                    WhatsApp
                </a>
                <?php endif; ?>

                <?php if($role==='manager'): ?>
                    <?php if($status==='pending'): ?>
                        <button class="btn btn-green" onclick="openConfirmModal(<?= $rid ?>)">✔ <?= e($tr['accept'] ?? 'قبول') ?></button>
                        <button class="btn btn-red" onclick="openCancelModal(<?= $rid ?>)">✖ <?= e($tr['cancel'] ?? 'إلغاء') ?></button>
                    <?php elseif($status==='confirmed'): ?>
                        <button class="btn btn-green" onclick="openCompleteModal(<?= $rid ?>)">✔ <?= e($tr['complete'] ?? 'مكتمل') ?></button>
                        <button class="btn btn-red" onclick="openCancelModal(<?= $rid ?>)">✖ <?= e($tr['cancel'] ?? 'إلغاء') ?></button>
                    <?php endif; ?>
                <?php endif; ?>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- REPORTS -->
<h1 style="margin-top:30px;">📊 <?= e($tr['reports'] ?? 'تقارير الحجوزات') ?></h1>

<div class="filter-box">
<form method="GET" id="reportForm" style="display:flex;gap:10px;flex-wrap:wrap;align-items:end;">

    <div>
        <label><?= e($tr['date_type'] ?? 'نوع التاريخ') ?></label>
        <select name="type" id="type" onchange="changeType()">
            <option value="all"   <?= $type==='all'?'selected':'' ?>><?= e($tr['all_periods'] ?? 'كل الفترات') ?></option>
            <option value="month" <?= $type==='month'?'selected':'' ?>><?= e($tr['by_month'] ?? 'حسب شهر') ?></option>
            <option value="day"   <?= $type==='day'?'selected':'' ?>><?= e($tr['by_day'] ?? 'حسب يوم') ?></option>
        </select>
    </div>

    <div id="monthBox" style="display:<?= $type==='month'?'block':'none' ?>;">
        <label><?= e($tr['choose_month'] ?? 'اختر الشهر') ?></label>
        <input type="month" name="date" value="<?= e($date ?? '') ?>">
    </div>

    <div id="dayBox" style="display:<?= $type==='day'?'block':'none' ?>;">
        <label><?= e($tr['choose_day'] ?? 'اختر اليوم') ?></label>
        <input type="date" name="date" value="<?= e($date ?? '') ?>">
    </div>

    <button type="submit">🔎 <?= e($tr['apply'] ?? 'تطبيق') ?></button>

    <a class="btnlink" href="?type=<?= urlencode($type) ?>&date=<?= urlencode($date ?? '') ?>&export=excel">
        ⬇ <?= e($tr['export_excel'] ?? 'تصدير Excel') ?>
    </a>

</form>
</div>

<div class="cards">
    <div class="card"><h3><?= e($tr['total_reservations'] ?? 'إجمالي الحجوزات') ?></h3><div class="num"><?= (int)$report_total ?></div></div>
    <div class="card"><h3><?= e($tr['pending'] ?? 'Pending') ?></h3><div class="num"><?= (int)$report_pending ?></div></div>
    <div class="card"><h3><?= e($tr['confirmed'] ?? 'Confirmed') ?></h3><div class="num"><?= (int)$report_confirmed ?></div></div>
    <div class="card"><h3><?= e($tr['completed'] ?? 'Completed') ?></h3><div class="num"><?= (int)$report_completed ?></div></div>
</div>

<div class="cards">
    <div class="card"><h3><?= e($tr['cancelled'] ?? 'Cancelled') ?></h3><div class="num"><?= (int)$report_cancelled ?></div></div>
    <div class="card"><h3><?= e($tr['top_time'] ?? 'أكثر وقت حجز') ?></h3><div class="num"><?= $top_time ? e(time12($top_time['reservation_time'])) : '—' ?></div></div>
    <div class="card"><h3><?= e($tr['repeat_customers'] ?? 'تكرار زبائن') ?></h3><div class="num"><?= (int)count($repeat_customers) ?></div></div>
    <div class="card"><h3><?= e($tr['not_completed'] ?? 'غير مكتمل') ?></h3><div class="num"><?= (int)($report_pending + $report_confirmed) ?></div></div>
</div>

<div class="table-box">
    <h2><?= e($tr['repeat_customers_title'] ?? 'أكثر الزبائن تكراراً') ?></h2>
    <table>
        <tr>
            <th><?= e($tr['customer_name'] ?? 'الاسم') ?></th>
            <th><?= e($tr['phone'] ?? 'الهاتف') ?></th>
            <th><?= e($tr['count'] ?? 'عدد الحجوزات') ?></th>
        </tr>
        <?php foreach($repeat_customers as $rc): ?>
        <tr>
            <td><?= e($rc['customer_name']) ?></td>
            <td><?= e($rc['customer_phone']) ?></td>
            <td><?= (int)$rc['total'] ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<div class="table-box">
    <h2>📋 <?= e($tr['reservations_table'] ?? 'جدول الحجوزات') ?></h2>
    <table>
        <tr>
            <th><?= e($tr['customer_name'] ?? 'الاسم') ?></th>
            <th><?= e($tr['phone'] ?? 'الهاتف') ?></th>
            <th><?= e($tr['date'] ?? 'التاريخ') ?></th>
            <th><?= e($tr['time'] ?? 'الوقت') ?></th>
            <th><?= e($tr['items'] ?? 'الإيتمات') ?></th>
            <th><?= e($tr['total'] ?? 'السعر') ?></th>
            <th><?= e($tr['status'] ?? 'الحالة') ?></th>
            <th><?= e($tr['notes'] ?? 'ملاحظات') ?></th>
        </tr>
        <?php foreach($report_rows as $r):
            $st = (string)($r['status'] ?? '');
            $badge_text = $tr[$st] ?? $st;
        ?>
        <tr>
            <td><?= e($r['customer_name']) ?></td>
            <td><?= e($r['customer_phone']) ?></td>
            <td><?= e($r['reservation_date']) ?></td>
            <td><?= time12($r['reservation_time']) ?></td>
            <td><?= e($r['items_text'] ?? '') ?></td>
            <td><?= number_format((float)($r['total_price'] ?? 0),0) ?></td>
            <td><span class="badge <?= e($st) ?>"><?= e($badge_text) ?></span></td>
            <td><?= e($r['notes'] ?? '') ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>

<!-- =========================
     MODALS
========================= -->

<!-- Slots modal -->
<div class="modal-backdrop" id="modalSlots">
  <div class="modal">
    <h3>⏰ <?= e($tr['available_times'] ?? 'أوقات الحجز المتاحة') ?></h3>
    <small><?= e($tr['slots_note'] ?? 'يمكن إضافة أكثر من فترة (مثلاً غداء/عشاء) عبر سجلات متعددة.') ?></small>

    <?php if($role==='manager'): ?>
    <div class="table-box" style="margin-top:12px;">
      <form method="post" style="display:flex;gap:10px;flex-wrap:wrap;align-items:end;">
        <input type="hidden" name="action" value="add_setting">
        <div>
          <label><?= e($tr['from'] ?? 'من') ?></label>
          <input type="time" name="from_time" required>
        </div>
        <div>
          <label><?= e($tr['to'] ?? 'إلى') ?></label>
          <input type="time" name="to_time" required>
        </div>
        <div>
          <label><?= e($tr['every_minutes'] ?? 'كل (دقيقة)') ?></label>
          <input type="number" name="slot_minutes" value="30" min="5" required>
        </div>
        <div>
          <label style="display:flex;gap:8px;align-items:center;margin-top:28px;">
            <input type="checkbox" name="active" checked>
            <?= e($tr['active'] ?? 'فعال') ?>
          </label>
        </div>
        <div>
          <button type="submit">➕ <?= e($tr['add'] ?? 'إضافة') ?></button>
        </div>
      </form>
    </div>
    <?php endif; ?>

    <div class="table-box" style="margin-top:12px;">
      <table>
        <tr>
          <th>ID</th>
          <th><?= e($tr['from'] ?? 'من') ?></th>
          <th><?= e($tr['to'] ?? 'إلى') ?></th>
          <th><?= e($tr['every_minutes'] ?? 'كل (دقيقة)') ?></th>
          <th><?= e($tr['status'] ?? 'الحالة') ?></th>
          <?php if($role==='manager'): ?><th><?= e($tr['actions'] ?? 'تحكم') ?></th><?php endif; ?>
        </tr>
        <?php foreach($settings_list as $s): ?>
        <tr>
          <td><?= (int)$s['id'] ?></td>
          <td><?= e($s['from_time']) ?></td>
          <td><?= e($s['to_time']) ?></td>
          <td><?= (int)$s['slot_minutes'] ?></td>
          <td><?= $s['active'] ? '<span class="badge confirmed">'.e($tr['active'] ?? 'فعال').'</span>' : '<span class="badge cancelled">'.e($tr['stopped'] ?? 'متوقف').'</span>' ?></td>
          <?php if($role==='manager'): ?>
          <td>
            <button class="btn btn-dark" type="button"
              onclick="openEditSetting(<?= (int)$s['id'] ?>,'<?= e($s['from_time']) ?>','<?= e($s['to_time']) ?>',<?= (int)$s['slot_minutes'] ?>,<?= (int)$s['active'] ?>)">
              <?= e($tr['edit'] ?? 'تعديل') ?>
            </button>
            <button class="btn btn-red" type="button" onclick="openDeleteSetting(<?= (int)$s['id'] ?>)">
              <?= e($tr['delete'] ?? 'حذف') ?>
            </button>
          </td>
          <?php endif; ?>
        </tr>
        <?php endforeach; ?>
      </table>
    </div>

    <div class="actions">
      <button type="button" class="btn btn-dark" onclick="closeModal('modalSlots')"><?= e($tr['close'] ?? 'إغلاق') ?></button>
    </div>
  </div>
</div>

<!-- Manual add modal -->
<div class="modal-backdrop" id="modalAddManual">
  <div class="modal">
    <h3>➕ <?= e($tr['add_reservation'] ?? 'إضافة حجز') ?></h3>
    <form method="post">
      <input type="hidden" name="action" value="add_manual">
      <div class="row">
        <div>
          <label><?= e($tr['customer_name'] ?? 'الاسم') ?></label>
          <input type="text" name="customer_name" required>
        </div>
        <div>
          <label><?= e($tr['customer_phone'] ?? 'الهاتف') ?></label>
          <input type="text" name="customer_phone" required>
        </div>
        <div>
          <label><?= e($tr['date'] ?? 'التاريخ') ?></label>
          <input type="date" name="reservation_date" required>
        </div>
        <div>
          <label><?= e($tr['time'] ?? 'الوقت') ?></label>
          <input type="time" name="reservation_time" required>
        </div>
      </div>

      <div class="actions">
        <button type="button" class="btn btn-dark" onclick="closeModal('modalAddManual')"><?= e($tr['cancel'] ?? 'إلغاء') ?></button>
        <button type="submit" class="btn btn-green"><?= e($tr['add'] ?? 'إضافة') ?></button>
      </div>
    </form>
  </div>
</div>

<!-- Confirm modal -->
<div class="modal-backdrop" id="modalConfirm">
  <div class="modal">
    <h3><?= e($tr['accept_reservation'] ?? 'قبول الحجز') ?></h3>
    <small><?= e($tr['choose_exact_time'] ?? 'اختر وقت الحضور بدقة') ?></small>

    <form method="post">
      <input type="hidden" name="action" value="confirm_reservation">
      <input type="hidden" name="res_id" id="confirm_res_id" value="">
      <label><?= e($tr['time'] ?? 'الوقت') ?></label>
      <input type="time" name="reservation_time" required>

      <div class="actions">
        <button type="button" class="btn btn-dark" onclick="closeModal('modalConfirm')"><?= e($tr['cancel'] ?? 'إلغاء') ?></button>
        <button type="submit" class="btn btn-green"><?= e($tr['confirm'] ?? 'تأكيد') ?></button>
      </div>
    </form>
  </div>
</div>

<!-- Complete modal -->
<div class="modal-backdrop" id="modalComplete">
  <div class="modal">
    <h3><?= e($tr['complete_reservation'] ?? 'إكمال الحجز') ?></h3>
    <small><?= e($tr['notes_optional'] ?? 'الملاحظات اختيارية') ?></small>

    <form method="post">
      <input type="hidden" name="action" value="complete_reservation">
      <input type="hidden" name="res_id" id="complete_res_id" value="">
      <label><?= e($tr['notes'] ?? 'ملاحظات') ?></label>
      <textarea name="notes" rows="4" class="full" placeholder="<?= e($tr['write_notes'] ?? 'اكتب ملاحظات إن وجدت...') ?>"></textarea>

      <div class="actions">
        <button type="button" class="btn btn-dark" onclick="closeModal('modalComplete')"><?= e($tr['back'] ?? 'رجوع') ?></button>
        <button type="submit" class="btn btn-green"><?= e($tr['confirm_complete'] ?? 'تأكيد مكتمل') ?></button>
      </div>
    </form>
  </div>
</div>

<!-- Cancel modal -->
<div class="modal-backdrop" id="modalCancel">
  <div class="modal">
    <h3><?= e($tr['confirm_cancel'] ?? 'تأكيد الإلغاء') ?></h3>
    <small><?= e($tr['cancel_note'] ?? 'هل أنت متأكد من الإلغاء؟') ?></small>

    <form method="post">
      <input type="hidden" name="action" value="cancel_reservation">
      <input type="hidden" name="res_id" id="cancel_res_id" value="">
      <div class="actions">
        <button type="button" class="btn btn-dark" onclick="closeModal('modalCancel')"><?= e($tr['no'] ?? 'لا') ?></button>
        <button type="submit" class="btn btn-red"><?= e($tr['yes_cancel'] ?? 'نعم، إلغاء') ?></button>
      </div>
    </form>
  </div>
</div>

<!-- Edit setting modal -->
<div class="modal-backdrop" id="modalEditSetting">
  <div class="modal">
    <h3><?= e($tr['edit_time'] ?? 'تعديل وقت الحجز') ?></h3>
    <form method="post">
      <input type="hidden" name="action" value="update_setting">
      <input type="hidden" name="id" id="set_id" value="">
      <div class="row">
        <div>
          <label><?= e($tr['from'] ?? 'من') ?></label>
          <input type="time" name="from_time" id="set_from" required>
        </div>
        <div>
          <label><?= e($tr['to'] ?? 'إلى') ?></label>
          <input type="time" name="to_time" id="set_to" required>
        </div>
        <div>
          <label><?= e($tr['every_minutes'] ?? 'كل (دقيقة)') ?></label>
          <input type="number" name="slot_minutes" id="set_min" min="5" required>
        </div>
        <div>
          <label style="display:flex;gap:8px;align-items:center;margin-top:28px;">
            <input type="checkbox" name="active" id="set_active">
            <?= e($tr['active'] ?? 'فعال') ?>
          </label>
        </div>
      </div>

      <div class="actions">
        <button type="button" class="btn btn-dark" onclick="closeModal('modalEditSetting')"><?= e($tr['close'] ?? 'إغلاق') ?></button>
        <button type="submit" class="btn btn-green"><?= e($tr['save'] ?? 'حفظ') ?></button>
      </div>
    </form>
  </div>
</div>

<!-- Delete setting modal -->
<div class="modal-backdrop" id="modalDeleteSetting">
  <div class="modal">
    <h3><?= e($tr['delete_time'] ?? 'حذف وقت الحجز') ?></h3>
    <small><?= e($tr['delete_note'] ?? 'هل تريد حذف هذا السجل نهائياً؟') ?></small>

    <form method="post">
      <input type="hidden" name="action" value="delete_setting">
      <input type="hidden" name="id" id="del_set_id" value="">
      <div class="actions">
        <button type="button" class="btn btn-dark" onclick="closeModal('modalDeleteSetting')"><?= e($tr['no'] ?? 'لا') ?></button>
        <button type="submit" class="btn btn-red"><?= e($tr['yes_delete'] ?? 'نعم، حذف') ?></button>
      </div>
    </form>
  </div>
</div>

<script>
function changeType(){
  const type = document.getElementById("type").value;
  document.getElementById("monthBox").style.display = (type === "month") ? "block" : "none";
  document.getElementById("dayBox").style.display   = (type === "day") ? "block" : "none";
}

function openModal(id){ document.getElementById(id).style.display='block'; }
function closeModal(id){ document.getElementById(id).style.display='none'; }

function openConfirmModal(resId){
  document.getElementById('confirm_res_id').value = resId;
  openModal('modalConfirm');
}
function openCompleteModal(resId){
  document.getElementById('complete_res_id').value = resId;
  openModal('modalComplete');
}
function openCancelModal(resId){
  document.getElementById('cancel_res_id').value = resId;
  openModal('modalCancel');
}
function openEditSetting(id, from, to, mins, active){
  document.getElementById('set_id').value = id;
  document.getElementById('set_from').value = from;
  document.getElementById('set_to').value = to;
  document.getElementById('set_min').value = mins;
  document.getElementById('set_active').checked = (active == 1);
  openModal('modalEditSetting');
}
function openDeleteSetting(id){
  document.getElementById('del_set_id').value = id;
  openModal('modalDeleteSetting');
}

/* ======================
   LIVE REFRESH (table only) + SOUND
====================== */
let lastLiveCount = null;

function playNotify(){
  // Try audio element first (if you already have a file)
  let a = document.getElementById('notifyAudio');
  if(a){
    a.currentTime = 0;
    a.play().catch(()=>beep());
  }else{
    beep();
  }
}

// fallback beep without any files
function beep(){
  try{
    const ctx = new (window.AudioContext || window.webkitAudioContext)();
    const o = ctx.createOscillator();
    const g = ctx.createGain();
    o.connect(g); g.connect(ctx.destination);
    o.frequency.value = 880;
    o.start();
    g.gain.setValueAtTime(0.08, ctx.currentTime);
    g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.25);
    o.stop(ctx.currentTime + 0.25);
  }catch(e){}
}

async function refreshLiveTable(){
  try{
    const res = await fetch('reservations.php?ajax=live&_=' + Date.now(), {cache:'no-store'});
    const data = await res.json();

    const tbody = document.getElementById('liveTbody');
    if(tbody && typeof data.html === 'string'){
      tbody.innerHTML = data.html;
    }

    if(data.play_sound){
      playNotify();
    }

    lastLiveCount = data.live_count;
  }catch(e){
    // ignore
  }
}

// run every 6 seconds
refreshLiveTable();
setInterval(refreshLiveTable, 6000);
</script>

<!-- Optional: if you have a sound file, put it here (no requirement) -->
<audio id="notifyAudio" preload="auto">
  <!-- ضع مسار ملف الصوت إذا موجود عندك -->
  <!-- <source src="assets/notify.mp3" type="audio/mpeg"> -->
</audio>

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