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

/** الصلاحيات البسيطة */
$user = current_user();                    // يفترض موجودة
$can_discount = !empty($user['can_discount']);
$branch_id = (int)($user['branch_id'] ?? 1);

date_default_timezone_set('Africa/Cairo');

/** Endpoints AJAX داخل نفس الصفحة */
if (isset($_GET['action'])) {
  header('Content-Type: application/json; charset=utf-8');
  $act = $_GET['action'];

  if ($act === 'get_floors') {
    $bid = (int)($_GET['branch_id'] ?? 0);
    $st = $pdo->prepare("SELECT FloorID, FloorName FROM floors WHERE BranchID=? ORDER BY FloorName");
    $st->execute([$bid]);
    echo json_encode($st->fetchAll(PDO::FETCH_ASSOC), JSON_UNESCAPED_UNICODE); exit;
  }

  if ($act === 'get_sections') {
    $fid = (int)($_GET['floor_id'] ?? 0);
    $st = $pdo->prepare("SELECT SectionID, SectionName FROM sections WHERE FloorID=? ORDER BY SectionName");
    $st->execute([$fid]);
    echo json_encode($st->fetchAll(PDO::FETCH_ASSOC), JSON_UNESCAPED_UNICODE); exit;
  }

  if ($act === 'get_tables') {
    $sid = (int)($_GET['section_id'] ?? 0);
    $st = $pdo->prepare("SELECT TableID, TableNumber, Seats FROM dining_tables WHERE SectionID=? ORDER BY TableNumber");
    $st->execute([$sid]);
    echo json_encode($st->fetchAll(PDO::FETCH_ASSOC), JSON_UNESCAPED_UNICODE); exit;
  }

  // هل الترابيزة مشغولة؟ (أي إيصال غير مدفوع/جزئي على نفس الترابيزة)
  if ($act === 'check_table_busy') {
    $tid = (int)($_GET['table_id'] ?? 0);
    $q = "SELECT COUNT(*) FROM salesreceipt
          WHERE TableID = ? AND ReceiptType='DineIn' AND PaymentStatus IN ('Unpaid','Partial')";
    $st = $pdo->prepare($q); $st->execute([$tid]);
    echo json_encode(['busy' => $st->fetchColumn() > 0]); exit;
  }

  echo json_encode(['ok'=>false,'msg'=>'unknown action']); exit;
}

/** إعدادات الفرع */
$st = $pdo->prepare("SELECT TaxRate, ServicePercent, Currency, PrintFooter FROM BranchSettings WHERE BranchID=?");
$st->execute([$branch_id]);
$branch = $st->fetch() ?: ['TaxRate'=>0.00,'ServicePercent'=>0.00,'Currency'=>'EGP','PrintFooter'=>null];

/** القوائم */
$branches = $pdo->query("SELECT BranchID, BranchName FROM branches WHERE IsActive=1 ORDER BY BranchName")->fetchAll();

/** المجموعات + أصناف مفعّلة */
$groups = $pdo->query("SELECT Code, CName, ColorHex FROM categories ORDER BY SortOrder, Code")->fetchAll(PDO::FETCH_ASSOC);

$rawItems = $pdo->query("
  SELECT Code, IName, PriceTW, Cat_Code
  FROM items
  WHERE Active=1
  ORDER BY Cat_Code, SortOrder, Code
")->fetchAll(PDO::FETCH_ASSOC);

$items = [];
foreach ($rawItems as $r) { $items[$r['Cat_Code']][] = $r; }

/** CSRF */
$token = bin2hex(random_bytes(16));
$_SESSION['csrf'] = $token;
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>🍽️💳 مبيعات صالة (Dine-In)</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
  <style>
    body{font-family:"Tajawal",sans-serif;background:#f5f6f8}
    .pane{background:#fff;border-radius:12px;padding:12px}
    .group-btn{
      margin:6px;border-radius:12px;font-weight:700;color:#fff;border:0;padding:10px 14px;
    }
    .item-btn{
      margin:6px;border-radius:12px;font-weight:700;color:#fff;border:0;padding:12px;min-width:140px
    }
    .item-grid{display:flex;flex-wrap:wrap}
    .item-grid .item-btn{flex:1 1 140px}
    .invoice-table tfoot td{font-size:1.05rem;font-weight:bold;color:#d35400}
    .qty-btn{width:32px;height:32px;line-height:16px;padding:0}
    .kbd{background:#111;color:#fff;border-radius:6px;padding:2px 6px;font-size:.82rem}
    .locked{pointer-events:none;opacity:.6}
    .hint{color:#6b7280}
    .badge-soft{background:#eef2ff;color:#1e40af;font-weight:600}
    .sel-grid .form-select{min-width:160px}
    @media (max-width:768px){
      .item-btn{min-width:120px}
      .pane{padding:8px}
      .sel-grid .form-select{min-width:unset}
    }
  </style>
</head>
<body>
<div class="container-fluid py-3">
  <div class="d-flex flex-wrap gap-2 align-items-center mb-3">
    <h4 class="m-0">🍽️💳 شاشة مبيعات الصالة</h4>
    <span class="text-muted">
      فرع افتراضي: <strong>#<?= htmlspecialchars($branch_id) ?></strong> | ضريبة: <strong><?= (float)$branch['TaxRate'] ?>%</strong> | خدمة: <strong><?= (float)($branch['ServicePercent'] ?? 0) ?>%</strong>
    </span>
    <div class="ms-auto d-flex gap-2">
      <span class="kbd">F2 حفظ</span>
      <span class="kbd">Ctrl+P طباعة</span>
      <span class="kbd">Esc إلغاء</span>
    </div>
  </div>

  <!-- اختيار الفرع/الدور/السكشن/الترابيزة -->
  <div class="pane mb-3 sel-grid">
    <div class="row g-2 align-items-end">
      <div class="col-lg-2">
        <label class="form-label">الفرع</label>
        <select id="selBranch" class="form-select">
          <?php foreach($branches as $b): ?>
            <option value="<?= (int)$b['BranchID'] ?>" <?= $b['BranchID']==$branch_id?'selected':'' ?>>
              <?= htmlspecialchars($b['BranchName']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-lg-2">
        <label class="form-label">الدور</label>
        <select id="selFloor" class="form-select" disabled>
          <option value="">— اختر —</option>
        </select>
      </div>
      <div class="col-lg-2">
        <label class="form-label">السكشن</label>
        <select id="selSection" class="form-select" disabled>
          <option value="">— اختر —</option>
        </select>
      </div>
      <div class="col-lg-3">
        <label class="form-label">الترابيزة</label>
        <select id="selTable" class="form-select" disabled>
          <option value="">— اختر —</option>
        </select>
        <div id="tableStatus" class="form-text hint"></div>
      </div>
      <div class="col-lg-3">
        <label class="form-label">عدد الأفراد</label>
        <input type="number" id="guests" class="form-control" value="1" min="1">
      </div>
    </div>
  </div>

  <div class="row g-3">
    <!-- المجموعات + الأصناف -->
    <div class="col-lg-7">
      <div class="pane mb-3">
        <div class="mb-2">
          <input class="form-control" id="searchBox" placeholder="ابحث عن صنف بالاسم…" oninput="searchItems()">
        </div>
        <div class="mb-2">
          <?php foreach($groups as $g):
            $color = $g['ColorHex'] ?? null;
            $bg = $color ? "background:$color" : "background:linear-gradient(135deg,#2c3e50,#3498db)";
          ?>
            <button class="group-btn" style="<?= $bg ?>" onclick="showItems(<?= (int)$g['Code'] ?>)">
              <?= htmlspecialchars($g['CName']) ?>
            </button>
          <?php endforeach; ?>
        </div>
        <div id="itemsContainer" class="item-grid"></div>
      </div>
    </div>

    <!-- الفاتورة -->
    <div class="col-lg-5">
      <div class="pane">
        <div class="d-flex justify-content-between align-items-center mb-2">
          <span class="badge badge-soft" id="selSummary">لم يتم اختيار ترابيزة</span>
          <small class="hint">لن يُسمح بالحفظ إلا بعد اختيار ترابيزة غير مشغولة</small>
        </div>
        <table class="table table-bordered text-center align-middle invoice-table" id="invoiceTable">
          <thead class="table-dark">
            <tr>
              <th>الصنف</th>
              <th style="width:130px">الكمية</th>
              <th>السعر</th>
              <th>القيمة</th>
              <th style="width:48px">❌</th>
            </tr>
          </thead>
          <tbody></tbody>
          <tfoot>
            <tr><td colspan="3" class="text-end">الإجمالي قبل الخصم</td><td id="subTotal">0.00</td><td></td></tr>
            <tr>
              <td colspan="2" class="text-end">
                الخصم
                <select id="discountType" class="form-select form-select-sm d-inline-block" style="width:auto">
                  <option value="amount">قيمة</option>
                  <option value="percent">نسبة %</option>
                </select>
              </td>
              <td><input type="number" step="0.01" class="form-control form-control-sm" id="discountValue" value="0"></td>
              <td id="discountDisp">0.00</td>
              <td></td>
            </tr>
            <tr><td colspan="3" class="text-end">الخدمة (<?= (float)($branch['ServicePercent'] ?? 0) ?>%)</td><td id="service">0.00</td><td></td></tr>
            <tr><td colspan="3" class="text-end">الضريبة (<?= (float)$branch['TaxRate'] ?>%)</td><td id="tax">0.00</td><td></td></tr>
            <tr><td colspan="3" class="text-end">الإجمالي</td><td id="total">0.00</td><td></td></tr>
          </tfoot>
        </table>

        <!-- الدفع -->
        <div class="row g-2">
          <div class="col-6">
            <label class="form-label">كاش</label>
            <input type="number" step="0.01" class="form-control" id="payCash" value="0">
          </div>
          <div class="col-6">
            <label class="form-label">فيزا</label>
            <input type="number" step="0.01" class="form-control" id="payCard" value="0">
          </div>
          <div class="col-6">
            <label class="form-label">المبلغ المستلم (كاش)</label>
            <input type="number" step="0.01" class="form-control" id="amountReceived" value="0">
          </div>
          <div class="col-6">
            <label class="form-label">الباقي</label>
            <input type="text" readonly class="form-control" id="changeDue" value="0.00">
          </div>
          <div class="col-12">
            <label class="form-label">ملاحظات</label>
            <input type="text" class="form-control" id="notes">
          </div>
          <div class="col-12">
            <label class="form-label">إيميل العميل (اختياري لإرسال PDF)</label>
            <input type="email" class="form-control" id="customerEmail">
          </div>
        </div>

        <div class="d-flex gap-2 mt-3">
          <button class="btn btn-success" id="saveBtn" onclick="saveReceipt()">💾 حفظ (F2)</button>
          <button class="btn btn-secondary" id="printBtn" onclick="printLast()" disabled>🖨️ طباعة</button>
          <button class="btn btn-outline-danger ms-auto" onclick="resetInvoice()">إلغاء (Esc)</button>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- libs -->
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script>
  const itemsByGroup = <?= json_encode($items, JSON_UNESCAPED_UNICODE) ?>;
  const TAX_RATE = <?= (float)$branch['TaxRate'] ?>;
  const SERVICE_PCT = <?= (float)($branch['ServicePercent'] ?? 0) ?>;
  const CURRENCY = <?= json_encode($branch['Currency'] ?? 'EGP') ?>;
  const CSRF = <?= json_encode($token) ?>;
  const CAN_DISCOUNT = <?= $can_discount ? 'true':'false' ?>;

  const invoice = new Map(); // key: Code, value: {code,name,qty,price}
  let lastReceiptId = null;

  // حالة اختيار الترابيزة
  let sel = { branch:null, floor:null, section:null, table:null, tableText:'' };
  let tableBusy = false;

  // تحميل أول مجموعة تلقائيًا
  const firstGroup = Object.keys(itemsByGroup)[0];

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

  function renderSelSummary(){
    const el = document.getElementById('selSummary');
    if(sel.table){
      el.textContent = `فرع #${sel.branch} | ترابيزة: ${sel.tableText}`;
    } else {
      el.textContent = 'لم يتم اختيار ترابيزة';
    }
  }

  // هرمية القوائم
  $('#selBranch').on('change', function(){
    sel.branch = this.value || null;
    $('#selFloor').prop('disabled', true).html('<option value="">— جاري التحميل —</option>');
    $('#selSection').prop('disabled', true).html('<option value="">— اختر —</option>');
    $('#selTable').prop('disabled', true).html('<option value="">— اختر —</option>');
    sel.floor = sel.section = sel.table = null; sel.tableText = ''; tableBusy=false; renderSelSummary();
    if(!sel.branch){ $('#selFloor').html('<option value="">— اختر —</option>'); return; }
    $.getJSON('?action=get_floors&branch_id='+sel.branch, rows=>{
      let html = '<option value="">— اختر —</option>';
      rows.forEach(r=> html += `<option value="${r.FloorID}">${escapeHtml(r.FloorName)}</option>`);
      $('#selFloor').html(html).prop('disabled', false);
    });
  }).trigger('change'); // حمّل أدوار الفرع الافتراضي

  $('#selFloor').on('change', function(){
    sel.floor = this.value || null;
    $('#selSection').prop('disabled', true).html('<option value="">— جاري التحميل —</option>');
    $('#selTable').prop('disabled', true).html('<option value="">— اختر —</option>');
    sel.section = sel.table = null; sel.tableText = ''; tableBusy=false; renderSelSummary();
    if(!sel.floor){ $('#selSection').html('<option value="">— اختر —</option>'); return; }
    $.getJSON('?action=get_sections&floor_id='+sel.floor, rows=>{
      let html = '<option value="">— اختر —</option>';
      rows.forEach(r=> html += `<option value="${r.SectionID}">${escapeHtml(r.SectionName)}</option>`);
      $('#selSection').html(html).prop('disabled', false);
    });
  });

  $('#selSection').on('change', function(){
    sel.section = this.value || null;
    $('#selTable').prop('disabled', true).html('<option value="">— جاري التحميل —</option>');
    sel.table = null; sel.tableText = ''; tableBusy=false; renderSelSummary();
    if(!sel.section){ $('#selTable').html('<option value="">— اختر —</option>'); return; }
    $.getJSON('?action=get_tables&section_id='+sel.section, rows=>{
      let html = '<option value="">— اختر —</option>';
      rows.forEach(r=> html += `<option value="${r.TableID}">${escapeHtml(r.TableNumber)} (${r.Seats||''})</option>`);
      $('#selTable').html(html).prop('disabled', false);
    });
  });

  $('#selTable').on('change', function(){
    sel.table = this.value || null;
    sel.tableText = this.options[this.selectedIndex]?.text || '';
    renderSelSummary();
    $('#tableStatus').text('');
    tableBusy = false;
    if(sel.table){
      $.getJSON('?action=check_table_busy&table_id='+sel.table, resp=>{
        tableBusy = !!resp.busy;
        if(tableBusy){
          $('#tableStatus').text('⚠️ الترابيزة مشغولة (فاتورة غير مدفوعة موجودة)').css('color','#b91c1c');
        } else {
          $('#tableStatus').text('✅ الترابيزة متاحة').css('color','#166534');
        }
      });
    }
  });

  // أصناف
  window.addEventListener('DOMContentLoaded', () => {
    showItems(firstGroup);
    if(!CAN_DISCOUNT){
      document.getElementById('discountType').classList.add('locked');
      document.getElementById('discountValue').classList.add('locked');
      document.getElementById('discountValue').disabled = true;
      document.getElementById('discountType').disabled = true;
    }
  });

  function searchItems(){
    const q = document.getElementById('searchBox').value.trim();
    const container = document.getElementById('itemsContainer');
    container.innerHTML = '';
    if(!q){ showItems(firstGroup); return; }
    const results = [];
    for(const gid in itemsByGroup){
      (itemsByGroup[gid]||[]).forEach(it=>{ if((it.IName||'').includes(q)) results.push(it); });
    }
    renderItemButtons(results);
  }

  function showItems(groupId){
    const items = itemsByGroup[groupId] || [];
    renderItemButtons(items);
  }

  function renderItemButtons(items){
    const container = document.getElementById('itemsContainer');
    container.innerHTML = '';
    items.forEach(item=>{
      const btn = document.createElement('button');
      btn.className = 'item-btn';
      btn.style.background = 'linear-gradient(135deg,#8e44ad,#9b59b6)';
      btn.textContent = `${item.IName} - ${parseFloat(item.PriceTW).toFixed(2)} ${CURRENCY}`;
      btn.onclick = ()=> addItem(item);
      container.appendChild(btn);
    });
  }

  function addItem(item){
    const code = item.Code;
    if(!invoice.has(code)){
      invoice.set(code, { code, name:item.IName, qty:0, price: parseFloat(item.PriceTW) });
    }
    invoice.get(code).qty += 1;
    renderInvoice();
  }
  function inc(code){ const r = invoice.get(code); if(!r) return; r.qty++; renderInvoice(); }
  function dec(code){ const r = invoice.get(code); if(!r) return; r.qty = Math.max(1, r.qty-1); renderInvoice(); }
  function removeItem(code){ invoice.delete(code); renderInvoice(); }

  function getTotals(){
    let sub = 0;
    invoice.forEach(r=> sub += r.qty * r.price);

    // خصم
    const dtype = document.getElementById('discountType').value;
    let dval = parseFloat(document.getElementById('discountValue').value||0);
    let discountAmt = 0;
    if(dtype === 'percent') discountAmt = Math.min(sub, sub * (dval/100));
    else discountAmt = Math.min(sub, dval);

    const afterDisc = Math.max(0, sub - discountAmt);
    // خدمة الصالة
    const serviceAmt = +(afterDisc * (SERVICE_PCT/100)).toFixed(2);
    // ضريبة
    const taxable = afterDisc + serviceAmt;
    const tax = +(taxable * (TAX_RATE/100)).toFixed(2);
    const total = +(taxable + tax).toFixed(2);

    return {
      sub:+sub.toFixed(2),
      discountAmt:+discountAmt.toFixed(2),
      serviceAmt:+serviceAmt.toFixed(2),
      tax:+tax.toFixed(2),
      total:+total.toFixed(2),
      dtype, dval
    };
  }

  function renderInvoice(){
    const tbody = document.querySelector('#invoiceTable tbody');
    tbody.innerHTML = '';
    invoice.forEach(row=>{
      const value = row.qty * row.price;
      const tr = document.createElement('tr');
      tr.innerHTML = `
        <td>${escapeHtml(row.name)}</td>
        <td>
          <div class="d-flex justify-content-center align-items-center gap-1">
            <button class="btn btn-sm btn-outline-secondary qty-btn" onclick="dec(${row.code})">-</button>
            <span style="min-width:32px;display:inline-block">${row.qty}</span>
            <button class="btn btn-sm btn-outline-secondary qty-btn" onclick="inc(${row.code})">+</button>
          </div>
        </td>
        <td>${row.price.toFixed(2)}</td>
        <td>${value.toFixed(2)}</td>
        <td><button class="btn btn-sm btn-danger" onclick="removeItem(${row.code})">❌</button></td>
      `;
      tbody.appendChild(tr);
    });

    const t = getTotals();
    document.getElementById('subTotal').textContent = t.sub.toFixed(2);
    document.getElementById('discountDisp').textContent = t.discountAmt.toFixed(2);
    document.getElementById('service').textContent = t.serviceAmt.toFixed(2);
    document.getElementById('tax').textContent = t.tax.toFixed(2);
    document.getElementById('total').textContent = t.total.toFixed(2);
    calcChange();
  }

  function calcChange(){
    const total = getTotals().total;
    const payCash = parseFloat(document.getElementById('payCash').value||0);
    const payCard = parseFloat(document.getElementById('payCard').value||0);
    const received = parseFloat(document.getElementById('amountReceived').value||0);
    const cashNeeded = Math.max(0, total - payCard);
    const change = Math.max(0, received - Math.min(received, cashNeeded));
    document.getElementById('changeDue').value = change.toFixed(2);
  }

  ['discountType','discountValue','payCash','payCard','amountReceived'].forEach(id=>{
    document.getElementById(id).addEventListener('input', renderInvoice);
  });

  async function ensureTableFree(){
    if(!sel.table){ alert('اختر الترابيزة أولاً'); return false; }
    try{
      const res = await fetch('?action=check_table_busy&table_id=' + encodeURIComponent(sel.table));
      const data = await res.json();
      if(data.busy){
        alert('الترابيزة مشغولة بفاتورة غير مدفوعة. لا يمكن الحفظ.');
        return false;
      }
      return true;
    }catch(e){
      alert('تعذر التحقق من حالة الترابيزة'); return false;
    }
  }

  async function saveReceipt(){
    if(invoice.size===0){ alert('أضف أصناف أولاً'); return; }
    if(!sel.table){ alert('اختر ترابيزة'); return; }
    if(!(await ensureTableFree())) return;

    const items = [];
    invoice.forEach(r=> items.push({code:r.code, qty:r.qty}));

    const totals = getTotals();
    const payload = {
      csrf: CSRF,
      receipt_type: 'DineIn',
      branch_id: parseInt(sel.branch || <?= (int)$branch_id ?>, 10),
      floor_id: sel.floor ? parseInt(sel.floor,10): null,
      section_id: sel.section ? parseInt(sel.section,10): null,
      table_id: parseInt(sel.table,10),
      guests: parseInt(document.getElementById('guests').value||'1',10),
      discount_type: totals.dtype,
      discount_value: totals.dval,
      service_percent: <?= (float)($branch['ServicePercent'] ?? 0) ?>,
      notes: document.getElementById('notes').value || null,
      customer_email: document.getElementById('customerEmail').value || null,
      pay_cash: parseFloat(document.getElementById('payCash').value||0),
      pay_card: parseFloat(document.getElementById('payCard').value||0),
      amount_received: parseFloat(document.getElementById('amountReceived').value||0),
      items
    };

    const res = await fetch('../api/save_receipt.php', {
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body: JSON.stringify(payload)
    });
    const data = await res.json();
    if(!res.ok || !data.success){
      alert('فشل الحفظ: ' + (data.message || res.status));
      return;
    }
    lastReceiptId = data.receipt_id;
    document.getElementById('printBtn').disabled = false;
    alert('تم الحفظ بنجاح. رقم الفاتورة: #' + lastReceiptId);
    // بعد الحفظ اتوقع الترابيزة تبقى مشغولة لحد السداد
    tableBusy = true;
    $('#tableStatus').text('⚠️ الترابيزة أصبحت مشغولة (فاتورة غير مدفوعة)').css('color','#b91c1c');
  }

  function printLast(){
    if(!lastReceiptId) return;
    window.open('../receipt/print.php?id=' + lastReceiptId, '_blank');
  }

  function resetInvoice(){
    invoice.clear();
    document.getElementById('discountType').value='amount';
    document.getElementById('discountValue').value='0';
    document.getElementById('payCash').value='0';
    document.getElementById('payCard').value='0';
    document.getElementById('amountReceived').value='0';
    document.getElementById('changeDue').value='0.00';
    document.getElementById('notes').value='';
    document.getElementById('customerEmail').value='';
    lastReceiptId=null;
    document.getElementById('printBtn').disabled = true;
    renderInvoice();
  }

  // اختصارات
  document.addEventListener('keydown', (e)=>{
    if(e.key==='F2'){ e.preventDefault(); saveReceipt(); }
    if(e.key==='Escape'){ e.preventDefault(); resetInvoice(); }
    if((e.ctrlKey || e.metaKey) && e.key.toLowerCase()==='p'){
      e.preventDefault(); printLast();
    }
  });

  // بدء
  window.addEventListener('DOMContentLoaded', ()=>{ showItems(firstGroup); renderInvoice(); });
</script>
</body>
</html>
