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

/** الصلاحيات البسيطة */
$user = current_user();          // افترض دالة بترجع بيانات المستخدم
$can_discount = !empty($user['can_discount']); // تحكم في إظهار/تعطيل الخصم

$branch_id = $user['branch_id'] ?? 1;

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

/** جلب المجموعات (مع لون) */
$groups = $pdo->query("SELECT Code, CName, ColorHex FROM categories ORDER BY SortOrder, Code")->fetchAll();
/** لو ماعندك ColorHex أضف عمود بسيط في Categories أو هنختار ألوان افتراضية من JS */

/** جلب الأصناف مجمعة حسب المجموعة */
$items = $pdo->query("
  SELECT Code, IName, PriceTW, Cat_Code
  FROM items
  WHERE Active=1
  ORDER BY Cat_Code, 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 $row) {
    $items[$row['Cat_Code']][] = $row;
}


/** CSRF */
$token = bin2hex(random_bytes(16));
$_SESSION['csrf'] = $token;
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title>🍔💳 مبيعات تيك أواي</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="preconnect" href="https://cdn.jsdelivr.net">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.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.1rem;font-weight:bold;color:#d35400}
    .qty-btn{width:32px;height:32px;line-height:16px;padding:0}
    .locked{pointer-events: none; opacity:.6}
    .kbd{background:#111;color:#fff;border-radius:6px;padding:2px 6px;font-size:.8rem}
    @media (max-width:768px){
      .item-btn{min-width:120px}
      .pane{padding:8px}
    }
  </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></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="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">
        <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['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>

<script>
  const itemsByGroup = <?= json_encode($items, JSON_UNESCAPED_UNICODE) ?>;
  const TAX_RATE = <?= (float)$branch['TaxRate'] ?>;
  const CURRENCY = <?= json_encode($branch['Currency']) ?>;
  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;

  // UI: تحميل أول مجموعة تلقائيًا
  const firstGroup = Object.keys(itemsByGroup)[0];
  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=>{
    // // ✅ Debug: اطبع الـ item كامل
    // console.log("Item from DB:", item);

    // // ✅ Debug: اطبع الـ Code بس
    // console.log("Item.Code =", item.Code);

    const btn = document.createElement('button');
    btn.className = 'item-btn';
    btn.style.background = 'linear-gradient(135deg,#27ae60,#2ecc71)';
    btn.textContent = `${item.IName} - ${parseFloat(item.PriceTW).toFixed(2)} ${CURRENCY}`;
    btn.onclick = ()=> addItem(item);
    container.appendChild(btn);
  });
}


  function addItem(item){
  const code = item.Code;   // من الجدول العمود اسمه Code
  if(!invoice.has(code)){
    invoice.set(code, {
      code: code,
      name: item.IName,
      qty: 0,
      price: parseFloat(item.PriceTW)
    });
  }
  invoice.get(code).qty += 1;
  renderInvoice();
}




  function inc(code){ const row = invoice.get(code); if(!row) return; row.qty+=1; renderInvoice(); }
  function dec(code){ const row = invoice.get(code); if(!row) return; row.qty = Math.max(1, row.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 taxable = Math.max(0, sub - discountAmt);
    const tax = +(taxable * (TAX_RATE/100)).toFixed(2);
    const total = +(taxable + tax).toFixed(2);

    return {sub:+sub.toFixed(2), discountAmt:+discountAmt.toFixed(2), tax, total, 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>${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('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 saveReceipt(){
    if(invoice.size===0){ alert('أضف أصناف أولاً'); return; }
    const items = [];
    
    invoice.forEach(r=> items.push({code:r.code, qty:r.qty}));
    

    const totals = getTotals();
    const payload = {
      csrf: CSRF,
      branch_id: <?= (int)$branch_id ?>,
      receipt_type: 'TakeAway',
      discount_type: totals.dtype,
      discount_value: totals.dval,
      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
    };
    // console.log("Payload to send:", payload);

    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);
  }

  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();
    }
  });
</script>
</body>
</html>
