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

/* =====================[ Helpers ]===================== */
function uploadFloorMap($inputName, $dir = 'uploads/floormaps/') {
  if (!isset($_FILES[$inputName]) || $_FILES[$inputName]['error'] !== UPLOAD_ERR_OK) return null;
  if (!is_dir($dir)) mkdir($dir, 0777, true);
  $ext = pathinfo($_FILES[$inputName]['name'], PATHINFO_EXTENSION);
  $safe = time() . '_' . bin2hex(random_bytes(4)) . '.' . strtolower($ext);
  $path = $dir . $safe;
  move_uploaded_file($_FILES[$inputName]['tmp_name'], $path);
  return $safe;
}

/* =====================[ Actions ]===================== */
/* Floors */
if (isset($_POST['save_floor'])) {
  $FloorID   = (int)($_POST['FloorID'] ?? 0);
  $BranchID  = (int)($_POST['BranchID'] ?? 0);
  $FloorName = trim($_POST['FloorName'] ?? '');
  $Description = trim($_POST['Description'] ?? '');
  $map = uploadFloorMap('FloorMap');

  if ($FloorID) {
    if ($map) {
      $stmt = $pdo->prepare("UPDATE floors SET BranchID=?, FloorName=?, Description=?, FloorMap=? WHERE FloorID=?");
      $stmt->execute([$BranchID,$FloorName,$Description,$map,$FloorID]);
    } else {
      $stmt = $pdo->prepare("UPDATE floors SET BranchID=?, FloorName=?, Description=? WHERE FloorID=?");
      $stmt->execute([$BranchID,$FloorName,$Description,$FloorID]);
    }
  } else {
    $stmt = $pdo->prepare("INSERT INTO floors (BranchID, FloorName, Description, FloorMap) VALUES (?,?,?,?)");
    $stmt->execute([$BranchID,$FloorName,$Description,$map]);
  }
  header("Location: ".$_SERVER['PHP_SELF']); exit;
}
if (isset($_GET['del_floor'])) {
  $id = (int)$_GET['del_floor'];
  $pdo->prepare("DELETE FROM floors WHERE FloorID=?")->execute([$id]);
  header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* Sections */
if (isset($_POST['save_section'])) {
  $SectionID = (int)($_POST['SectionID'] ?? 0);
  $FloorID   = (int)($_POST['FloorID'] ?? 0);
  $SectionName = trim($_POST['SectionName'] ?? '');
  $Description = trim($_POST['SecDescription'] ?? '');

  if ($SectionID) {
    $stmt = $pdo->prepare("UPDATE sections SET FloorID=?, SectionName=?, Description=? WHERE SectionID=?");
    $stmt->execute([$FloorID,$SectionName,$Description,$SectionID]);
  } else {
    $stmt = $pdo->prepare("INSERT INTO sections (FloorID, SectionName, Description) VALUES (?,?,?)");
    $stmt->execute([$FloorID,$SectionName,$Description]);
  }
  header("Location: ".$_SERVER['PHP_SELF']); exit;
}
if (isset($_GET['del_section'])) {
  $id = (int)$_GET['del_section'];
  $pdo->prepare("DELETE FROM sections WHERE SectionID=?")->execute([$id]);
  header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* Tables */
if (isset($_POST['save_table'])) {
  $TableID = (int)($_POST['TableID'] ?? 0);
  $SectionID = (int)($_POST['TableSectionID'] ?? 0);
  $TableNumber = trim($_POST['TableNumber'] ?? '');
  $Seats = (int)($_POST['Seats'] ?? 4);
  $Shape = $_POST['Shape'] ?? 'square';
  $PosX  = ($_POST['PosX'] === '' ? null : (int)$_POST['PosX']);
  $PosY  = ($_POST['PosY'] === '' ? null : (int)$_POST['PosY']);
  $QRCode = trim($_POST['QRCode'] ?? '');
  $Status = $_POST['Status'] ?? 'available';

  if ($TableID) {
    $stmt = $pdo->prepare("UPDATE dining_tables SET SectionID=?, TableNumber=?, Seats=?, Shape=?, PosX=?, PosY=?, QRCode=?, Status=? WHERE TableID=?");
    $stmt->execute([$SectionID,$TableNumber,$Seats,$Shape,$PosX,$PosY,$QRCode,$Status,$TableID]);
  } else {
    $stmt = $pdo->prepare("INSERT INTO dining_tables (SectionID, TableNumber, Seats, Shape, PosX, PosY, QRCode, Status) VALUES (?,?,?,?,?,?,?,?)");
    $stmt->execute([$SectionID,$TableNumber,$Seats,$Shape,$PosX,$PosY,$QRCode,$Status]);
  }
  header("Location: ".$_SERVER['PHP_SELF']); exit;
}
if (isset($_GET['del_table'])) {
  $id = (int)$_GET['del_table'];
  $pdo->prepare("DELETE FROM dining_tables WHERE TableID=?")->execute([$id]);
  header("Location: ".$_SERVER['PHP_SELF']); exit;
}

/* =====================[ Data ]===================== */
$branches = $pdo->query("SELECT BranchID, BranchName FROM branches WHERE IsActive=1 ORDER BY BranchName")->fetchAll(PDO::FETCH_ASSOC);
$floors   = $pdo->query("SELECT * FROM floors ORDER BY FloorID DESC")->fetchAll(PDO::FETCH_ASSOC);
$sections = $pdo->query("SELECT * FROM sections ORDER BY SectionID DESC")->fetchAll(PDO::FETCH_ASSOC);
$tables   = $pdo->query("SELECT * FROM dining_tables ORDER BY TableID DESC")->fetchAll(PDO::FETCH_ASSOC);

/* ماب بين IDs للأسماء لتسهيل العرض */
$branchMap = [];
foreach ($branches as $b) $branchMap[$b['BranchID']] = $b['BranchName'];
$floorMap  = [];
foreach ($floors as $f) $floorMap[$f['FloorID']] = $f['FloorName'];
$sectionMap= [];
foreach ($sections as $s) $sectionMap[$s['SectionID']] = $s['SectionName'];
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="utf-8">
  <title>إدارة الأدوار والسكاشن والترابيزات</title>
  <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;
      --panel:#ffffff;
    }
    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;
    }
    .title{font-weight:800; letter-spacing:.3px;}
    .wrap{display:flex; gap:18px; flex-direction:row-reverse; padding:0 18px 18px;}
    .sidebar{
      width:280px; background:#2f3b46; color:#fff; border-radius:14px; padding:12px; height:fit-content;
      position:sticky; top:18px;
    }
    main{flex:1;}
    .card{border:1px solid var(--border); border-radius:14px;}
    .nav-pills .nav-link{font-weight:700}
    .btn-primary{background:var(--primary); border-color:var(--primary)}
    .btn-primary:hover{background:var(--primary-600); border-color:var(--primary-600)}
    /* Floor map canvas container */
    .map-wrap{position:relative; border:1px dashed var(--border); border-radius:12px; background:#fff; overflow:hidden}
    .map-wrap img{width:100%; display:block; user-select:none; pointer-events:none}
    .table-dot{
      position:absolute; width:28px; height:28px; border-radius:50%;
      display:flex; align-items:center; justify-content:center; font-size:12px; color:#fff; cursor:grab;
      background:linear-gradient(135deg,#16a085,#0e7f65); border:2px solid rgba(255,255,255,.9);
      transform:translate(-50%,-50%); /* center at pos */
    }
    .table-dot:active{cursor:grabbing}
    .small-note{color:var(--muted); font-size:12px}
  </style>
</head>
<body>

<header class="d-flex align-items-center justify-content-between">
  <div class="title"><i class="fa-solid fa-table-list"></i> إدارة الأدوار والسكاشن والترابيزات</div>
  <a href="dashboard.php" class="btn btn-light btn-sm"><i class="fa-solid fa-house"></i> الرئيسية</a>
</header>

<div class="wrap">

  <!-- Sidebar (فلترة هرمية + مساعدة) -->
  <aside class="sidebar">
    <h6 class="mb-3">التنقل السريع</h6>
    <ol class="mb-3">
      <li>اختر الفرع</li>
      <li>اختر الدور</li>
      <li>اختر السكشن</li>
      <li>أضف/عدّل ترابيزات</li>
    </ol>
    <div class="small text-white-50">
      <i class="fa-solid fa-circle-info"></i>
      يمكنك رفع خريطة الدور (صورة) ثم سحب وإفلات الدبوس لتحديد مكان الترابيزة.
    </div>
  </aside>

  <!-- Main -->
  <main>

    <!-- Tabs -->
    <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
      <li class="nav-item" role="presentation">
        <button class="nav-link active" id="pills-floors-tab" data-bs-toggle="pill" data-bs-target="#pills-floors" type="button" role="tab">الأدوار (Floors)</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="pills-sections-tab" data-bs-toggle="pill" data-bs-target="#pills-sections" type="button" role="tab">السكاشن (Sections)</button>
      </li>
      <li class="nav-item" role="presentation">
        <button class="nav-link" id="pills-tables-tab" data-bs-toggle="pill" data-bs-target="#pills-tables" type="button" role="tab">الترابيزات (Tables)</button>
      </li>
    </ul>

    <div class="tab-content" id="pills-tabContent">

      <!-- ========== FLOORS ========== -->
      <div class="tab-pane fade show active" id="pills-floors" role="tabpanel">
        <div class="row g-3">
          <div class="col-lg-4">
            <div class="card">
              <div class="card-header bg-light fw-bold">إضافة / تعديل دور</div>
              <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                  <input type="hidden" name="FloorID" id="FloorID">
                  <div class="mb-2">
                    <label class="form-label">الفرع</label>
                    <select name="BranchID" id="FloorBranchID" class="form-select" required>
                      <option value="">— اختر الفرع —</option>
                      <?php foreach($branches as $b): ?>
                        <option value="<?= $b['BranchID'] ?>"><?= htmlspecialchars($b['BranchName']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                  <div class="mb-2">
                    <label class="form-label">اسم الدور</label>
                    <input type="text" name="FloorName" id="FloorName" class="form-control" required placeholder="مثلاً: الدور الأرضي">
                  </div>
                  <div class="mb-2">
                    <label class="form-label">وصف</label>
                    <textarea name="Description" id="FloorDesc" class="form-control" rows="2" placeholder="وصف اختياري"></textarea>
                  </div>
                  <div class="mb-2">
                    <label class="form-label">صورة/خريطة الدور</label>
                    <input type="file" name="FloorMap" accept="image/*" class="form-control">
                    <div class="small-note mt-1">اختياري – JPG/PNG</div>
                  </div>
                  <div class="text-end">
                    <button class="btn btn-primary" name="save_floor"><i class="fa-solid fa-floppy-disk"></i> حفظ</button>
                  </div>
                </form>
              </div>
            </div>
          </div>

          <div class="col-lg-8">
            <div class="card">
              <div class="card-header bg-light fw-bold">قائمة الأدوار</div>
              <div class="card-body">
                <div class="row g-2 mb-2">
                  <div class="col-md-4">
                    <select id="filterBranchFloors" class="form-select">
                      <option value="">فلترة بالفرع</option>
                      <?php foreach($branches as $b): ?>
                        <option value="<?= $b['BranchID'] ?>"><?= htmlspecialchars($b['BranchName']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>
                <div class="table-responsive">
                  <table id="floorsTable" class="table table-striped table-bordered align-middle text-center">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>الفرع</th>
                        <th>اسم الدور</th>
                        <th>خريطة</th>
                        <th>إجراءات</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach($floors as $f): ?>
                        <tr data-branch="<?= (int)$f['BranchID'] ?>">
                          <td><?= (int)$f['FloorID'] ?></td>
                          <td><?= htmlspecialchars($branchMap[$f['BranchID']] ?? '-') ?></td>
                          <td><?= htmlspecialchars($f['FloorName']) ?></td>
                          <td><?= !empty($f['FloorMap']) ? '<a target="_blank" href="uploads/floormaps/'.htmlspecialchars($f['FloorMap']).'">عرض</a>' : '—' ?></td>
                          <td>
                            <button class="btn btn-sm btn-warning" onclick='editFloor(<?= json_encode($f, JSON_UNESCAPED_UNICODE) ?>)'><i class="fa-solid fa-pen"></i></button>
                            <a class="btn btn-sm btn-danger" href="?del_floor=<?= (int)$f['FloorID'] ?>" onclick="return confirm('حذف هذا الدور؟')"><i class="fa-solid fa-trash"></i></a>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>

      <!-- ========== SECTIONS ========== -->
      <div class="tab-pane fade" id="pills-sections" role="tabpanel">
        <div class="row g-3">
          <div class="col-lg-4">
            <div class="card">
              <div class="card-header bg-light fw-bold">إضافة / تعديل سكشن</div>
              <div class="card-body">
                <form method="POST">
                  <input type="hidden" name="SectionID" id="SectionID">
                  <div class="mb-2">
                    <label class="form-label">الدور</label>
                    <select id="SecFloorID" class="form-select" required>
                      <option value="">— اختر الدور —</option>
                      <?php foreach($floors as $f): ?>
                        <option value="<?= $f['FloorID'] ?>" data-branch="<?= (int)$f['BranchID'] ?>">
                          <?= htmlspecialchars(($branchMap[$f['BranchID']]??'')." — ".$f['FloorName']) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                    <div class="small-note">* ملاحظة: السكشن يرتبط بدور مباشرة.</div>
                  </div>
                  <input type="hidden" name="FloorID" id="SecFloorIDReal">
                  <div class="mb-2">
                    <label class="form-label">اسم السكشن</label>
                    <input type="text" name="SectionName" id="SectionName" class="form-control" required placeholder="VIP / Families / Smoking">
                  </div>
                  <div class="mb-2">
                    <label class="form-label">وصف</label>
                    <textarea name="SecDescription" id="SecDescription" class="form-control" rows="2" placeholder="وصف اختياري"></textarea>
                  </div>
                  <div class="text-end">
                    <button class="btn btn-primary" name="save_section"><i class="fa-solid fa-floppy-disk"></i> حفظ</button>
                  </div>
                </form>
              </div>
            </div>
          </div>

          <div class="col-lg-8">
            <div class="card">
              <div class="card-header bg-light fw-bold">قائمة السكاشن</div>
              <div class="card-body">
                <div class="row g-2 mb-2">
                  <div class="col-md-4">
                    <select id="filterFloorSections" class="form-select">
                      <option value="">فلترة بالدور</option>
                      <?php foreach($floors as $f): ?>
                        <option value="<?= $f['FloorID'] ?>"><?= htmlspecialchars(($branchMap[$f['BranchID']]??'')." — ".$f['FloorName']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>
                <div class="table-responsive">
                  <table id="sectionsTable" class="table table-striped table-bordered align-middle text-center">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>الدور</th>
                        <th>اسم السكشن</th>
                        <th>إجراءات</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach($sections as $s): ?>
                        <tr data-floor="<?= (int)$s['FloorID'] ?>">
                          <td><?= (int)$s['SectionID'] ?></td>
                          <td><?= htmlspecialchars($floorMap[$s['FloorID']] ?? '-') ?></td>
                          <td><?= htmlspecialchars($s['SectionName']) ?></td>
                          <td>
                            <button class="btn btn-sm btn-warning" onclick='editSection(<?= json_encode($s, JSON_UNESCAPED_UNICODE) ?>)'><i class="fa-solid fa-pen"></i></button>
                            <a class="btn btn-sm btn-danger" href="?del_section=<?= (int)$s['SectionID'] ?>" onclick="return confirm('حذف هذا السكشن؟')"><i class="fa-solid fa-trash"></i></a>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>

      <!-- ========== TABLES ========== -->
      <div class="tab-pane fade" id="pills-tables" role="tabpanel">
        <div class="row g-3">
          <div class="col-lg-4">
            <div class="card">
              <div class="card-header bg-light fw-bold">إضافة / تعديل ترابيزة</div>
              <div class="card-body">
                <form method="POST">
                  <input type="hidden" name="TableID" id="TableID">

                  <div class="mb-2">
                    <label class="form-label">الفرع</label>
                    <select id="TblBranchID" class="form-select">
                      <option value="">— اختر الفرع —</option>
                      <?php foreach($branches as $b): ?>
                        <option value="<?= $b['BranchID'] ?>"><?= htmlspecialchars($b['BranchName']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>

                  <div class="mb-2">
                    <label class="form-label">الدور</label>
                    <select id="TblFloorID" class="form-select">
                      <option value="">— اختر الدور —</option>
                      <?php foreach($floors as $f): ?>
                        <option value="<?= $f['FloorID'] ?>" data-branch="<?= (int)$f['BranchID'] ?>"><?= htmlspecialchars($f['FloorName']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>

                  <div class="mb-2">
                    <label class="form-label">السكشن</label>
                    <select id="TblSectionID" name="TableSectionID" class="form-select" required>
                      <option value="">— اختر السكشن —</option>
                      <?php foreach($sections as $s): ?>
                        <option value="<?= $s['SectionID'] ?>" data-floor="<?= (int)$s['FloorID'] ?>"><?= htmlspecialchars($s['SectionName']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>

                  <div class="row g-2">
                    <div class="col-6">
                      <label class="form-label">رقم/كود الترابيزة</label>
                      <input type="text" name="TableNumber" id="TableNumber" class="form-control" required placeholder="مثلاً: T12">
                    </div>
                    <div class="col-6">
                      <label class="form-label">عدد الكراسي</label>
                      <input type="number" name="Seats" id="Seats" class="form-control" min="1" value="4" required>
                    </div>
                  </div>

                  <div class="row g-2 mt-1">
                    <div class="col-6">
                      <label class="form-label">الشكل</label>
                      <select name="Shape" id="Shape" class="form-select">
                        <option value="rectangle">مستطيل</option>
                        <option value="round">دائري</option>
                        <option value="square">مربع</option>
                      </select>
                    </div>
                    <div class="col-6">
                      <label class="form-label">حالة الترابيزة</label>
                      <select name="Status" id="Status" class="form-select">
                        <option value="available">متاحة</option>
                        <option value="reserved">محجوزة</option>
                        <option value="occupied">مشغولة</option>
                        <option value="out_of_service">خارج الخدمة</option>
                      </select>
                    </div>
                  </div>

                  <div class="row g-2 mt-1">
                    <div class="col-6">
                      <label class="form-label">PosX</label>
                      <input type="number" name="PosX" id="PosX" class="form-control" readonly>
                    </div>
                    <div class="col-6">
                      <label class="form-label">PosY</label>
                      <input type="number" name="PosY" id="PosY" class="form-control" readonly>
                    </div>
                  </div>

                  <div class="mb-2 mt-1">
                    <label class="form-label">رابط QR (كنص/لينك)</label>
                    <input type="text" name="QRCode" id="QRCode" class="form-control" placeholder="https://example.com/qr/T12">
                  </div>

                  <div class="text-end">
                    <button class="btn btn-primary" name="save_table"><i class="fa-solid fa-floppy-disk"></i> حفظ</button>
                  </div>
                </form>
              </div>
            </div>
          </div>

          <div class="col-lg-8">
            <div class="card mb-3">
              <div class="card-header bg-light fw-bold d-flex justify-content-between align-items-center">
                <span>خريطة الدور (اسحب الدبوس لتحديد مكان الترابيزة)</span>
                <span class="small-note">اختر الفرع → الدور لعرض الخريطة</span>
              </div>
              <div class="card-body">
                <div id="mapContainer" class="map-wrap" style="min-height:320px;">
                  <!-- الصورة + الدبوس هيتعرضوا هنا -->
                </div>
              </div>
            </div>

            <div class="card">
              <div class="card-header bg-light fw-bold">قائمة الترابيزات</div>
              <div class="card-body">
                <div class="row g-2 mb-2">
                  <div class="col-md-4">
                    <select id="filterSectionTables" class="form-select">
                      <option value="">فلترة بالسكشن</option>
                      <?php foreach($sections as $s): ?>
                        <option value="<?= $s['SectionID'] ?>">
                          <?= htmlspecialchars(($floorMap[$s['FloorID']]??'')." — ".$s['SectionName']) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>
                <div class="table-responsive">
                  <table id="tablesTable" class="table table-striped table-bordered align-middle text-center">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>السكشن</th>
                        <th>الترابيزة</th>
                        <th>مقاعد</th>
                        <th>شكل</th>
                        <th>X</th>
                        <th>Y</th>
                        <th>QR</th>
                        <th>حالة</th>
                        <th>إجراءات</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach($tables as $t): ?>
                        <tr data-section="<?= (int)$t['SectionID'] ?>">
                          <td><?= (int)$t['TableID'] ?></td>
                          <td><?= htmlspecialchars($sectionMap[$t['SectionID']] ?? '-') ?></td>
                          <td><?= htmlspecialchars($t['TableNumber']) ?></td>
                          <td><?= (int)$t['Seats'] ?></td>
                          <td><?= htmlspecialchars($t['Shape']) ?></td>
                          <td><?= htmlspecialchars($t['PosX']) ?></td>
                          <td><?= htmlspecialchars($t['PosY']) ?></td>
                          <td><?= !empty($t['QRCode']) ? '<a href="'.htmlspecialchars($t['QRCode']).'" target="_blank">فتح</a>' : '—' ?></td>
                          <td><?= htmlspecialchars($t['Status']) ?></td>
                          <td>
                            <button class="btn btn-sm btn-warning" onclick='editTable(<?= json_encode($t, JSON_UNESCAPED_UNICODE) ?>)'><i class="fa-solid fa-pen"></i></button>
                            <a class="btn btn-sm btn-danger" href="?del_table=<?= (int)$t['TableID'] ?>" onclick="return confirm('حذف هذه الترابيزة؟')"><i class="fa-solid fa-trash"></i></a>
                          </td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>

    </div>

  </main>
</div>

<!-- Scripts -->
<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>
  // DataTables
  $(function(){
    const ft = $('#floorsTable').DataTable({ language:{ url:"//cdn.datatables.net/plug-ins/1.13.6/i18n/ar.json" } });
    const st = $('#sectionsTable').DataTable({ language:{ url:"//cdn.datatables.net/plug-ins/1.13.6/i18n/ar.json" } });
    const tt = $('#tablesTable').DataTable({ language:{ url:"//cdn.datatables.net/plug-ins/1.13.6/i18n/ar.json" } });

    // فلترة الأدوار بالفرع
    $('#filterBranchFloors').on('change', function(){
      const val = $(this).val();
      if(!val) { ft.columns(1).search('').draw(); return; }
      // عمود 1 = اسم الفرع (نص) لذا نفلتر بالعرض الظاهر
      const txt = $(this).find('option:selected').text().trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      ft.columns(1).search('^'+txt+'$', true, false).draw();
    });

    // فلترة السكاشن بالدور (عمود 1 = اسم الدور)
    $('#filterFloorSections').on('change', function(){
      const val = $(this).val();
      if(!val) { st.columns(1).search('').draw(); return; }
      const txt = $(this).find('option:selected').text().split('—').pop().trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      st.columns(1).search(txt, true, false).draw();
    });

    // فلترة الترابيزات بالسكشن (عمود 1 = اسم السكشن)
    $('#filterSectionTables').on('change', function(){
      const val = $(this).val();
      if(!val) { tt.columns(1).search('').draw(); return; }
      const txt = $(this).find('option:selected').text().split('—').pop().trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      tt.columns(1).search(txt, true, false).draw();
    });
  });

  // تعبئة نموذج الدور عند التعديل
  function editFloor(f){
    document.getElementById('FloorID').value = f.FloorID;
    document.getElementById('FloorBranchID').value = f.BranchID;
    document.getElementById('FloorName').value = f.FloorName;
    document.getElementById('FloorDesc').value = f.Description ?? '';
    // تبويب الأدوار
    const tab = new bootstrap.Tab(document.querySelector('#pills-floors-tab'));
    tab.show();
    window.scrollTo({top:0, behavior:'smooth'});
  }

  // تعبئة نموذج السكشن
  function editSection(s){
    document.getElementById('SectionID').value = s.SectionID;
    document.getElementById('SecFloorID').value = s.FloorID;
    document.getElementById('SecFloorIDReal').value = s.FloorID;
    document.getElementById('SectionName').value = s.SectionName;
    document.getElementById('SecDescription').value = s.Description ?? '';
    const tab = new bootstrap.Tab(document.querySelector('#pills-sections-tab'));
    tab.show();
    window.scrollTo({top:0, behavior:'smooth'});
  }

  // اختيار الدور في نموذج السكشن → خزّنه في hidden الحقيقي
  document.getElementById('SecFloorID').addEventListener('change', e=>{
    document.getElementById('SecFloorIDReal').value = e.target.value || '';
  });

  // تعبئة نموذج الترابيزة
  function editTable(t){
    document.getElementById('TableID').value = t.TableID;
    // حدد الفرع و الدور و السكشن حسب العلاقات الحالية:
    const floorOption = [...document.querySelectorAll('#TblFloorID option')].find(o=>o.value== (t.FloorID || ''));
    // لو مش متاح FloorID في بيانات الجدول، نجيب من sections array عبر data-floor في ال DOM (سهل نحافظ يدويًا)
    // أسهل: نملا فقط السكشن ونعتمد على تحميل الخريطة يدويًا من اختيار المستخدم.
    document.getElementById('TblSectionID').value = t.SectionID;
    document.getElementById('TableNumber').value = t.TableNumber;
    document.getElementById('Seats').value = t.Seats;
    document.getElementById('Shape').value = t.Shape;
    document.getElementById('Status').value = t.Status;
    document.getElementById('QRCode').value = t.QRCode ?? '';
    document.getElementById('PosX').value = t.PosX ?? '';
    document.getElementById('PosY').value = t.PosY ?? '';

    const tab = new bootstrap.Tab(document.querySelector('#pills-tables-tab'));
    tab.show();
    window.scrollTo({top:0, behavior:'smooth'});
  }

  /* ================== Hierarchy & Map ================== */
  // فلاترة الأدوار حسب الفرع في تبويب الترابيزات
  const branchSel = document.getElementById('TblBranchID');
  const floorSel  = document.getElementById('TblFloorID');
  const sectionSel= document.getElementById('TblSectionID');
  const mapContainer = document.getElementById('mapContainer');

  branchSel.addEventListener('change', ()=>{
    const bid = branchSel.value;
    // أعرض فقط الأدوار التابعة للفرع
    [...floorSel.options].forEach((o,idx)=>{
      if(idx===0){ o.hidden=false; return; }
      o.hidden = (o.dataset.branch !== bid);
    });
    floorSel.value = '';
    // كذلك أخفي السكاشن
    [...sectionSel.options].forEach((o,idx)=>{
      if(idx===0){ o.hidden=false; return; }
      o.hidden = true;
    });
    sectionSel.value = '';
    clearMap();
  });

  floorSel.addEventListener('change', ()=>{
    const fid = floorSel.value;
    // أعرض السكاشن التابعة للدور
    [...sectionSel.options].forEach((o,idx)=>{
      if(idx===0){ o.hidden=false; return; }
      o.hidden = (o.dataset.floor !== fid);
    });
    sectionSel.value = '';
    // حمل خريطة الدور (لو متاحة) من مصفوفة floors المرسلة للواجهة (نرسلها عبر JSON)
    loadFloorMap(fid);
  });

  function clearMap(){ mapContainer.innerHTML = '<div class="p-3 text-muted small">لا توجد خريطة معروضة</div>'; }

  // نبعث بيانات الأدوار (بما فيها FloorMap) للجافاسكربت
  const floorsData = <?php
    $send = [];
    foreach($floors as $f){
      $send[$f['FloorID']] = [
        'FloorID'=>$f['FloorID'],
        'FloorName'=>$f['FloorName'],
        'BranchID'=>$f['BranchID'],
        'FloorMap'=>$f['FloorMap'] ?? null
      ];
    }
    echo json_encode($send, JSON_UNESCAPED_UNICODE);
  ?>;

  function loadFloorMap(floorId){
    clearMap();
    if(!floorId || !floorsData[floorId] || !floorsData[floorId].FloorMap){ return; }
    const imgSrc = 'uploads/floormaps/' + floorsData[floorId].FloorMap;
    const img = new Image();
    img.src = imgSrc;
    img.onload = ()=>{
      mapContainer.innerHTML = '';
      mapContainer.appendChild(img);
      // أضف دبوس قابل للسحب يمثل الترابيزة الحالية (إن وجدت إحداثيات)
      createOrMovePin();
    };
    img.onerror = ()=>{ clearMap(); };
  }

  // إنشاء دبوس وسحبه لتحديث PosX/PosY
  function createOrMovePin(){
    // احسب مركز الحاوية كبداية
    const existing = document.querySelector('.table-dot');
    if (existing) existing.remove();

    const pin = document.createElement('div');
    pin.className = 'table-dot';
    pin.title = 'اسحب لتحديد الموقع';
    pin.innerHTML = '<i class="fa-solid fa-chair"></i>';
    mapContainer.appendChild(pin);

    // وضع ابتدائي: لو عندنا PosX/PosY نستخدمهم، غير كده منتصف الصورة
    const PosX = document.getElementById('PosX');
    const PosY = document.getElementById('PosY');

    const rect = mapContainer.getBoundingClientRect();
    const initX = (PosX.value ? parseInt(PosX.value) : Math.round(rect.width/2));
    const initY = (PosY.value ? parseInt(PosY.value) : Math.round(rect.height/2));
    setPinPosition(pin, initX, initY);

    let dragging = false;
    let offsetX = 0, offsetY = 0;

    pin.addEventListener('mousedown', (e)=>{
      dragging = true;
      const p = pin.getBoundingClientRect();
      offsetX = e.clientX - p.left;
      offsetY = e.clientY - p.top;
      e.preventDefault();
    });
    document.addEventListener('mousemove', (e)=>{
      if(!dragging) return;
      const mc = mapContainer.getBoundingClientRect();
      let x = e.clientX - mc.left + (pin.offsetWidth/2 - offsetX);
      let y = e.clientY - mc.top  + (pin.offsetHeight/2 - offsetY);
      // حد داخل الحاوية
      x = Math.max(0, Math.min(mc.width, x));
      y = Math.max(0, Math.min(mc.height, y));
      setPinPosition(pin, x, y);
      PosX.value = Math.round(x);
      PosY.value = Math.round(y);
    });
    document.addEventListener('mouseup', ()=> dragging=false);

    // كليك على الخريطة ينقل الدبوس
    mapContainer.addEventListener('click', (e)=>{
      const mc = mapContainer.getBoundingClientRect();
      const x = e.clientX - mc.left;
      const y = e.clientY - mc.top;
      setPinPosition(pin, x, y);
      PosX.value = Math.round(x);
      PosY.value = Math.round(y);
    }, { once:false });
  }

  function setPinPosition(pin, x, y){
    pin.style.left = x + 'px';
    pin.style.top  = y + 'px';
  }

</script>
</body>
</html>
