<?php
require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/csrf.php';
require_once __DIR__ . '/../app/docno.php';
require_once __DIR__ . '/../app/ledger.php';
require_once __DIR__ . '/../app/audit.php';

$me  = require_role(['ADMIN','DISTRIBUTOR']);
$pdo = db();
$csrf = csrf_token();

$action = $_GET['action'] ?? 'list';

function json_out($data, int $code=200): void {
  http_response_code($code);
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($data, JSON_UNESCAPED_UNICODE);
  exit;
}

function my_distributor_id(array $me): ?int {
  if ($me['role'] === 'DISTRIBUTOR') {
    return !empty($me['distributor_id']) ? (int)$me['distributor_id'] : null;
  }
  return null;
}

function fetch_outlets_for_distributor(PDO $pdo, int $distributorId): array {
  $st = $pdo->prepare("SELECT o.id, o.name FROM outlets o JOIN distributor_outlets do ON do.outlet_id=o.id WHERE o.active=1 AND do.distributor_id=? ORDER BY o.name");
  $st->execute([$distributorId]);
  return $st->fetchAll();
}

function fetch_products(PDO $pdo): array {
  return $pdo->query("SELECT id, name FROM products WHERE active=1 ORDER BY name")->fetchAll();
}

function fetch_issues_for_product(PDO $pdo, int $productId): array {
  $st = $pdo->prepare("SELECT id, issue_number, issue_month, issue_year, cover_price, status FROM issues WHERE product_id=? ORDER BY issue_year DESC, issue_month DESC, issue_number DESC");
  $st->execute([$productId]);
  return $st->fetchAll();
}

function distributor_issue_balance(PDO $pdo, int $distributorId, int $issueId): int {
  $st = $pdo->prepare("SELECT COALESCE(SUM(CASE WHEN status='POSTED' THEN (qty_in-qty_out) ELSE 0 END),0) bal FROM inventory_ledger WHERE entity_type='DISTRIBUTOR' AND entity_id=? AND issue_id=?");
  $st->execute([$distributorId, $issueId]);
  return (int)$st->fetchColumn();
}

function outlet_label(PDO $pdo, int $outletId): string {
  $st = $pdo->prepare("SELECT name FROM outlets WHERE id=?");
  $st->execute([$outletId]);
  return (string)($st->fetchColumn() ?: '');
}

function distributor_label(PDO $pdo, int $distId): string {
  $st = $pdo->prepare("SELECT name FROM distributors WHERE id=?");
  $st->execute([$distId]);
  return (string)($st->fetchColumn() ?: '');
}

function fetch_delivery(PDO $pdo, int $id, ?int $restrictDistributorId = null): ?array {
  $sql = "
    SELECT od.*, o.name AS outlet_name, d.name AS distributor_name, u.name AS created_by_name
    FROM outlet_deliveries od
    JOIN outlets o ON o.id=od.outlet_id
    JOIN distributors d ON d.id=od.distributor_id
    JOIN users u ON u.id=od.created_by
    WHERE od.id=?
  ";
  $args = [$id];
  if ($restrictDistributorId !== null) {
    $sql .= " AND od.distributor_id=?";
    $args[] = $restrictDistributorId;
  }
  $st = $pdo->prepare($sql);
  $st->execute($args);
  $r = $st->fetch();
  return $r ?: null;
}

function fetch_delivery_items(PDO $pdo, int $deliveryId): array {
  $st = $pdo->prepare("
    SELECT odi.*, p.name AS product_name, i.issue_number, i.issue_month, i.issue_year
    FROM outlet_delivery_items odi
    JOIN issues i ON i.id=odi.issue_id
    JOIN products p ON p.id=i.product_id
    WHERE odi.delivery_id=?
    ORDER BY p.name, i.issue_year DESC, i.issue_month DESC
  ");
  $st->execute([$deliveryId]);
  return $st->fetchAll();
}

// ───────────────────── API ─────────────────────
$distId = my_distributor_id($me);

if ($action === 'api_bootstrap') {
  if ($distId === null) json_out(['ok'=>false,'error'=>'Only distributor can create'], 403);
  json_out([
    'ok'=>true,
    'distributor'=>['id'=>$distId,'name'=>distributor_label($pdo,$distId)],
    'outlets'=>fetch_outlets_for_distributor($pdo,$distId),
    'products'=>fetch_products($pdo),
  ]);
}

if ($action === 'api_issues') {
  if ($distId === null) json_out(['ok'=>false,'error'=>'Only distributor'], 403);
  $productId = (int)($_GET['product_id'] ?? 0);
  if ($productId<=0) json_out(['ok'=>false,'error'=>'Bad product_id'], 400);
  $issues = [];
  foreach (fetch_issues_for_product($pdo, $productId) as $i) {
    $issueId = (int)$i['id'];
    $bal = distributor_issue_balance($pdo, $distId, $issueId);
    // لا نعرض إصدار بلا رصيد (لتسهيل الاستخدام)
    if ($bal <= 0) continue;
    $label = 'عدد '.($i['issue_number'] ?? '').' - '.str_pad((string)$i['issue_month'],2,'0',STR_PAD_LEFT).'/'.$i['issue_year'];
    $issues[] = [
      'id'=>$issueId,
      'label'=>$label,
      'cover_price'=>(float)$i['cover_price'],
      'available_qty'=>$bal,
    ];
  }
  json_out(['ok'=>true,'issues'=>$issues]);
}

if ($action === 'api_view') {
  $id = (int)($_GET['id'] ?? 0);
  if ($id<=0) json_out(['ok'=>false,'error'=>'Bad id'], 400);
  $d = fetch_delivery($pdo, $id, $distId);
  if (!$d) json_out(['ok'=>false,'error'=>'Not found'], 404);
  $items = fetch_delivery_items($pdo, $id);
  // حساب إجماليات (سعر الوحدة: unit_price_applied أو cover_price)
  $total = 0.0;
  foreach ($items as &$it) {
    $unit = $it['unit_price_applied'];
    if ($unit === null) {
      $st = $pdo->prepare("SELECT cover_price FROM issues WHERE id=?");
      $st->execute([(int)$it['issue_id']]);
      $unit = (float)$st->fetchColumn();
    } else {
      $unit = (float)$unit;
    }
    $it['unit_price'] = $unit;
    $it['line_total'] = round($unit * (int)$it['qty_delivered'], 3);
    $total += $it['line_total'];
  }
  json_out(['ok'=>true,'delivery'=>$d,'items'=>$items,'total'=>round($total,3)]);
}

// ───────────────────── Confirm Sale ─────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $op = $_POST['op'] ?? '';

  if ($op === 'confirm_sale') {
    if ($distId === null) exit('Only distributor can confirm sale');

    $outlet_id = (int)($_POST['outlet_id'] ?? 0);
    $deal_ui   = trim($_POST['deal_ui'] ?? ''); // CASH / CONSIGNMENT
    $discount_percent = (float)($_POST['discount_percent'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');

    if ($outlet_id<=0) exit('اختر المنفذ');
    if (!in_array($deal_ui, ['CASH','CONSIGNMENT'], true)) exit('اختر نوع التعامل');
    $discount_percent = max(0.0, min(100.0, $discount_percent));

    // تحقق: المنفذ تابع للموزع
    $st = $pdo->prepare("SELECT COUNT(*) FROM distributor_outlets WHERE distributor_id=? AND outlet_id=?");
    $st->execute([$distId, $outlet_id]);
    if ((int)$st->fetchColumn() <= 0) exit('هذا المنفذ غير مرتبط بالموزع');

    $issue_ids = $_POST['issue_id'] ?? [];
    $qtys      = $_POST['qty'] ?? [];
    if (!is_array($issue_ids) || !is_array($qtys) || count($issue_ids) === 0) exit('أضف أصناف أولاً');

    $lines = [];
    for ($k=0; $k<count($issue_ids); $k++) {
      $iid = (int)$issue_ids[$k];
      $q   = (int)$qtys[$k];
      if ($iid<=0 || $q<=0) continue;
      $lines[] = ['issue_id'=>$iid,'qty'=>$q];
    }
    if (count($lines) === 0) exit('أضف كمية صحيحة');

    // تحقق رصيد الموزع لكل إصدار
    foreach ($lines as $ln) {
      $bal = distributor_issue_balance($pdo, $distId, (int)$ln['issue_id']);
      if ($ln['qty'] > $bal) {
        exit('الكمية المطلوبة أكبر من المتوفر لإحدى الإصدارات');
      }
    }

    $deal_type = $deal_ui === 'CASH' ? 'DIRECT_SALE' : 'CONSIGNMENT';

    $pdo->beginTransaction();
    try {
      // إنشاء سند تسليم مباشر (معتمد فورًا — بدون موافقات)
      $deliveryAt = date('Y-m-d H:i:s');
      $deliveryNo = next_doc_no($pdo, 'ODL', date('Y-m-d'));

      $pdo->prepare("INSERT INTO outlet_deliveries (delivery_no, distributor_id, outlet_id, delivery_at, deal_type, created_by, status, notes) VALUES (?,?,?,?,?,?, 'APPROVED', ?)")
          ->execute([$deliveryNo, $distId, $outlet_id, $deliveryAt, $deal_type, (int)$me['id'], $notes]);
      $deliveryId = (int)$pdo->lastInsertId();

      // سطور
      foreach ($lines as $ln) {
        $issueId = (int)$ln['issue_id'];
        $qty = (int)$ln['qty'];
        $st = $pdo->prepare("SELECT cover_price FROM issues WHERE id=?");
        $st->execute([$issueId]);
        $cover = (float)$st->fetchColumn();
        $unit = $cover;
        if ($deal_type === 'DIRECT_SALE' && $discount_percent > 0) {
          $unit = round($cover * (1.0 - ($discount_percent/100.0)), 3);
        }
        $pdo->prepare("INSERT INTO outlet_delivery_items (delivery_id, issue_id, qty_delivered, unit_price_applied) VALUES (?,?,?,?)")
            ->execute([$deliveryId, $issueId, $qty, ($deal_type === 'DIRECT_SALE' ? $unit : null)]);

        // Ledger: خصم من مخزون الموزع + إضافة للمنفذ
        ledger_post($pdo, 'DISTRIBUTOR', $distId, $issueId, 0, $qty, 'OUTLET_DELIVERY', $deliveryId, (int)$me['id'], 'Delivery to outlet');
        ledger_post($pdo, 'OUTLET', $outlet_id, $issueId, $qty, 0, 'OUTLET_DELIVERY', $deliveryId, (int)$me['id'], 'Received from distributor');
      }

      // CASH: إنشاء فاتورة مباشرة مدفوعة
      if ($deal_type === 'DIRECT_SALE') {
        $invNo = next_doc_no($pdo, 'INV', date('Y-m-d'));
        $pdo->prepare("INSERT INTO invoices (invoice_no, outlet_id, distributor_id, source_type, source_id, issued_at, status, currency, total_amount, total_paid, balance_due, created_by)
                       VALUES (?,?,?,'DIRECT_SALE',?,NOW(),'ISSUED','OMR',0,0,0,?)")
            ->execute([$invNo, $outlet_id, $distId, $deliveryId, (int)$me['id']]);
        $invoiceId = (int)$pdo->lastInsertId();
        $total = 0.0;
        foreach ($lines as $ln) {
          $issueId = (int)$ln['issue_id'];
          $qty = (int)$ln['qty'];
          $st = $pdo->prepare("SELECT cover_price FROM issues WHERE id=?");
          $st->execute([$issueId]);
          $cover = (float)$st->fetchColumn();
          $unit = $discount_percent>0 ? round($cover * (1.0 - ($discount_percent/100.0)), 3) : $cover;
          $lineTotal = round($unit * $qty, 3);
          $total += $lineTotal;
          $pdo->prepare("INSERT INTO invoice_items (invoice_id, issue_id, qty, unit_price, line_total, commission_amount) VALUES (?,?,?,?,?,0)")
              ->execute([$invoiceId, $issueId, $qty, $unit, $lineTotal]);
        }
        $total = round($total, 3);
        // CASH: نعتبرها مدفوعة بالكامل
        $pdo->prepare("UPDATE invoices SET total_amount=?, total_paid=?, balance_due=0 WHERE id=?")
            ->execute([$total, $total, $invoiceId]);
      }

      audit_log($pdo, (int)$me['id'], 'CREATE', 'outlet_deliveries', $deliveryId, ['delivery_no'=>$deliveryNo,'deal_type'=>$deal_type,'discount_percent'=>$discount_percent]);

      $pdo->commit();
      flash('تم تأكيد البيع بنجاح');
      redirect('outlet_deliveries.php');
    } catch (Throwable $e) {
      $pdo->rollBack();
      throw $e;
    }
  }
}

// ───────────────────── Page (List) ─────────────────────
$where = "WHERE od.status='APPROVED'";
$args = [];
if ($distId !== null) {
  $where .= " AND od.distributor_id=?";
  $args[] = $distId;
}

$st = $pdo->prepare("
  SELECT od.id, od.delivery_no, od.delivery_at, od.deal_type, od.outlet_id, o.name AS outlet_name
  FROM outlet_deliveries od
  JOIN outlets o ON o.id=od.outlet_id
  $where
  ORDER BY od.id DESC
  LIMIT 200
");
$st->execute($args);
$rows = $st->fetchAll();

$distName = ($distId!==null) ? distributor_label($pdo,$distId) : '';

?><!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>أوامر التسليم — MGZ</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
<style>
  body{font-family:Tahoma,Arial; background:#f4f7f6; margin:0; padding:16px;}
  .topbar{display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; margin-bottom:12px;}
  .btn{background:#1a73e8; color:#fff; border:none; padding:10px 14px; border-radius:10px; cursor:pointer; font-size:14px;}
  .btn:disabled{opacity:.5; cursor:not-allowed;}
  .btn-secondary{background:#6c757d;}
  .card{background:#fff; border-radius:14px; padding:14px; box-shadow:0 2px 10px rgba(0,0,0,.06);}
  table{width:100%; border-collapse:collapse;}
  th,td{padding:10px; border-bottom:1px solid #eee; font-size:13px; text-align:right;}
  th{background:#fafafa;}
  .pill{display:inline-block; padding:4px 10px; border-radius:999px; font-size:12px; background:#eef2ff;}
  .pill.cash{background:#e8fff1;}
  .pill.cons{background:#fff7e6;}
  /* Modal */
  .modal-backdrop{position:fixed; inset:0; background:rgba(0,0,0,.55); display:none; align-items:center; justify-content:center; z-index:9999;}
  .modal{background:#fff; width:min(920px, 96vw); max-height:90vh; overflow:auto; border-radius:16px; padding:14px;}
  @media (max-width: 520px){
    .modal{width:98vw; height:92vh; max-height:92vh; border-radius:14px;}
    .btn{width:100%;}
  }
  .modal-header{display:flex; justify-content:space-between; align-items:center; gap:10px; margin-bottom:10px;}
  .x{background:transparent; border:none; font-size:22px; cursor:pointer;}
  .grid{display:grid; grid-template-columns:1fr 1fr; gap:10px;}
  @media (max-width: 520px){ .grid{grid-template-columns:1fr;} }
  select,input,textarea{width:100%; padding:10px; border:1px solid #ddd; border-radius:10px; font-size:14px;}
  textarea{min-height:70px; resize:vertical;}
  .items{width:100%; border:1px solid #eee; border-radius:12px; overflow:hidden; margin-top:10px;}
  .items th,.items td{border-bottom:1px solid #eee;}
  .row-actions{display:flex; gap:6px;}
  .linkbtn{border:none; background:#f1f5ff; padding:8px 10px; border-radius:10px; cursor:pointer;}
  .totals{margin-top:10px; display:grid; grid-template-columns:1fr 1fr 1fr; gap:10px;}
  @media (max-width: 520px){ .totals{grid-template-columns:1fr;} }
  .muted{color:#666; font-size:12px;}
</style>
</head>
<body>

<div class="topbar">
  <div>
    <a href="../dashboard.php" class="btn btn-secondary" style="text-decoration:none;">⬅ العودة</a>
  </div>
  <div style="flex:1"></div>
  <?php if ($me['role']==='DISTRIBUTOR'): ?>
    <div class="muted">الموزع: <?=h($distName)?></div>
    <button class="btn" id="btnCreate">إنشاء</button>
  <?php endif; ?>
</div>

<?php show_flash(); ?>

<div class="card">
  <h3 style="margin:0 0 10px 0;">📋 آخر 200 أمر تسليم</h3>
  <table>
    <thead>
      <tr>
        <th>#</th>
        <th>المنفذ</th>
        <th>التاريخ</th>
        <th>نوع التعامل</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <?php if (!$rows): ?>
        <tr><td colspan="5" class="muted">لا يوجد بيانات</td></tr>
      <?php else: foreach ($rows as $r): ?>
        <tr>
          <td><?=h($r['delivery_no'] ?: $r['id'])?></td>
          <td><?=h($r['outlet_name'])?></td>
          <td><?=h(date('Y-m-d H:i', strtotime($r['delivery_at'])))?></td>
          <td>
            <?php if ($r['deal_type']==='DIRECT_SALE'): ?>
              <span class="pill cash">كاش</span>
            <?php else: ?>
              <span class="pill cons">أمانة</span>
            <?php endif; ?>
          </td>
          <td><button class="linkbtn" data-open="<?= (int)$r['id'] ?>">فتح</button></td>
        </tr>
      <?php endforeach; endif; ?>
    </tbody>
  </table>
</div>

<!-- Create Modal -->
<div class="modal-backdrop" id="mCreate">
  <div class="modal" role="dialog" aria-modal="true">
    <div class="modal-header">
      <div>
        <div style="font-weight:700;">إنشاء عملية بيع / تسليم</div>
        <div class="muted">لن يتم حفظ أي شيء إلا بعد الضغط على “تأكيد البيع”</div>
      </div>
      <button class="x" data-close="#mCreate">×</button>
    </div>

    <form method="post" id="frmCreate">
      <input type="hidden" name="csrf" value="<?=h($csrf)?>">
      <input type="hidden" name="op" value="confirm_sale">

      <div class="grid">
        <div>
          <label class="muted">المنفذ</label>
          <select name="outlet_id" id="outletSel" required></select>
        </div>
        <div>
          <label class="muted">نوع التعامل</label>
          <select name="deal_ui" id="dealSel" required>
            <option value="">— اختر —</option>
            <option value="CASH">كاش</option>
            <option value="CONSIGNMENT">أمانة</option>
          </select>
        </div>
      </div>

      <div class="items" style="margin-top:12px;">
        <table class="items" id="itemsTbl">
          <thead>
            <tr>
              <th style="width:32%">المنتج</th>
              <th style="width:30%">الإصدار</th>
              <th style="width:14%">المتاح</th>
              <th style="width:12%">الكمية</th>
              <th style="width:12%">الإجمالي</th>
              <th style="width:70px"></th>
            </tr>
          </thead>
          <tbody id="itemsBody"></tbody>
        </table>
      </div>

      <div style="margin-top:10px;">
        <button type="button" class="linkbtn" id="btnAddLine">+ إضافة منتج/إصدار</button>
      </div>

      <div class="totals">
        <div>
          <label class="muted">الإجمالي قبل الخصم</label>
          <input type="text" id="totalBefore" readonly value="0.000">
        </div>
        <div>
          <label class="muted">خصم %</label>
          <input type="number" min="0" max="100" step="1" name="discount_percent" id="discountPct" value="0">
        </div>
        <div>
          <label class="muted">الإجمالي بعد الخصم</label>
          <input type="text" id="totalAfter" readonly value="0.000">
        </div>
      </div>

      <div style="margin-top:10px;">
        <label class="muted">ملاحظة (اختياري)</label>
        <textarea name="notes" placeholder="..."></textarea>
      </div>

      <div style="margin-top:12px; display:flex; gap:10px; flex-wrap:wrap;">
        <button type="submit" class="btn" id="btnConfirm" disabled>تأكيد البيع</button>
        <button type="button" class="btn btn-secondary" data-close="#mCreate">إلغاء</button>
      </div>

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

<!-- View Modal -->
<div class="modal-backdrop" id="mView">
  <div class="modal" role="dialog" aria-modal="true">
    <div class="modal-header">
      <div style="font-weight:700;">تفاصيل المعاملة</div>
      <button class="x" data-close="#mView">×</button>
    </div>
    <div id="viewBox" class="muted">...</div>
  </div>
</div>

<script>
const $ = (s, el=document) => el.querySelector(s);
const $$ = (s, el=document) => Array.from(el.querySelectorAll(s));

function openModal(id){
  const m = document.getElementById(id);
  m.style.display='flex';
}
function closeModal(sel){
  const m = document.querySelector(sel);
  if(m) m.style.display='none';
}

document.addEventListener('click', (e)=>{
  const c = e.target.getAttribute('data-close');
  if(c){ closeModal(c); }
});

// View details
$$('[data-open]').forEach(btn=>{
  btn.addEventListener('click', async ()=>{
    const id = btn.getAttribute('data-open');
    openModal('mView');
    $('#viewBox').textContent = '...';
    const res = await fetch('outlet_deliveries.php?action=api_view&id='+encodeURIComponent(id));
    const js = await res.json();
    if(!js.ok){ $('#viewBox').textContent = js.error || 'خطأ'; return; }
    const d = js.delivery;
    const items = js.items;
    let html = '';
    html += `<div class="card" style="margin-bottom:10px;">
      <div><b>رقم:</b> ${escapeHtml(d.delivery_no || d.id)}</div>
      <div><b>المنفذ:</b> ${escapeHtml(d.outlet_name)}</div>
      <div><b>نوع التعامل:</b> ${d.deal_type==='DIRECT_SALE' ? 'كاش' : 'أمانة'}</div>
      <div><b>التاريخ:</b> ${escapeHtml(d.delivery_at)}</div>
      ${d.notes ? `<div><b>ملاحظة:</b> ${escapeHtml(d.notes)}</div>`:''}
    </div>`;
    html += `<div class="card"><table><thead><tr>
      <th>المنتج</th><th>الإصدار</th><th>الكمية</th><th>سعر الوحدة</th><th>الإجمالي</th>
    </tr></thead><tbody>`;
    items.forEach(it=>{
      const label = `عدد ${it.issue_number||''} - ${String(it.issue_month).padStart(2,'0')}/${it.issue_year}`;
      html += `<tr>
        <td>${escapeHtml(it.product_name)}</td>
        <td>${escapeHtml(label)}</td>
        <td>${it.qty_delivered}</td>
        <td>${Number(it.unit_price).toFixed(3)}</td>
        <td>${Number(it.line_total).toFixed(3)}</td>
      </tr>`;
    });
    html += `</tbody></table>
      <div style="margin-top:8px; font-weight:700;">الإجمالي: ${Number(js.total).toFixed(3)}</div>
    </div>`;
    $('#viewBox').innerHTML = html;
  });
});

function escapeHtml(s){
  return String(s??'').replace(/[&<>"']/g, c=>({"&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#39;"}[c]));
}

// Create flow
const btnCreate = document.getElementById('btnCreate');
if(btnCreate){
  btnCreate.addEventListener('click', async ()=>{
    openModal('mCreate');
    await bootstrapCreate();
    resetLines();
    addLine();
    recalc();
  });
}

let BOOT = null;
async function bootstrapCreate(){
  if(BOOT) return;
  const r = await fetch('outlet_deliveries.php?action=api_bootstrap');
  const js = await r.json();
  if(!js.ok){ alert(js.error||'خطأ'); return; }
  BOOT = js;
  // outlets
  const oSel = $('#outletSel');
  oSel.innerHTML = '<option value="">— اختر —</option>';
  js.outlets.forEach(o=>{
    const op = document.createElement('option');
    op.value = o.id;
    op.textContent = o.name;
    oSel.appendChild(op);
  });
}

function resetLines(){
  $('#itemsBody').innerHTML='';
}

function addLine(){
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td><select class="prodSel"><option value="">— اختر —</option></select></td>
    <td><select class="issueSel" disabled><option value="">— اختر —</option></select>
        <input type="hidden" name="issue_id[]" class="issueIdHidden">
    </td>
    <td class="avail">—</td>
    <td><input type="number" class="qtyInp" name="qty[]" min="0" step="1" value="0"></td>
    <td class="lineTotal">0.000</td>
    <td><button type="button" class="linkbtn btnRemove">حذف</button></td>
  `;
  $('#itemsBody').appendChild(tr);

  const prodSel = $('.prodSel', tr);
  const issueSel = $('.issueSel', tr);

  // fill products
  (BOOT?.products||[]).forEach(p=>{
    const op = document.createElement('option');
    op.value = p.id;
    op.textContent = p.name;
    prodSel.appendChild(op);
  });

  prodSel.addEventListener('change', async ()=>{
    const pid = prodSel.value;
    issueSel.innerHTML = '<option value="">— اختر —</option>';
    issueSel.disabled = true;
    $('.avail', tr).textContent='—';
    $('.issueIdHidden', tr).value='';
    tr.dataset.cover='0';
    tr.dataset.avail='0';
    if(!pid) { recalc(); return; }
    const r = await fetch('outlet_deliveries.php?action=api_issues&product_id='+encodeURIComponent(pid));
    const js = await r.json();
    if(!js.ok){ alert(js.error||'خطأ'); return; }
    js.issues.forEach(i=>{
      const op = document.createElement('option');
      op.value = i.id;
      op.textContent = i.label;
      op.dataset.cover = i.cover_price;
      op.dataset.avail = i.available_qty;
      issueSel.appendChild(op);
    });
    issueSel.disabled = false;
  });

  issueSel.addEventListener('change', ()=>{
    const opt = issueSel.options[issueSel.selectedIndex];
    if(!opt || !issueSel.value){
      $('.avail', tr).textContent='—';
      $('.issueIdHidden', tr).value='';
      tr.dataset.cover='0';
      tr.dataset.avail='0';
      recalc();
      return;
    }
    const avail = Number(opt.dataset.avail||0);
    const cover = Number(opt.dataset.cover||0);
    $('.avail', tr).textContent = String(avail);
    $('.issueIdHidden', tr).value = issueSel.value;
    tr.dataset.cover = String(cover);
    tr.dataset.avail = String(avail);
    // clamp qty
    const q = $('.qtyInp', tr);
    if(Number(q.value) > avail) q.value = avail;
    recalc();
  });

  $('.qtyInp', tr).addEventListener('input', ()=>{
    const avail = Number(tr.dataset.avail||0);
    const q = $('.qtyInp', tr);
    let v = Number(q.value||0);
    if(v<0) v=0;
    if(avail>0 && v>avail) v=avail;
    q.value = String(Math.floor(v));
    recalc();
  });

  $('.btnRemove', tr).addEventListener('click', ()=>{
    tr.remove();
    recalc();
  });
}

$('#btnAddLine')?.addEventListener('click', ()=>{ addLine(); });
$('#discountPct')?.addEventListener('input', ()=>recalc());
$('#dealSel')?.addEventListener('change', ()=>recalc());
$('#outletSel')?.addEventListener('change', ()=>recalc());

function recalc(){
  const deal = $('#dealSel')?.value || '';
  let total = 0;
  $$('#itemsBody tr').forEach(tr=>{
    const cover = Number(tr.dataset.cover||0);
    const qty = Number($('.qtyInp', tr)?.value||0);
    const line = cover * qty;
    $('.lineTotal', tr).textContent = Number(line).toFixed(3);
    total += line;
  });
  $('#totalBefore').value = Number(total).toFixed(3);
  let pct = Number($('#discountPct')?.value||0);
  if(pct<0) pct=0;
  if(pct>100) pct=100;
  const after = total * (1 - pct/100);
  $('#totalAfter').value = Number(after).toFixed(3);

  // enable confirm
  const okOutlet = !!($('#outletSel')?.value);
  const okDeal = (deal==='CASH' || deal==='CONSIGNMENT');
  let okLines = false;
  $$('#itemsBody tr').forEach(tr=>{
    const iid = $('.issueIdHidden', tr)?.value;
    const qty = Number($('.qtyInp', tr)?.value||0);
    if(iid && qty>0) okLines = true;
  });
  $('#btnConfirm').disabled = !(okOutlet && okDeal && okLines);
}
</script>

</body>
</html>
