<?php
require_once __DIR__ . '/../app/csrf.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/upload.php';

$me = require_role(['ADMIN','WAREHOUSE']);
$pdo = db();

function fetch_distributors(PDO $pdo): array {
  return $pdo->query("SELECT id, name FROM distributors WHERE active=1 ORDER BY name")->fetchAll();
}
function fetch_issues(PDO $pdo): array {
  return $pdo->query("
    SELECT i.id, CONCAT(p.name,' - ',LPAD(i.issue_month,2,'0'),'/',i.issue_year) AS label
    FROM issues i JOIN products p ON p.id=i.product_id
    WHERE i.status='OPEN'
    ORDER BY i.issue_year DESC, i.issue_month DESC, p.name
  ")->fetchAll();
}
function fetch_dispatch(PDO $pdo, int $id): ?array {
  $st = $pdo->prepare("
    SELECT d.*,
           u1.name AS created_by_name,
           u2.name AS manager_by_name,
           dist.name AS distributor_name
    FROM distributor_dispatches d
    JOIN users u1 ON u1.id = d.created_by
    LEFT JOIN users u2 ON u2.id = d.manager_by
    JOIN distributors dist ON dist.id = d.distributor_id
    WHERE d.id=?
  ");
  $st->execute([$id]);
  $r = $st->fetch();
  return $r ?: null;
}
function fetch_dispatch_items(PDO $pdo, int $dispatchId): array {
  $st = $pdo->prepare("
    SELECT di.*, CONCAT(p.name,' - ',LPAD(i.issue_month,2,'0'),'/',i.issue_year) AS issue_label
    FROM distributor_dispatch_items di
    JOIN issues i ON i.id=di.issue_id
    JOIN products p ON p.id=i.product_id
    WHERE di.dispatch_id=?
    ORDER BY issue_label
  ");
  $st->execute([$dispatchId]);
  return $st->fetchAll();
}

$csrf   = csrf_token();
$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);

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

  if ($op === 'create') {
    $distributor_id = (int)($_POST['distributor_id'] ?? 0);
    $dispatch_at    = trim($_POST['dispatch_at'] ?? '');
    if ($distributor_id<=0 || $dispatch_at==='') exit("Bad data");
    $st = $pdo->prepare("INSERT INTO distributor_dispatches (dispatch_no, distributor_id, dispatch_at, created_by, status) VALUES (NULL, ?, ?, ?, 'DRAFT')");
    $st->execute([$distributor_id, $dispatch_at, (int)$me['id']]);
    $newId = (int)$pdo->lastInsertId();
    redirect("dispatches.php?action=edit&id=".$newId);
  }

  if ($op === 'add_item') {
    $dispatch_id = (int)($_POST['dispatch_id'] ?? 0);
    $issue_id    = (int)($_POST['issue_id']    ?? 0);
    $qty         = (int)($_POST['qty']          ?? 0);
    if ($dispatch_id<=0 || $issue_id<=0 || $qty<=0) exit("Bad item");
    $d = fetch_dispatch($pdo, $dispatch_id);
    if (!$d) exit("Dispatch not found");
    if (!in_array($d['status'], ['DRAFT','REJECTED'], true)) exit("Cannot edit in this status");
    $st = $pdo->prepare("INSERT INTO distributor_dispatch_items (dispatch_id, issue_id, qty) VALUES (?,?,?) ON DUPLICATE KEY UPDATE qty = qty + VALUES(qty)");
    $st->execute([$dispatch_id, $issue_id, $qty]);
    redirect("dispatches.php?action=edit&id=".$dispatch_id);
  }

  if ($op === 'remove_item') {
    $dispatch_id = (int)($_POST['dispatch_id'] ?? 0);
    $item_id     = (int)($_POST['item_id']     ?? 0);
    $d = fetch_dispatch($pdo, $dispatch_id);
    if (!$d) exit("Dispatch not found");
    if (!in_array($d['status'], ['DRAFT','REJECTED'], true)) exit("Cannot edit in this status");
    $pdo->prepare("DELETE FROM distributor_dispatch_items WHERE id=? AND dispatch_id=?")->execute([$item_id, $dispatch_id]);
    redirect("dispatches.php?action=edit&id=".$dispatch_id);
  }

  if ($op === 'upload_pod') {
    $dispatch_id = (int)($_POST['dispatch_id'] ?? 0);
    $d = fetch_dispatch($pdo, $dispatch_id);
    if (!$d) exit("Dispatch not found");
    if (!in_array($d['status'], ['DRAFT','REJECTED','SUBMITTED'], true)) exit("Cannot upload in this status");
    if (empty($_FILES['pod']) || !is_array($_FILES['pod'])) exit("No file");
    $attId = save_upload($_FILES['pod'], (int)$me['id']);
    $pdo->prepare("UPDATE distributor_dispatches SET pod_attachment_id=? WHERE id=?")->execute([$attId, $dispatch_id]);
    redirect("dispatches.php?action=edit&id=".$dispatch_id);
  }

  if ($op === 'submit') {
    $dispatch_id = (int)($_POST['dispatch_id'] ?? 0);
    $d = fetch_dispatch($pdo, $dispatch_id);
    if (!$d) exit("Dispatch not found");
    if (!in_array($d['status'], ['DRAFT','REJECTED'], true)) exit("Bad status");
    $cnt = $pdo->prepare("SELECT COUNT(*) c FROM distributor_dispatch_items WHERE dispatch_id=?");
    $cnt->execute([$dispatch_id]);
    if ((int)$cnt->fetch()['c'] <= 0) exit("Add items first");
    if (empty($d['dispatch_no'])) {
      $no = next_doc_no('DIS', new DateTimeImmutable($d['dispatch_at']));
      $pdo->prepare("UPDATE distributor_dispatches SET dispatch_no=? WHERE id=?")->execute([$no, $dispatch_id]);
    }
    $pdo->prepare("UPDATE distributor_dispatches SET status='SUBMITTED' WHERE id=?")->execute([$dispatch_id]);
    redirect("dispatches.php?action=edit&id=".$dispatch_id);
  }

  if ($op === 'approve') {
    require_role(['ADMIN']);
    $dispatch_id = (int)($_POST['dispatch_id'] ?? 0);
    $d = fetch_dispatch($pdo, $dispatch_id);
    if (!$d) exit("Dispatch not found");
    if ($d['status'] !== 'SUBMITTED') exit("Only SUBMITTED can be approved");
    $pdo->prepare("UPDATE distributor_dispatches SET status='APPROVED', manager_by=?, manager_at=NOW(), manager_reason=NULL WHERE id=?")->execute([(int)$me['id'], $dispatch_id]);
    redirect("dispatches.php?action=edit&id=".$dispatch_id);
  }

  if ($op === 'reject') {
    require_role(['ADMIN']);
    $dispatch_id = (int)($_POST['dispatch_id'] ?? 0);
    $reason      = trim($_POST['reason'] ?? '');
    if ($reason === '') exit("Reason required");
    $d = fetch_dispatch($pdo, $dispatch_id);
    if (!$d) exit("Dispatch not found");
    if ($d['status'] !== 'SUBMITTED') exit("Only SUBMITTED can be rejected");
    $pdo->prepare("UPDATE distributor_dispatches SET status='REJECTED', manager_by=?, manager_at=NOW(), manager_reason=? WHERE id=?")->execute([(int)$me['id'], $reason, $dispatch_id]);
    redirect("dispatches.php?action=edit&id=".$dispatch_id);
  }
}

if ($action === 'edit' && $id > 0) {
  $dispatch     = fetch_dispatch($pdo, $id);
  if (!$dispatch) { http_response_code(404); exit("Not found"); }
  $items        = fetch_dispatch_items($pdo, $id);
  $distributors = fetch_distributors($pdo);
  $issues       = fetch_issues($pdo);
} else {
  $dispatch     = null;
  $items        = [];
  $distributors = [];
  $issues       = [];
  $rows         = $pdo->query("
    SELECT d.id, d.dispatch_no, d.dispatch_at, d.status,
           dist.name AS distributor_name, u.name AS created_by_name
    FROM distributor_dispatches d
    JOIN distributors dist ON dist.id=d.distributor_id
    JOIN users u ON u.id=d.created_by
    ORDER BY d.id DESC
    LIMIT 200
  ")->fetchAll();
}

/* ── ترجمة الحالة ── */
function dis_status_ar(string $s): array {
  return match($s) {
    'DRAFT'     => ['مسودة',  'badge-draft'],
    'SUBMITTED' => ['مرسلة',  'badge-submitted'],
    'APPROVED'  => ['معتمدة', 'badge-approved'],
    'REJECTED'  => ['مرفوضة','badge-rejected'],
    default     => [$s,        'badge-draft'],
  };
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>صرف للموزعين (DIS) — MGZ</title>
<style>
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
  body {
    font-family: 'Segoe UI', Tahoma, Arial, sans-serif;
    background: #f3f4f6;
    color: #1f2937;
    min-height: 100vh;
  }

  /* Back */
  .back-link {
    display: inline-block;
    padding: 10px 20px;
    color: #6b7280;
    text-decoration: none;
    font-size: .9rem;
    transition: color .2s;
  }
  .back-link:hover { color: #1d4ed8; }

  /* Header */
  .page-header {
    background: linear-gradient(135deg, #1e3a5f 0%, #2563eb 100%);
    color: #fff;
    padding: 22px 32px;
    border-radius: 12px;
    margin: 0 20px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 4px 15px rgba(37,99,235,.35);
  }
  .page-header h1 { font-size: 1.5rem; font-weight: 700; }
  .page-header .subtitle { font-size: .85rem; opacity: .8; margin-top: 4px; }
  .page-header .doc-badge {
    background: rgba(255,255,255,.18);
    border-radius: 8px;
    padding: 6px 18px;
    font-size: .95rem;
    font-weight: 700;
  }

  /* Content */
  .content { padding: 0 20px 40px; }

  /* Meta bar */
  .meta-bar {
    background: #fff;
    border-radius: 10px;
    padding: 16px 24px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,.07);
    display: flex;
    flex-wrap: wrap;
    gap: 28px;
    align-items: center;
  }
  .meta-item { display: flex; flex-direction: column; gap: 3px; }
  .meta-label { font-size: .72rem; color: #9ca3af; text-transform: uppercase; letter-spacing: .6px; }
  .meta-value { font-size: .95rem; font-weight: 600; color: #1e3a5f; }

  /* Alert */
  .alert-danger {
    background: #fef2f2;
    border: 1px solid #fca5a5;
    border-radius: 8px;
    padding: 14px 20px;
    color: #991b1b;
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    align-items: flex-start;
    font-size: .92rem;
  }

  /* Card */
  .card {
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
    margin-bottom: 24px;
    overflow: hidden;
  }
  .card-header {
    padding: 15px 24px;
    border-bottom: 1px solid #e5e7eb;
    font-size: 1rem;
    font-weight: 600;
    color: #1e3a5f;
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .card-body { padding: 24px; }

  /* Form */
  .form-row {
    display: flex;
    align-items: flex-end;
    gap: 14px;
    flex-wrap: wrap;
  }
  .form-row label {
    display: flex;
    flex-direction: column;
    gap: 5px;
    font-size: .82rem;
    color: #374151;
    font-weight: 500;
  }
  .form-row input,
  .form-row select {
    padding: 9px 14px;
    border: 1px solid #d1d5db;
    border-radius: 7px;
    font-size: .92rem;
    font-family: inherit;
    background: #f9fafb;
    color: #1f2937;
    outline: none;
    transition: border-color .2s, box-shadow .2s;
  }
  .form-row input[type="text"]   { width: 230px; }
  .form-row input[type="number"] { width: 110px; }
  .form-row select               { min-width: 200px; }
  .form-row input:focus,
  .form-row select:focus {
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37,99,235,.15);
    background: #fff;
  }
  /* Reject row */
  .reject-row {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
  }
  .reject-row input {
    padding: 9px 14px;
    border: 1px solid #fca5a5;
    border-radius: 7px;
    font-size: .9rem;
    font-family: inherit;
    background: #fff;
    color: #1f2937;
    outline: none;
    width: 260px;
    transition: border-color .2s;
  }
  .reject-row input:focus {
    border-color: #dc2626;
    box-shadow: 0 0 0 3px rgba(220,38,38,.12);
  }

  /* File upload */
  .upload-row {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
  }
  .upload-row input[type="file"] {
    font-size: .88rem;
    color: #374151;
    font-family: inherit;
  }
  .upload-note {
    font-size: .8rem;
    color: #6b7280;
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 6px;
  }

  /* Buttons */
  .btn {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 9px 20px;
    border: none;
    border-radius: 7px;
    font-size: .9rem;
    font-weight: 600;
    cursor: pointer;
    font-family: inherit;
    transition: background .2s, transform .1s;
  }
  .btn:active { transform: scale(.97); }
  .btn-primary   { background: #2563eb; color: #fff; }
  .btn-primary:hover   { background: #1d4ed8; }
  .btn-success   { background: #16a34a; color: #fff; }
  .btn-success:hover   { background: #15803d; }
  .btn-warning   { background: #d97706; color: #fff; }
  .btn-warning:hover   { background: #b45309; }
  .btn-danger    { background: #dc2626; color: #fff; }
  .btn-danger:hover    { background: #b91c1c; }
  .btn-secondary { background: #e5e7eb; color: #374151; }
  .btn-secondary:hover { background: #d1d5db; }

  /* Badges */
  .badge {
    display: inline-block;
    padding: 3px 12px;
    border-radius: 20px;
    font-size: .78rem;
    font-weight: 700;
  }
  .badge-draft     { background: #f3f4f6; color: #6b7280; border: 1px solid #d1d5db; }
  .badge-submitted { background: #dbeafe; color: #1e40af; }
  .badge-approved  { background: #d1fae5; color: #065f46; }
  .badge-rejected  { background: #fee2e2; color: #991b1b; }

  /* Table */
  .table-meta { font-size: .85rem; color: #6b7280; padding: 12px 24px 0; }
  table { width: 100%; border-collapse: collapse; }
  thead th {
    background: #f1f5f9;
    color: #374151;
    font-weight: 600;
    font-size: .875rem;
    padding: 12px 18px;
    text-align: right;
    border-bottom: 2px solid #e5e7eb;
  }
  tbody tr { border-bottom: 1px solid #f3f4f6; transition: background .15s; }
  tbody tr:hover { background: #f8faff; }
  tbody tr:last-child { border-bottom: none; }
  tbody td { padding: 12px 18px; font-size: .9rem; color: #374151; text-align: right; }

  /* Actions bar */
  .actions-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: center;
  }
  .divider { width: 1px; height: 32px; background: #e5e7eb; }

  /* Empty state */
  .empty-state { text-align: center; padding: 40px 20px; color: #9ca3af; }
  .empty-state .icon { font-size: 2.2rem; margin-bottom: 10px; }
  .empty-state p { font-size: .9rem; }

  /* Open link */
  .btn-open {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    color: #2563eb;
    text-decoration: none;
    font-size: .85rem;
    font-weight: 500;
    padding: 4px 12px;
    border-radius: 6px;
    border: 1px solid #bfdbfe;
    background: #eff6ff;
    transition: background .2s;
  }
  .btn-open:hover { background: #dbeafe; }
</style>
</head>
<body>

<a class="back-link" href="../dashboard.php">→ العودة للرئيسية</a>

<?php if ($action === 'edit' && $dispatch):
  [$status_ar, $status_cls] = dis_status_ar($dispatch['status']);
  $editable = in_array($dispatch['status'], ['DRAFT','REJECTED'], true);
?>

<!-- ===== وضع التعديل ===== -->
<div class="page-header">
  <div>
    <h1>🚚 صرف للموزعين — تعديل</h1>
    <div class="subtitle">مراجعة وإدارة أمر الصرف للموزع</div>
  </div>
  <?php if ($dispatch['dispatch_no']): ?>
    <div class="doc-badge"><?= h($dispatch['dispatch_no']) ?></div>
  <?php else: ?>
    <div class="doc-badge" style="opacity:.6;">لم يُولَّد رقم بعد</div>
  <?php endif; ?>
</div>

<div class="content">

  <!-- Meta Bar -->
  <div class="meta-bar">
    <div class="meta-item">
      <span class="meta-label">رقم المستند</span>
      <span class="meta-value"><?= $dispatch['dispatch_no'] ? h($dispatch['dispatch_no']) : '—' ?></span>
    </div>
    <div class="meta-item">
      <span class="meta-label">الموزع</span>
      <span class="meta-value"><?= h($dispatch['distributor_name']) ?></span>
    </div>
    <div class="meta-item">
      <span class="meta-label">تاريخ الصرف</span>
      <span class="meta-value"><?= h($dispatch['dispatch_at']) ?></span>
    </div>
    <div class="meta-item">
      <span class="meta-label">أنشئ بواسطة</span>
      <span class="meta-value"><?= h($dispatch['created_by_name']) ?></span>
    </div>
    <?php if ($dispatch['manager_by_name']): ?>
    <div class="meta-item">
      <span class="meta-label">المدير / التوقيت</span>
      <span class="meta-value"><?= h($dispatch['manager_by_name']) ?> — <?= h($dispatch['manager_at']) ?></span>
    </div>
    <?php endif; ?>
    <div class="meta-item">
      <span class="meta-label">الحالة</span>
      <span class="badge <?= $status_cls ?>"><?= $status_ar ?></span>
    </div>
  </div>

  <!-- تنبيه الرفض -->
  <?php if ($dispatch['manager_reason']): ?>
  <div class="alert-danger">
    <span>⚠️</span>
    <div><strong>سبب الرفض:</strong> <?= h($dispatch['manager_reason']) ?></div>
  </div>
  <?php endif; ?>

  <!-- إضافة صنف -->
  <?php if ($editable): ?>
  <div class="card">
    <div class="card-header">➕ إضافة إصدار</div>
    <div class="card-body">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="add_item">
        <input type="hidden" name="dispatch_id" value="<?= (int)$dispatch['id'] ?>">
        <div class="form-row">
          <label>
            الإصدار
            <select name="issue_id" required>
              <option value="">— اختر الإصدار —</option>
              <?php foreach ($issues as $iss): ?>
                <option value="<?= (int)$iss['id'] ?>"><?= h($iss['label']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <label>
            الكمية
            <input type="number" name="qty" min="1" step="1" placeholder="0" required>
          </label>
          <button type="submit" class="btn btn-primary">✔ إضافة</button>
        </div>
      </form>
    </div>
  </div>
  <?php endif; ?>

  <!-- جدول الأصناف -->
  <div class="card">
    <div class="card-header">📋 الأصناف</div>
    <div class="table-meta"><?= count($items) ?> صنف</div>
    <?php if (empty($items)): ?>
      <div class="empty-state">
        <div class="icon">🚚</div>
        <p>لم يُضَف أي إصدار بعد</p>
      </div>
    <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>الإصدار</th>
          <th>الكمية</th>
          <?php if ($editable): ?><th>حذف</th><?php endif; ?>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($items as $idx => $it): ?>
        <tr>
          <td><?= $idx + 1 ?></td>
          <td><strong><?= h($it['issue_label']) ?></strong></td>
          <td><?= number_format((int)$it['qty']) ?></td>
          <?php if ($editable): ?>
          <td>
            <form method="post" onsubmit="return confirm('هل تريد حذف هذا الصنف؟')">
              <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
              <input type="hidden" name="op" value="remove_item">
              <input type="hidden" name="dispatch_id" value="<?= (int)$dispatch['id'] ?>">
              <input type="hidden" name="item_id" value="<?= (int)$it['id'] ?>">
              <button type="submit" class="btn btn-danger" style="padding:5px 14px;font-size:.82rem;">🗑 حذف</button>
            </form>
          </td>
          <?php endif; ?>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

  <!-- رفع POD -->
  <div class="card">
    <div class="card-header">📎 إيصال التسليم (POD)</div>
    <div class="card-body">
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="upload_pod">
        <input type="hidden" name="dispatch_id" value="<?= (int)$dispatch['id'] ?>">
        <div class="upload-row">
          <input type="file" name="pod" accept=".jpg,.jpeg,.png,.pdf" required>
          <button type="submit" class="btn btn-secondary">📤 رفع الملف</button>
        </div>
        <div class="upload-note">
          ℹ️ إيصال التسليم (POD) يتضمن توقيع وبيانات المستلم لتأكيد التسليم وتقليل النزاعات.
        </div>
      </form>
      <?php if (!empty($dispatch['pod_attachment_id'])): ?>
        <p style="margin-top:12px; color:#16a34a; font-weight:600;">✔ تم رفع إيصال التسليم</p>
      <?php endif; ?>
    </div>
  </div>

  <!-- الإجراءات -->
  <div class="card">
    <div class="card-header">⚙️ الإجراءات</div>
    <div class="card-body">
      <div class="actions-bar">

        <?php if ($editable): ?>
        <form method="post" onsubmit="return confirm('إرسال أمر الصرف للمراجعة؟')">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="submit">
          <input type="hidden" name="dispatch_id" value="<?= (int)$dispatch['id'] ?>">
          <button type="submit" class="btn btn-warning">📤 إرسال للمراجعة</button>
        </form>
        <?php endif; ?>

        <?php if ($me['role'] === 'ADMIN' && $dispatch['status'] === 'SUBMITTED'): ?>
        <form method="post" onsubmit="return confirm('اعتماد أمر الصرف؟')">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="approve">
          <input type="hidden" name="dispatch_id" value="<?= (int)$dispatch['id'] ?>">
          <button type="submit" class="btn btn-success">✔ اعتماد</button>
        </form>

        <div class="divider"></div>

        <form method="post" class="reject-row">
          <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="reject">
          <input type="hidden" name="dispatch_id" value="<?= (int)$dispatch['id'] ?>">
          <input type="text" name="reason" placeholder="
              سبب الرفض..." required>
          <button type="submit" class="btn btn-danger">✖ رفض</button>
        </form>
        <?php endif; ?>

        <?php if ($dispatch['status'] === 'APPROVED'): ?>
          <span style="color:#16a34a; font-weight:600; display:flex; align-items:center; gap:6px;">
            ✔ تم اعتماد أمر الصرف بشكل نهائي
          </span>
        <?php endif; ?>

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

</div><!-- /content edit -->

<?php else: /* ========== قائمة أوامر الصرف ========== */ ?>

<div class="page-header">
  <div>
    <h1>🚚 صرف للموزعين (DIS)</h1>
    <div class="subtitle">أوامر صرف المجلات للموزعين</div>
  </div>
  <div style="font-size:2rem; opacity:.2;">🚚</div>
</div>

<div class="content">

  <!-- إنشاء أمر جديد -->
  <div class="card">
    <div class="card-header">➕ إنشاء أمر صرف جديد</div>
    <div class="card-body">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="create">
        <div class="form-row">
          <label>
            الموزع
            <select name="distributor_id" required>
              <option value="">— اختر الموزع —</option>
              <?php foreach (fetch_distributors($pdo) as $dist): ?>
                <option value="<?= (int)$dist['id'] ?>"><?= h($dist['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </label>
          <label>
            تاريخ الصرف
            <input
              type="text"
              name="dispatch_at"
              value="<?= h(date('Y-m-d H:i:s')) ?>"
              placeholder="YYYY-MM-DD HH:MM:SS"
              required
            >
          </label>
          <button type="submit" class="btn btn-primary">➕ إنشاء</button>
        </div>
      </form>
    </div>
  </div>

  <!-- قائمة الأوامر -->
  <div class="card">
    <div class="card-header">📋 آخر 200 أمر صرف</div>
    <div class="table-meta"><?= count($rows) ?> أمر</div>

    <?php if (empty($rows)): ?>
      <div class="empty-state">
        <div class="icon">🚚</div>
        <p>لا توجد أوامر صرف مسجلة بعد</p>
      </div>
    <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>رقم الأمر</th>
          <th>التاريخ</th>
          <th>الموزع</th>
          <th>الحالة</th>
          <th>أنشئ بواسطة</th>
          <th>فتح</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $idx => $r):
          [$st_ar, $st_cls] = dis_status_ar($r['status']);
        ?>
        <tr>
          <td><?= $idx + 1 ?></td>
          <td>
            <?php if ($r['dispatch_no']): ?>
              <strong><?= h($r['dispatch_no']) ?></strong>
            <?php else: ?>
              <span style="color:#9ca3af; font-style:italic;">لم يُولَّد بعد</span>
            <?php endif; ?>
          </td>
          <td><?= h($r['dispatch_at']) ?></td>
          <td><?= h($r['distributor_name']) ?></td>
          <td><span class="badge <?= $st_cls ?>"><?= $st_ar ?></span></td>
          <td><?= h($r['created_by_name']) ?></td>
          <td>
            <a href="dispatches.php?action=edit&id=<?= (int)$r['id'] ?>" class="btn-open">
              📂 فتح
            </a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

</div><!-- /content list -->

<?php endif; ?>

</body>
</html>
