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

/* ============ Tiny JSON responder ============ */
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;
}

/* ============ AJAX Endpoints ============ */
/* 1) Get floors by branch */
if (isset($_GET['action']) && $_GET['action']==='get_floors') {
  $branch = (int)($_GET['branch_id'] ?? 0);
  $stmt = $pdo->prepare("SELECT FloorID, BranchID, FloorName, FloorMap FROM floors WHERE BranchID=? ORDER BY FloorName");
  $stmt->execute([$branch]);
  json_out($stmt->fetchAll(PDO::FETCH_ASSOC));
}

/* 2) Get tables by floor */
if (isset($_GET['action']) && $_GET['action']==='get_tables') {
  $floor = (int)($_GET['floor_id'] ?? 0);
  // نجيب الترابيزات عبر السكاشن التابعة للدور
  $sql = "SELECT t.TableID, t.SectionID, t.TableNumber, t.Seats, t.Shape, t.PosX, t.PosY, t.Status,
                 s.SectionName
          FROM dining_tables t
          JOIN sections s ON t.SectionID = s.SectionID
          WHERE s.FloorID = ?
          ORDER BY t.TableNumber";
  $stmt = $pdo->prepare($sql);
  $stmt->execute([$floor]);
  json_out($stmt->fetchAll(PDO::FETCH_ASSOC));
}

/* 3) Save position after drag */
if (isset($_GET['action']) && $_GET['action']==='save_pos' && $_SERVER['REQUEST_METHOD']==='POST') {
  $TableID = (int)($_POST['TableID'] ?? 0);
  $PosX    = (int)($_POST['PosX'] ?? 0);
  $PosY    = (int)($_POST['PosY'] ?? 0);
  if ($TableID>0) {
    $stmt = $pdo->prepare("UPDATE dining_tables SET PosX=?, PosY=? WHERE TableID=?");
    $stmt->execute([$PosX, $PosY, $TableID]);
    json_out(['ok'=>true,'TableID'=>$TableID,'PosX'=>$PosX,'PosY'=>$PosY]);
  }
  json_out(['ok'=>false], 400);
}

/* ============ Initial Data for dropdowns ============ */
$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 -->
  <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">

  <!-- jQuery / jQuery UI for draggable -->
  <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
  <link  href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" rel="stylesheet">
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

  <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;
      --avail:#16a34a; --occ:#dc2626; --res:#d97706; --oos:#6b7280;
    }
    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);}
    .controls .form-select{min-width:220px}
    .legend .badge{font-size:.8rem}

  /* Map area */
.map-shell{position:relative; overflow:hidden; border-radius:14px; border:1px solid var(--border); background:#fff;}
.map-viewport{position:relative; transform-origin: 0 0;}
.map-img{position:relative; z-index:1; display:block; width:100%; height:auto; user-select:none; pointer-events:none;}
.pin{
  position:absolute; z-index:10;   /* مهم: فوق الصورة */
  transform: translate(-50%, -50%);
  display:flex; align-items:center; justify-content:center;
  color:#fff; font-weight:800; font-size:12px; cursor:grab; box-shadow:0 6px 16px rgba(0,0,0,.25);
  background:#16a085;              /* خلفية افتراضية لو الحالة مش متعرّفة */
  border:2px solid #fff;
}
.pin:active{cursor:grabbing}
.pin.round{border-radius:50%;}
.pin.rect{border-radius:10px;}
/* size */
.pin.round{ width:40px; height:40px; }
.pin.rect{ width:56px; height:36px; }

/* status colors */
.pin.available{ background: var(--avail); }
.pin.occupied{  background: var(--occ); }
.pin.reserved{  background: var(--res); }
.pin.out_of_service{ background: var(--oos); }

    /* zoom buttons */
    .zoom-tools{
      position:absolute; top:12px; left:12px; z-index:50; display:flex; gap:8px;
    }
    .zoom-tools .btn{ border-radius:10px; }
    .hint{color:var(--muted); font-size:.9rem}
  </style>
</head>
<body>

<header class="container-fluid">
  <div class="fw-bold"><i class="fa-solid fa-map"></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 controls">
      <div class="col-md-4">
        <label class="form-label">الفرع</label>
        <select id="branchSel" 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-4">
        <label class="form-label">الدور</label>
        <select id="floorSel" class="form-select" disabled>
          <option value="">— اختر الدور —</option>
        </select>
      </div>
      <div class="col-md-4 text-md-end">
        <div class="legend">
          <span class="badge bg-success">متاح</span>
          <span class="badge bg-warning text-dark">محجوز</span>
          <span class="badge bg-danger">مشغول</span>
          <span class="badge bg-secondary">خارج الخدمة</span>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="container">
  <div class="panel p-0">
    <div class="map-shell">
      <!-- Zoom tools -->
      <div class="zoom-tools">
        <button id="zoomIn"  class="btn btn-sm btn-outline-dark"><i class="fa-solid fa-magnifying-glass-plus"></i></button>
        <button id="zoomOut" class="btn btn-sm btn-outline-dark"><i class="fa-solid fa-magnifying-glass-minus"></i></button>
        <button id="zoomReset" class="btn btn-sm btn-outline-dark"><i class="fa-solid fa-up-right-and-down-left-from-center"></i></button>
      </div>

      <!-- Viewport (scaled) -->
      <div id="mapViewport" class="map-viewport">
        <!-- background image injected here -->
      </div>
    </div>
    <div class="p-3">
      <div class="hint"><i class="fa-solid fa-circle-info"></i> اسحب الترابيزة إلى مكانها المناسب. يتم الحفظ تلقائيًا بعد الإفلات.</div>
    </div>
  </div>
</div>

<!-- Modal: Table details -->
<div class="modal fade" id="tableModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title"><i class="fa-solid fa-chair"></i> تفاصيل الترابيزة</h6>
        <button type="button" class="btn-close ms-0" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row g-2">
          <div class="col-6"><strong>رقم:</strong> <span id="mTableNumber"></span></div>
          <div class="col-6"><strong>مقاعد:</strong> <span id="mSeats"></span></div>
          <div class="col-6"><strong>شكل:</strong> <span id="mShape"></span></div>
          <div class="col-6"><strong>حالة:</strong> <span id="mStatus"></span></div>
          <div class="col-12"><strong>سكشن:</strong> <span id="mSection"></span></div>
          <div class="col-12"><strong>الموقع:</strong> <span id="mPos"></span></div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">إغلاق</button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
let currentScale = 1.0;     // zoom scale
let imgNaturalW = 0;        // natural image width
let imgNaturalH = 0;        // natural image height

const $branchSel = $('#branchSel');
const $floorSel  = $('#floorSel');
const $viewport  = $('#mapViewport');

function clearViewport(){
  $viewport.empty();
  imgNaturalW = imgNaturalH = 0;
}

function loadFloors(branchId){
  $floorSel.prop('disabled', true).html('<option value="">— جاري التحميل —</option>');
  $.getJSON('?action=get_floors&branch_id='+branchId, function(rows){
    let html = '<option value="">— اختر الدور —</option>';
    rows.forEach(r=>{
      html += `<option value="${r.FloorID}" data-map="${r.FloorMap? r.FloorMap:''}">${escapeHtml(r.FloorName)}</option>`;
    });
    $floorSel.html(html).prop('disabled', false);
  });
}

function loadMapAndTables(floorId){
  clearViewport();
  const opt = $floorSel.find('option:selected');
  const mapFile = opt.data('map') || '';
  if(!mapFile){
    $viewport.html('<div class="p-4 text-center text-muted">لا توجد خريطة مرفوعة لهذا الدور.</div>');
    return;
  }
  const img = new Image();
  img.className = 'map-img';
  img.src = 'uploads/floormaps/' + encodeURIComponent(mapFile); // لو خريطتك في uploads/floors/ بدّل المسار هنا
  img.onload = ()=>{
    imgNaturalW = img.naturalWidth;
    imgNaturalH = img.naturalHeight;
    $viewport.empty().append(img);
    $.getJSON('?action=get_tables&floor_id='+floorId, function(rows){
      console.log('tables rows for floor', floorId, rows);
      if (!rows || !rows.length) {
        $viewport.append('<div class="p-3 text-center text-muted">لا توجد ترابيزات مرتبطة بهذا الدور.</div>');
        return;
      }
      rows.forEach(addPinFromRow);
    }).fail(function(xhr){
      console.warn('get_tables failed', xhr.responseText);
      $viewport.append('<div class="p-3 text-center text-danger">تعذّر جلب الترابيزات.</div>');
    });
    currentScale = 1.0;
    applyScale();
  };
  img.onerror = ()=>{
    console.warn('تعذر تحميل الخريطة من:', img.src);
    $viewport.html('<div class="p-4 text-center text-danger">تعذّر تحميل الخريطة.</div>');
  };
}

function addPinFromRow(row){
  const x = parseInt(row.PosX || 0);
  const y = parseInt(row.PosY || 0);

  // شكل
  const shapeClass = (row.Shape && row.Shape.toLowerCase()==='round') ? 'round' : 'rect';

  // ماب للحالات عشان أي حروف/قيم تتظبط
  const statusMap = {
    'available':'available',
    'reserved':'reserved',
    'occupied':'occupied',
    'out_of_service':'out_of_service',
    'out-of-service':'out_of_service',
    'out of service':'out_of_service'
  };
  const rawStatus = (row.Status || '').toString().trim().toLowerCase();
  const statusClass = statusMap[rawStatus] || 'available';

  const $pin = $(`
    <div class="pin ${shapeClass} ${statusClass}" 
         data-id="${row.TableID}" 
         data-number="${escapeHtml(row.TableNumber)}"
         data-seats="${row.Seats}" 
         data-shape="${escapeHtml(row.Shape)}"
         data-status="${statusClass}"
         data-section="${escapeHtml(row.SectionName)}"
         title="ترابيزة ${escapeHtml(row.TableNumber)}">
      ${escapeHtml(row.TableNumber)}
    </div>
  `);

  // احسب أبعاد الصورة المعروضة
  const imgEl = $viewport.find('img.map-img').get(0);
  const rect  = imgEl ? imgEl.getBoundingClientRect() : null;
  const baseW = rect ? rect.width  : (imgNaturalW || 800);
  const baseH = rect ? rect.height : (imgNaturalH || 600);

  // موضع ابتدائي
  const startX = x>0 ? x : Math.round(baseW/2);
  const startY = y>0 ? y : Math.round(baseH/2);

  // ضع داخل viewport أولًا
  $viewport.append($pin);

  // طبّق الموضع (مع مراعاة الـ scale الحالي)
  const scaledLeft = startX * currentScale;
  const scaledTop  = startY * currentScale;
  $pin.css({ left: scaledLeft+'px', top: scaledTop+'px' });

  // سحب
  $pin.draggable({
    containment: 'parent',
    stop: function(e, ui){
      const scaledX = ui.position.left;
      const scaledY = ui.position.top;
      const realX = Math.round(scaledX / currentScale);
      const realY = Math.round(scaledY / currentScale);
      savePos($(this).data('id'), realX, realY);
    }
  });

  // تفاصيل
  $pin.on('click', function(){
    const $t = $(this);
    $('#mTableNumber').text($t.data('number'));
    $('#mSeats').text($t.data('seats'));
    const sh = ($t.data('shape')||'').toString().toLowerCase();
    $('#mShape').text(sh==='round' ? 'دائري' : (sh==='rectangle'?'مستطيل':'مربع'));
    const st = $t.data('status');
    $('#mStatus').text(st==='available'?'متاح':st==='reserved'?'محجوز':st==='occupied'?'مشغول':'خارج الخدمة');
    $('#mSection').text($t.data('section'));
    const cs = $t.position(); // scaled
    $('#mPos').text( Math.round(cs.left/currentScale) + ' , ' + Math.round(cs.top/currentScale) );
    const modal = new bootstrap.Modal(document.getElementById('tableModal'));
    modal.show();
  });
}


function savePos(TableID, PosX, PosY){
  $.post('?action=save_pos', { TableID, PosX, PosY })
    .fail(()=> console.warn('فشل حفظ الإحداثيات'))
    .done(()=> console.log('تم الحفظ', TableID, PosX, PosY));
}

/* ============ Zoom handlers ============ */
function applyScale(){
  // نغير scale للـ viewport كله (الصورة + الدبابيس)
  $viewport.css('transform', 'scale('+currentScale+')');
  // عند تغيير الـ scale، لازم نعيد تموضع الدبابيس حسب scale الحالي
  // لكن لأننا نعمل transform على الحاوية، مواضع الأطفال تتحرك تلقائيًا.
}

$('#zoomIn').on('click', function(){ currentScale = Math.min(3, currentScale + 0.1); applyScale(); });
$('#zoomOut').on('click', function(){ currentScale = Math.max(0.4, currentScale - 0.1); applyScale(); });
$('#zoomReset').on('click', function(){ currentScale = 1.0; applyScale(); });

/* ============ Events ============ */
$branchSel.on('change', function(){
  const bid = $(this).val();
  clearViewport();
  $('#floorSel').html('<option value="">— اختر الدور —</option>').prop('disabled', true);
  if(!bid) return;
  loadFloors(bid);
});

$floorSel.on('change', function(){
  const fid = $(this).val();
  clearViewport();
  if(!fid) return;
  loadMapAndTables(fid);
});

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