<?php
require_once __DIR__ . '/../core/auth.php';
require_login();
date_default_timezone_set('Africa/Cairo');
$pdo = db();

/* ============ Utilities ============ */
function json_out($data, $code=200){
  http_response_code($code);
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($data, JSON_UNESCAPED_UNICODE);
  exit;
}
function sanitize_dt($s){
  // يقبل: 2025-09-20 14:30 أو 2025-09-20T14:30 من input:datetime-local
  $s = trim((string)$s);
  $s = str_replace('T',' ', $s);
  return $s;
}
function is_available($pdo, $tableId, $from, $to, $excludeId = 0){
  $sql = "SELECT COUNT(*) FROM reservations
          WHERE TableID = ?
            AND Status IN ('pending','confirmed','occupied')
            AND ? < ReservedTo
            AND ? > ReservedFrom";
  $params = [$tableId, $from, $to];
  if ($excludeId > 0) {
    $sql .= " AND ReservationID <> ?";
    $params[] = $excludeId;
  }
  $stmt = $pdo->prepare($sql);
  $stmt->execute($params);
  return $stmt->fetchColumn() == 0;
}

/* ============ AJAX Endpoints ============ */
if (isset($_GET['action'])) {
  $act = $_GET['action'];

  // 0) هرمية الاختيارات
  if ($act === 'get_floors') {
    $branch = (int)($_GET['branch_id'] ?? 0);
    $stmt = $pdo->prepare("SELECT FloorID, FloorName FROM floors WHERE BranchID=? ORDER BY FloorName");
    $stmt->execute([$branch]);
    json_out($stmt->fetchAll(PDO::FETCH_ASSOC));
  }
  if ($act === 'get_sections') {
    $floor = (int)($_GET['floor_id'] ?? 0);
    $stmt = $pdo->prepare("SELECT SectionID, SectionName FROM sections WHERE FloorID=? ORDER BY SectionName");
    $stmt->execute([$floor]);
    json_out($stmt->fetchAll(PDO::FETCH_ASSOC));
  }
  if ($act === 'get_tables') {
    $section = (int)($_GET['section_id'] ?? 0);
    $stmt = $pdo->prepare("SELECT TableID, TableNumber FROM dining_tables WHERE SectionID=? ORDER BY TableNumber");
    $stmt->execute([$section]);
    json_out($stmt->fetchAll(PDO::FETCH_ASSOC));
  }

  // 1) التحقق من التوافر
  if ($act === 'check_available') {
    $tableId = (int)($_GET['TableID'] ?? 0);
    $from = sanitize_dt($_GET['ReservedFrom'] ?? '');
    $to   = sanitize_dt($_GET['ReservedTo'] ?? '');
    $exclude = (int)($_GET['exclude_id'] ?? 0);
    if (!$tableId || !$from || !$to || strtotime($from) >= strtotime($to)) {
      json_out(['ok'=>false,'msg'=>'بيانات الوقت غير صحيحة'], 400);
    }
    $ok = is_available($pdo, $tableId, $from, $to, $exclude);
    json_out(['ok'=>true,'available'=>$ok]);
  }

  // 2) إنشاء/تعديل حجز
  if ($act === 'save_reservation' && $_SERVER['REQUEST_METHOD']==='POST') {
    $ReservationID = (int)($_POST['ReservationID'] ?? 0);
    $TableID       = (int)($_POST['TableID'] ?? 0);
    $CustomerName  = trim($_POST['CustomerName'] ?? '');
    $CustomerPhone = trim($_POST['CustomerPhone'] ?? '');
    $ReservedFrom  = sanitize_dt($_POST['ReservedFrom'] ?? '');
    $ReservedTo    = sanitize_dt($_POST['ReservedTo'] ?? '');
    $Source        = ($_POST['Source'] ?? 'internal');
    $Notes         = trim($_POST['Notes'] ?? '');

    if (!$TableID || !$ReservedFrom || !$ReservedTo || strtotime($ReservedFrom) >= strtotime($ReservedTo)) {
      json_out(['ok'=>false,'msg'=>'البيانات غير مكتملة أو زمن غير صحيح'], 400);
    }

    // منع التداخل
    if (!is_available($pdo, $TableID, $ReservedFrom, $ReservedTo, $ReservationID)) {
      json_out(['ok'=>false,'msg'=>'الوقت غير متاح لهذه الترابيزة'], 409);
    }

    try {
      if ($ReservationID > 0) {
        $stmt = $pdo->prepare("UPDATE reservations
          SET TableID=?, CustomerName=?, CustomerPhone=?, ReservedFrom=?, ReservedTo=?, Source=?, Notes=?
          WHERE ReservationID=?");
        $stmt->execute([$TableID, $CustomerName, $CustomerPhone, $ReservedFrom, $ReservedTo, $Source, $Notes, $ReservationID]);
        json_out(['ok'=>true,'id'=>$ReservationID,'msg'=>'تم التعديل']);
      } else {
        // داخلي → confirmed / خارجي → pending
        $Status = ($Source === 'online') ? 'pending' : 'confirmed';
        $stmt = $pdo->prepare("INSERT INTO reservations
          (TableID, CustomerName, CustomerPhone, ReservedFrom, ReservedTo, Source, Status, Notes)
          VALUES (?,?,?,?,?,?,?,?)");
        $stmt->execute([$TableID,$CustomerName,$CustomerPhone,$ReservedFrom,$ReservedTo,$Source,$Status,$Notes]);
        json_out(['ok'=>true,'id'=>$pdo->lastInsertId(),'msg'=>'تم الحجز']);
      }
    } catch (Exception $e) {
      json_out(['ok'=>false,'msg'=>'حدث خطأ أثناء الحفظ'], 500);
    }
  }

  // 3) تحديث الحالة
  if ($act === 'update_status' && $_SERVER['REQUEST_METHOD']==='POST') {
    $id = (int)($_POST['ReservationID'] ?? 0);
    $status = strtolower(trim($_POST['Status'] ?? ''));
    $allowed = ['pending','confirmed','occupied','completed','cancelled'];
    if (!$id || !in_array($status, $allowed, true)) json_out(['ok'=>false,'msg'=>'بيانات غير صحيحة'], 400);
    $stmt = $pdo->prepare("UPDATE reservations SET Status=? WHERE ReservationID=?");
    $stmt->execute([$status,$id]);
    json_out(['ok'=>true]);
  }

  // 4) حذف / إلغاء
  if ($act === 'delete_reservation' && $_SERVER['REQUEST_METHOD']==='POST') {
    $id = (int)($_POST['ReservationID'] ?? 0);
    if (!$id) json_out(['ok'=>false], 400);
    $stmt = $pdo->prepare("DELETE FROM reservations WHERE ReservationID=?");
    $stmt->execute([$id]);
    json_out(['ok'=>true]);
  }

  // 5) جلب الحجوزات (حسب فلاتر)
  if ($act === 'list') {
    // فلاتر: branch/floor/section/table, date_from, date_to, status, source
    $where = [];
    $prm = [];

    // الربط بالهرمية
    if (!empty($_GET['BranchID'])) {
      $where[] = "b.BranchID = ?";
      $prm[] = (int)$_GET['BranchID'];
    }
    if (!empty($_GET['FloorID'])) {
      $where[] = "f.FloorID = ?";
      $prm[] = (int)$_GET['FloorID'];
    }
    if (!empty($_GET['SectionID'])) {
      $where[] = "s.SectionID = ?";
      $prm[] = (int)$_GET['SectionID'];
    }
    if (!empty($_GET['TableID'])) {
      $where[] = "r.TableID = ?";
      $prm[] = (int)$_GET['TableID'];
    }

    // التاريخ
    $df = sanitize_dt($_GET['DateFrom'] ?? '');
    $dt = sanitize_dt($_GET['DateTo'] ?? '');
    if ($df && $dt && strtotime($df) <= strtotime($dt)) {
      $where[] = "r.ReservedFrom >= ? AND r.ReservedTo <= ?";
      $prm[] = $df; $prm[] = $dt;
    }

    // الحالة/المصدر
    if (!empty($_GET['Status'])) {
      $where[] = "r.Status = ?";
      $prm[] = $_GET['Status'];
    }
    if (!empty($_GET['Source'])) {
      $where[] = "r.Source = ?";
      $prm[] = $_GET['Source'];
    }

    $sql = "SELECT r.ReservationID, r.TableID, r.CustomerName, r.CustomerPhone, r.ReservedFrom, r.ReservedTo,
                   r.Source, r.Status, r.Notes, r.CreatedAt,
                   t.TableNumber, t.Seats,
                   s.SectionName, f.FloorName, b.BranchName
            FROM reservations r
            JOIN dining_tables t ON r.TableID = t.TableID
            JOIN sections s ON t.SectionID = s.SectionID
            JOIN floors   f ON s.FloorID = f.FloorID
            JOIN branches b ON f.BranchID = b.BranchID";
    if ($where) $sql .= " WHERE " . implode(" AND ", $where);
    $sql .= " ORDER BY r.ReservedFrom DESC";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($prm);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    json_out(['ok'=>true,'rows'=>$rows]);
  }

  json_out(['ok'=>false,'msg'=>'Unknown action'], 400);
}

/* ============ Initial data for filters ============ */
$branches = $pdo->query("SELECT BranchID, BranchName FROM branches WHERE IsActive=1 ORDER BY BranchName")->fetchAll(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <title>إدارة الحجوزات</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Bootstrap / FontAwesome / DataTables -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
  <style>
    :root{
      --bg:#f5f7fa; --text:#1f2937; --muted:#6b7280; --card:#fff; --border:rgba(0,0,0,.08);
      --brand1:#0f2027; --brand2:#203a43; --brand3:#2c5364; --primary:#1abc9c; --primary-600:#16a085;
    }
    body{background:var(--bg); color:var(--text); font-family:"Tajawal", Tahoma, Arial, sans-serif;}
    header{background:linear-gradient(135deg,var(--brand1),var(--brand2),var(--brand3));
      color:#fff; padding:14px 18px; display:flex; align-items:center; justify-content:space-between; gap:12px;
      box-shadow:0 6px 24px rgba(0,0,0,.25); margin-bottom:18px;}
    .panel{background:var(--card); border:1px solid var(--border); border-radius:14px; box-shadow:0 10px 24px rgba(0,0,0,.05);}
    .badge-status{font-size:.8rem}
    .badge-status.pending{background:#fcd34d; color:#92400e}
    .badge-status.confirmed{background:#60a5fa}
    .badge-status.occupied{background:#ef4444}
    .badge-status.completed{background:#e5e7eb; color:#1f2937}
    .badge-status.cancelled{background:#9ca3af}
  </style>
</head>
<body>

<header class="container-fluid">
  <div class="fw-bold"><i class="fa-solid fa-calendar-check"></i> إدارة الحجوزات</div>
  <a href="dashboard.php" class="btn btn-light btn-sm"><i class="fa-solid fa-house"></i> الرئيسية</a>
</header>

<div class="container mb-3">
  <div class="panel p-3">
    <div class="row g-3 align-items-end">
      <div class="col-md-3">
        <label class="form-label">الفرع</label>
        <select id="fBranch" class="form-select">
          <option value="">الكل</option>
          <?php foreach($branches as $b): ?>
            <option value="<?= (int)$b['BranchID'] ?>"><?= htmlspecialchars($b['BranchName']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">الدور</label>
        <select id="fFloor" class="form-select" disabled>
          <option value="">الكل</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">السكشن</label>
        <select id="fSection" class="form-select" disabled>
          <option value="">الكل</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">الترابيزة</label>
        <select id="fTable" class="form-select" disabled>
          <option value="">الكل</option>
        </select>
      </div>

      <div class="col-md-3">
        <label class="form-label">من</label>
        <input type="datetime-local" id="fFrom" class="form-control">
      </div>
      <div class="col-md-3">
        <label class="form-label">إلى</label>
        <input type="datetime-local" id="fTo" class="form-control">
      </div>
      <div class="col-md-3">
        <label class="form-label">الحالة</label>
        <select id="fStatus" class="form-select">
          <option value="">الكل</option>
          <option value="pending">قيد الانتظار</option>
          <option value="confirmed">مؤكد</option>
          <option value="occupied">مشغول</option>
          <option value="completed">مكتمل</option>
          <option value="cancelled">ملغي</option>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">المصدر</label>
        <select id="fSource" class="form-select">
          <option value="">الكل</option>
          <option value="internal">داخلي</option>
          <option value="online">خارجي</option>
        </select>
      </div>

      <div class="col-12 text-end">
        <button id="btnNew" class="btn btn-success"><i class="fa-solid fa-plus"></i> حجز جديد</button>
        <button id="btnRefresh" class="btn btn-primary"><i class="fa-solid fa-rotate"></i> تحديث</button>
      </div>
    </div>
  </div>
</div>

<div class="container">
  <div class="panel p-2">
    <div class="table-responsive p-2">
      <table id="resTable" class="table table-bordered table-hover align-middle text-center">
        <thead class="table-dark">
          <tr>
            <th>#</th>
            <th>الفرع</th>
            <th>الدور</th>
            <th>السكشن</th>
            <th>الترابيزة</th>
            <th>العميل</th>
            <th>الهاتف</th>
            <th>من</th>
            <th>إلى</th>
            <th>المصدر</th>
            <th>الحالة</th>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal: Add/Edit -->
<div class="modal fade" id="resModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form id="resForm">
        <input type="hidden" name="ReservationID" id="ReservationID">
        <div class="modal-header">
          <h6 class="modal-title"><i class="fa-solid fa-pen-to-square"></i> حجز</h6>
          <button type="button" class="btn-close ms-0" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="row g-3">
            <div class="col-md-3">
              <label class="form-label">الفرع</label>
              <select id="mBranch" class="form-select" required>
                <option value="">اختر</option>
                <?php foreach($branches as $b): ?>
                  <option value="<?= (int)$b['BranchID'] ?>"><?= htmlspecialchars($b['BranchName']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label">الدور</label>
              <select id="mFloor" class="form-select" required disabled>
                <option value="">اختر</option>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label">السكشن</label>
              <select id="mSection" class="form-select" required disabled>
                <option value="">اختر</option>
              </select>
            </div>
            <div class="col-md-3">
              <label class="form-label">الترابيزة</label>
              <select name="TableID" id="mTable" class="form-select" required disabled>
                <option value="">اختر</option>
              </select>
            </div>

            <div class="col-md-4">
              <label class="form-label">اسم العميل</label>
              <input type="text" name="CustomerName" id="CustomerName" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label">الهاتف</label>
              <input type="text" name="CustomerPhone" id="CustomerPhone" class="form-control">
            </div>
            <div class="col-md-4">
              <label class="form-label">المصدر</label>
              <select name="Source" id="Source" class="form-select">
                <option value="internal">داخلي</option>
                <option value="online">خارجي</option>
              </select>
            </div>

            <div class="col-md-6">
              <label class="form-label">من</label>
              <input type="datetime-local" name="ReservedFrom" id="ReservedFrom" class="form-control" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">إلى</label>
              <input type="datetime-local" name="ReservedTo" id="ReservedTo" class="form-control" required>
            </div>

            <div class="col-12">
              <label class="form-label">ملاحظات</label>
              <textarea name="Notes" id="Notes" class="form-control" rows="2"></textarea>
            </div>

            <div class="col-12">
              <button id="btnCheck" type="button" class="btn btn-outline-primary">
                <i class="fa-solid fa-magnifying-glass"></i> تحقق من التوافر
              </button>
              <span id="checkResult" class="ms-2"></span>
            </div>

          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" type="submit"><i class="fa-solid fa-floppy-disk"></i> حفظ</button>
          <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">إغلاق</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal: Update Status -->
<div class="modal fade" id="statusModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-sm modal-dialog-centered">
    <div class="modal-content">
      <form id="statusForm">
        <input type="hidden" name="ReservationID" id="sReservationID">
        <div class="modal-header">
          <h6 class="modal-title"><i class="fa-solid fa-clipboard-check"></i> تحديث الحالة</h6>
          <button type="button" class="btn-close ms-0" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <select name="Status" id="sStatus" class="form-select" required>
            <option value="pending">قيد الانتظار</option>
            <option value="confirmed">مؤكد</option>
            <option value="occupied">مشغول</option>
            <option value="completed">مكتمل</option>
            <option value="cancelled">ملغي</option>
          </select>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" type="submit">حفظ</button>
          <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">إلغاء</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- JS libs -->
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script>
let dt;

function escapeHtml(str){
  if (str===null || str===undefined) return '';
  return String(str).replace(/[&<>"'`=\/]/g, s => ({
    '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;','/':'&#x2F;','`':'&#x60;','=':'&#x3D;'
  }[s]));
}

/* ============ Filters hierarchy ============ */
$('#fBranch').on('change', function(){
  const bid = $(this).val();
  $('#fFloor').prop('disabled', true).html('<option value="">الكل</option>');
  $('#fSection').prop('disabled', true).html('<option value="">الكل</option>');
  $('#fTable').prop('disabled', true).html('<option value="">الكل</option>');
  if (!bid) return;
  $.getJSON('?action=get_floors&branch_id='+bid, function(rows){
    let html = '<option value="">الكل</option>';
    rows.forEach(r=> html += `<option value="${r.FloorID}">${escapeHtml(r.FloorName)}</option>`);
    $('#fFloor').html(html).prop('disabled', false);
  });
});
$('#fFloor').on('change', function(){
  const fid = $(this).val();
  $('#fSection').prop('disabled', true).html('<option value="">الكل</option>');
  $('#fTable').prop('disabled', true).html('<option value="">الكل</option>');
  if (!fid) return;
  $.getJSON('?action=get_sections&floor_id='+fid, function(rows){
    let html = '<option value="">الكل</option>';
    rows.forEach(r=> html += `<option value="${r.SectionID}">${escapeHtml(r.SectionName)}</option>`);
    $('#fSection').html(html).prop('disabled', false);
  });
});
$('#fSection').on('change', function(){
  const sid = $(this).val();
  $('#fTable').prop('disabled', true).html('<option value="">الكل</option>');
  if (!sid) return;
  $.getJSON('?action=get_tables&section_id='+sid, function(rows){
    let html = '<option value="">الكل</option>';
    rows.forEach(r=> html += `<option value="${r.TableID}">${escapeHtml(r.TableNumber)}</option>`);
    $('#fTable').html(html).prop('disabled', false);
  });
});

/* ============ List reservations ============ */
function fetchReservations(){
  const q = $.param({
    action:'list',
    BranchID: $('#fBranch').val() || '',
    FloorID:  $('#fFloor').val() || '',
    SectionID:$('#fSection').val() || '',
    TableID:  $('#fTable').val() || '',
    DateFrom: $('#fFrom').val() ? $('#fFrom').val().replace('T',' ') : '',
    DateTo:   $('#fTo').val()   ? $('#fTo').val().replace('T',' ')   : '',
    Status:   $('#fStatus').val() || '',
    Source:   $('#fSource').val() || ''
  });
  $.getJSON('?'+q, function(resp){
    if (!resp.ok) return;
    const rows = resp.rows || [];
    const data = rows.map(r=>{
      const statusBadge =
        `<span class="badge badge-status ${escapeHtml(r.Status)}">${
          r.Status==='pending'?'قيد الانتظار':r.Status==='confirmed'?'مؤكد':r.Status==='occupied'?'مشغول':r.Status==='completed'?'مكتمل':'ملغي'
        }</span>`;
      const srcTxt = r.Source==='online'?'خارجي':'داخلي';
      const actions = `
        <div class="btn-group btn-group-sm">
          <button class="btn btn-outline-primary" onclick='openEdit(${r.ReservationID})'><i class="fa-solid fa-pen"></i></button>
          <button class="btn btn-outline-secondary" onclick='openStatus(${r.ReservationID},"${r.Status}")'><i class="fa-solid fa-clipboard-check"></i></button>
          <button class="btn btn-outline-danger" onclick='delReservation(${r.ReservationID})'><i class="fa-solid fa-trash"></i></button>
        </div>`;
      return [
        r.ReservationID,
        escapeHtml(r.BranchName||''),
        escapeHtml(r.FloorName||''),
        escapeHtml(r.SectionName||''),
        escapeHtml((r.TableNumber||'') + ' ('+(r.Seats||'')+')'),
        escapeHtml(r.CustomerName||''),
        escapeHtml(r.CustomerPhone||''),
        escapeHtml(r.ReservedFrom||''),
        escapeHtml(r.ReservedTo||''),
        srcTxt,
        statusBadge,
        actions
      ];
    });
    if (!dt){
      dt = $('#resTable').DataTable({
        language:{ url:"//cdn.datatables.net/plug-ins/1.13.6/i18n/ar.json" },
        pageLength: 25,
        data: data
      });
    } else {
      dt.clear().rows.add(data).draw();
    }
  });
}
$('#btnRefresh').on('click', fetchReservations);

/* ============ New / Edit Modal hierarchy ============ */
function resetModal(){
  $('#resForm')[0].reset();
  $('#ReservationID').val('');
  $('#mFloor').prop('disabled', true).html('<option value="">اختر</option>');
  $('#mSection').prop('disabled', true).html('<option value="">اختر</option>');
  $('#mTable').prop('disabled', true).html('<option value="">اختر</option>');
  $('#checkResult').text('');
}
$('#btnNew').on('click', ()=>{
  resetModal();
  new bootstrap.Modal(document.getElementById('resModal')).show();
});
$('#mBranch').on('change', function(){
  const bid = $(this).val();
  $('#mFloor').prop('disabled', true).html('<option value="">اختر</option>');
  $('#mSection').prop('disabled', true).html('<option value="">اختر</option>');
  $('#mTable').prop('disabled', true).html('<option value="">اختر</option>');
  if(!bid) return;
  $.getJSON('?action=get_floors&branch_id='+bid, rows=>{
    let html = '<option value="">اختر</option>';
    rows.forEach(r=> html += `<option value="${r.FloorID}">${escapeHtml(r.FloorName)}</option>`);
    $('#mFloor').html(html).prop('disabled', false);
  });
});
$('#mFloor').on('change', function(){
  const fid = $(this).val();
  $('#mSection').prop('disabled', true).html('<option value="">اختر</option>');
  $('#mTable').prop('disabled', true).html('<option value="">اختر</option>');
  if(!fid) return;
  $.getJSON('?action=get_sections&floor_id='+fid, rows=>{
    let html = '<option value="">اختر</option>';
    rows.forEach(r=> html += `<option value="${r.SectionID}">${escapeHtml(r.SectionName)}</option>`);
    $('#mSection').html(html).prop('disabled', false);
  });
});
$('#mSection').on('change', function(){
  const sid = $(this).val();
  $('#mTable').prop('disabled', true).html('<option value="">اختر</option>');
  if(!sid) return;
  $.getJSON('?action=get_tables&section_id='+sid, rows=>{
    let html = '<option value="">اختر</option>';
    rows.forEach(r=> html += `<option value="${r.TableID}">${escapeHtml(r.TableNumber)}</option>`);
    $('#mTable').html(html).prop('disabled', false);
  });
});

/* ============ Check availability ============ */
$('#btnCheck').on('click', function(){
  const id = $('#ReservationID').val() || 0;
  const q = $.param({
    action:'check_available',
    TableID: $('#mTable').val() || 0,
    ReservedFrom: $('#ReservedFrom').val() ? $('#ReservedFrom').val().replace('T',' ') : '',
    ReservedTo:   $('#ReservedTo').val()   ? $('#ReservedTo').val().replace('T',' ')   : '',
    exclude_id: id
  });
  $('#checkResult').removeClass('text-success text-danger').text('جاري التحقق...');
  $.getJSON('?'+q, resp=>{
    if(resp.ok && resp.available){
      $('#checkResult').addClass('text-success').text('متاح ✅');
    }else{
      $('#checkResult').addClass('text-danger').text(resp.msg || 'غير متاح ❌');
    }
  }).fail(()=> $('#checkResult').addClass('text-danger').text('فشل التحقق'));
});

/* ============ Submit save ============ */
$('#resForm').on('submit', function(e){
  e.preventDefault();
  const form = $(this).serialize() + '&action=save_reservation';
  $.post('?action=save_reservation', $(this).serialize(), resp=>{
    if(resp.ok){
      bootstrap.Modal.getInstance(document.getElementById('resModal')).hide();
      fetchReservations();
    }else{
      alert(resp.msg || 'خطأ أثناء الحفظ');
    }
  }, 'json').fail(()=> alert('خطأ أثناء الحفظ'));
});

/* ============ Edit / Status / Delete ============ */
function openEdit(id){
  // نجيب صف الحجز من الجدول الحالي (dt) أو نعيد طلب القائمة ونفلتر
  const data = dt.rows().data().toArray();
  const row = data.find(r => parseInt(r[0])===parseInt(id));
  if (!row) { fetchReservations(); return; }

  resetModal();
  $('#ReservationID').val(id);
  // مبدئياً لا نملك كل المفاتيح الهرمية هنا، فنعيد التحميل بناءً على أسماء/أرقام غير متوفرة.
  // الأفضل إعادة جلب الحجز بالتفاصيل لو حابب توسّع. هنا هنطلب list بفلتر ReservationID:
  $.getJSON('?action=list&ReservationID='+id, function(resp){
    if(!resp.ok || !resp.rows || !resp.rows.length){ return; }
    const r = resp.rows[0];
    // املأ الهرمية
    // 1) Branch -> Floors
    $('#mBranch').val($('#fBranch option').filter(function(){return $(this).text()===r.BranchName;}).val() || '');
    $('#mBranch').trigger('change');
    // ننتظر تحميل floors:
    setTimeout(()=>{
      $('#mFloor').val($('#mFloor option').filter(function(){return $(this).text()===r.FloorName;}).val() || '').trigger('change');
      setTimeout(()=>{
        $('#mSection').val($('#mSection option').filter(function(){return $(this).text()===r.SectionName;}).val() || '').trigger('change');
        setTimeout(()=>{
          $('#mTable').val($('#mTable option').filter(function(){return $(this).text()===r.TableNumber;}).val() || '');
        }, 300);
      }, 300);
    }, 300);

    $('#CustomerName').val(r.CustomerName||'');
    $('#CustomerPhone').val(r.CustomerPhone||'');
    $('#Source').val(r.Source||'internal');
    // صيغة datetime-local تحتاج T
    $('#ReservedFrom').val((r.ReservedFrom||'').replace(' ','T'));
    $('#ReservedTo').val((r.ReservedTo||'').replace(' ','T'));
    $('#Notes').val(r.Notes||'');

    new bootstrap.Modal(document.getElementById('resModal')).show();
  });
}

function openStatus(id, cur){
  $('#sReservationID').val(id);
  $('#sStatus').val(cur);
  new bootstrap.Modal(document.getElementById('statusModal')).show();
}
$('#statusForm').on('submit', function(e){
  e.preventDefault();
  $.post('?action=update_status', $(this).serialize(), resp=>{
    if(resp.ok){
      bootstrap.Modal.getInstance(document.getElementById('statusModal')).hide();
      fetchReservations();
    }
  }, 'json');
});

function delReservation(id){
  if(!confirm('هل تريد حذف هذا الحجز؟')) return;
  $.post('?action=delete_reservation', {ReservationID:id}, resp=>{
    if(resp.ok) fetchReservations();
  }, 'json').fail(()=> alert('فشل الحذف'));
}

/* ============ Init ============ */
// قيم افتراضية لنطاق اليوم
(function setDefaultDates(){
  const now = new Date();
  const yyyy = now.getFullYear();
  const mm = String(now.getMonth()+1).padStart(2,'0');
  const dd = String(now.getDate()).padStart(2,'0');
  $('#fFrom').val(`${yyyy}-${mm}-${dd}T00:00`);
  $('#fTo').val(`${yyyy}-${mm}-${dd}T23:59`);
})();
$(function(){
  dt = $('#resTable').DataTable({ language:{ url:"//cdn.datatables.net/plug-ins/1.13.6/i18n/ar.json" } });
  fetchReservations();
});
</script>
</body>
</html>
