<?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';

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

/* ═══════════════════════════════════════════
   دوال مساعدة
═══════════════════════════════════════════ */
function fetch_issues(PDO $pdo): array {
    return $pdo->query("
        SELECT i.id,
               CONCAT(
                   p.name, ' — ',
                   LPAD(i.issue_month, 2, '0'), '/', i.issue_year,
                   IF(i.issue_number IS NOT NULL,
                      CONCAT(' (عدد ', i.issue_number, ')'),
                      ''
                   )
               ) AS label
        FROM issues i
        JOIN products p ON p.id = i.product_id
        WHERE i.status = 'OPEN'
        ORDER BY p.name, i.issue_year DESC, i.issue_month DESC
    ")->fetchAll();
}


function fetch_receipt(PDO $pdo, int $id): ?array {
  $st = $pdo->prepare("
    SELECT wr.*,
           u1.name AS created_by_name,
           u2.name AS manager_by_name
    FROM warehouse_receipts wr
    JOIN users u1 ON u1.id = wr.created_by
    LEFT JOIN users u2 ON u2.id = wr.manager_by
    WHERE wr.id = ?
  ");
  $st->execute([$id]);
  $r = $st->fetch();
  return $r ?: null;
}

function fetch_receipt_items(PDO $pdo, int $receiptId): array {
  $st = $pdo->prepare("
    SELECT wri.*,
           CONCAT(p.name, ' — عدد ', i.issue_number) AS issue_label
    FROM warehouse_receipt_items wri
    JOIN issues i ON i.id = wri.issue_id
    JOIN products p ON p.id = i.product_id
    WHERE wri.receipt_id = ?
    ORDER BY p.name, i.issue_number
  ");
  $st->execute([$receiptId]);
  return $st->fetchAll();
}

function whr_status_ar(string $s): array {
  return match($s) {
    'DRAFT'     => ['مسودة',   'badge-draft'],
    'SUBMITTED' => ['مرسلة',   'badge-submitted'],
    'APPROVED'  => ['معتمدة',  'badge-approved'],
    'REJECTED'  => ['مرفوضة', 'badge-rejected'],
    default     => [$s,         'badge-draft'],
  };
}

/* ═══════════════════════════════════════════
   معالجة POST
═══════════════════════════════════════════ */
$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') {
    $received_at = date('Y-m-d H:i:s');
    $st = $pdo->prepare("
      INSERT INTO warehouse_receipts (receipt_no, received_at, created_by, status)
      VALUES (NULL, ?, ?, 'DRAFT')
    ");
    $st->execute([$received_at, (int)$me['id']]);
    $newId = (int)$pdo->lastInsertId();
    redirect("wh_receipts.php?action=edit&id=" . $newId);
  }

  /* ── إضافة صنف ── */
  if ($op === 'add_item') {
    $receipt_id = (int)($_POST['receipt_id'] ?? 0);
    $issue_id   = (int)($_POST['issue_id']   ?? 0);
    $qty        = (int)($_POST['qty']         ?? 0);
    if ($receipt_id <= 0 || $issue_id <= 0 || $qty <= 0) exit("Bad item");
    $r = fetch_receipt($pdo, $receipt_id);
    if (!$r) exit("Receipt not found");
    if (!in_array($r['status'], ['DRAFT','REJECTED'], true)) exit("Cannot edit in this status");
    $st = $pdo->prepare("
      INSERT INTO warehouse_receipt_items (receipt_id, issue_id, qty)
      VALUES (?,?,?)
      ON DUPLICATE KEY UPDATE qty = qty + VALUES(qty)
    ");
    $st->execute([$receipt_id, $issue_id, $qty]);
    redirect("wh_receipts.php?action=edit&id=" . $receipt_id);
  }

  /* ── حذف صنف ── */
  if ($op === 'remove_item') {
    $receipt_id = (int)($_POST['receipt_id'] ?? 0);
    $item_id    = (int)($_POST['item_id']    ?? 0);
    $r = fetch_receipt($pdo, $receipt_id);
    if (!$r) exit("Receipt not found");
    if (!in_array($r['status'], ['DRAFT','REJECTED'], true)) exit("Cannot edit in this status");
    $pdo->prepare("DELETE FROM warehouse_receipt_items WHERE id=? AND receipt_id=?")
        ->execute([$item_id, $receipt_id]);
    redirect("wh_receipts.php?action=edit&id=" . $receipt_id);
  }

  /* ── حذف إيصال DRAFT فردي ── */
  if ($op === 'delete_receipt') {
    require_role(['ADMIN','WAREHOUSE']);
    $receipt_id = (int)($_POST['receipt_id'] ?? 0);
    $r = fetch_receipt($pdo, $receipt_id);
    if (!$r) exit("Receipt not found");
    if ($r['status'] !== 'DRAFT') exit("Only DRAFT can be deleted");
    $pdo->prepare("DELETE FROM warehouse_receipt_items WHERE receipt_id=?")->execute([$receipt_id]);
    $pdo->prepare("DELETE FROM warehouse_receipts WHERE id=? AND status='DRAFT'")->execute([$receipt_id]);
    redirect("wh_receipts.php");
  }

  /* ── حذف إيصالات DRAFT محددة (bulk) ── */
  if ($op === 'delete_bulk') {
    require_role(['ADMIN','WAREHOUSE']);
    $ids_raw = $_POST['selected_ids'] ?? '';
    $ids = array_filter(array_map('intval', explode(',', $ids_raw)));
    if (!empty($ids)) {
      $placeholders = implode(',', array_fill(0, count($ids), '?'));
      $pdo->prepare("DELETE FROM warehouse_receipt_items WHERE receipt_id IN ($placeholders)")
          ->execute($ids);
      $pdo->prepare("DELETE FROM warehouse_receipts WHERE id IN ($placeholders) AND status='DRAFT'")
          ->execute($ids);
    }
    redirect("wh_receipts.php");
  }

  /* ── رفع صورة ── */
  if ($op === 'upload_image') {
    $receipt_id = (int)($_POST['receipt_id'] ?? 0);
    $r = fetch_receipt($pdo, $receipt_id);
    if (!$r) exit(json_encode(['ok'=>false,'msg'=>'Receipt not found']));

    $allowed_mime = ['image/jpeg','image/png','image/gif','image/webp',
                     'image/bmp','image/svg+xml','image/tiff'];
    $file = $_FILES['receipt_image'] ?? null;

    if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
      echo json_encode(['ok'=>false,'msg'=>'فشل الرفع، حاول مرة أخرى.']);
      exit;
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($mime, $allowed_mime, true)) {
      echo json_encode(['ok'=>false,'msg'=>'نوع الملف غير مدعوم. الأنواع المقبولة: JPG, PNG, GIF, WEBP, BMP, SVG, TIFF']);
      exit;
    }

    $ext      = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'whr_' . $receipt_id . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    $dest_dir = __DIR__ . '/../../uploads/whr/';
    if (!is_dir($dest_dir)) mkdir($dest_dir, 0755, true);
    $dest = $dest_dir . $filename;

    if (!move_uploaded_file($file['tmp_name'], $dest)) {
      echo json_encode(['ok'=>false,'msg'=>'تعذّر حفظ الملف على السيرفر.']);
      exit;
    }

    $url = '../uploads/whr/' . $filename;
    /* اختياري: تخزين مسار الصورة في قاعدة البيانات لو عندك عمود image_path */
    // $pdo->prepare("UPDATE warehouse_receipts SET image_path=? WHERE id=?")
    //     ->execute([$url, $receipt_id]);

    echo json_encode(['ok'=>true,'url'=>$url,'filename'=>$filename]);
    exit;
  }

  /* ── إرسال للمراجعة ── */
  if ($op === 'submit') {
    $receipt_id = (int)($_POST['receipt_id'] ?? 0);
    $r = fetch_receipt($pdo, $receipt_id);
    if (!$r) exit("Receipt not found");
    if (!in_array($r['status'], ['DRAFT','REJECTED'], true)) exit("Bad status");
    $cnt = $pdo->prepare("SELECT COUNT(*) c FROM warehouse_receipt_items WHERE receipt_id=?");
    $cnt->execute([$receipt_id]);
    if ((int)$cnt->fetch()['c'] <= 0) exit("Add items first");
    if (empty($r['receipt_no'])) {
      $no = next_doc_no($pdo, 'WHR', isset($r['received_at']) ? (new DateTimeImmutable($r['received_at']))->format('Y-m-d') : null);
      $pdo->prepare("UPDATE warehouse_receipts SET receipt_no=? WHERE id=?")->execute([$no, $receipt_id]);
    }
    $pdo->prepare("UPDATE warehouse_receipts SET status='SUBMITTED' WHERE id=?")->execute([$receipt_id]);
    redirect("wh_receipts.php?action=edit&id=" . $receipt_id);
  }

  /* ── اعتماد ── */
  if ($op === 'approve') {
    require_role(['ADMIN']);
    $receipt_id = (int)($_POST['receipt_id'] ?? 0);
    $r = fetch_receipt($pdo, $receipt_id);
    if (!$r) exit("Receipt not found");
    if ($r['status'] !== 'SUBMITTED') exit("Only SUBMITTED can be approved");
    $pdo->prepare("
      UPDATE warehouse_receipts
      SET status='APPROVED', manager_by=?, manager_at=NOW(), manager_reason=NULL
      WHERE id=?
    ")->execute([(int)$me['id'], $receipt_id]);
    redirect("wh_receipts.php?action=edit&id=" . $receipt_id);
  }

  /* ── رفض ── */
  if ($op === 'reject') {
    require_role(['ADMIN']);
    $receipt_id = (int)($_POST['receipt_id'] ?? 0);
    $reason     = trim($_POST['reason'] ?? '');
    if ($reason === '') exit("Reason required");
    $r = fetch_receipt($pdo, $receipt_id);
    if (!$r) exit("Receipt not found");
    if ($r['status'] !== 'SUBMITTED') exit("Only SUBMITTED can be rejected");
    $pdo->prepare("
      UPDATE warehouse_receipts
      SET status='REJECTED', manager_by=?, manager_at=NOW(), manager_reason=?
      WHERE id=?
    ")->execute([(int)$me['id'], $reason, $receipt_id]);
    redirect("wh_receipts.php?action=edit&id=" . $receipt_id);
  }
}

/* ═══════════════════════════════════════════
   جلب البيانات
═══════════════════════════════════════════ */
if ($action === 'edit' && $id > 0) {
  $receipt = fetch_receipt($pdo, $id);
  if (!$receipt) { http_response_code(404); exit("Not found"); }
  $items  = fetch_receipt_items($pdo, $id);
  $issues = fetch_issues($pdo);
} else {
  $receipt = null; $items = []; $issues = [];
  /* أحدث 50 أولاً — الباقي يُحمَّل عبر AJAX */
  $offset = (int)($_GET['offset'] ?? 0);
  $limit  = 50;
  $rows = $pdo->prepare("
    SELECT wr.id, wr.receipt_no, wr.received_at, wr.status, u.name AS created_by_name
    FROM warehouse_receipts wr
    JOIN users u ON u.id = wr.created_by
    ORDER BY wr.id DESC
    LIMIT $limit OFFSET $offset
  ");
  $rows->execute();
  $rows = $rows->fetchAll();

  /* لو طلب AJAX يرجع JSON فقط */
  if (isset($_GET['ajax'])) {
    $out = [];
    foreach ($rows as $r) {
      [$st_ar, $st_cls] = whr_status_ar($r['status']);
      $del_btn = ($r['status'] === 'DRAFT')
        ? '<button class="btn-del-single btn-icon" data-id="'.h($r['id']).'">🗑</button>'
        : '<span style="color:#d1d5db;">—</span>';
      $chk = ($r['status'] === 'DRAFT')
        ? '<input type="checkbox" class="row-check" value="'.h($r['id']).'">'
        : '';

      $out[] = [
        'id'   => $r['id'],
        'html' => '
          <tr data-id="'.h($r['id']).'">
            <td>'.$chk.'</td>
            <td>'.($r['receipt_no'] ? '<strong>'.h($r['receipt_no']).'</strong>' : '<span style="color:#9ca3af;font-style:italic;">لم يُولَّد بعد</span>').'</td>
            <td>'.h($r['received_at']).'</td>
            <td><span class="badge '.$st_cls.'">'.$st_ar.'</span></td>
            <td>'.h($r['created_by_name']).'</td>
            <td>
              <a href="wh_receipts.php?action=edit&id='.h($r['id']).'" class="btn-open">📂 فتح</a>
            </td>
            <td>'.$del_btn.'</td>
          </tr>',
      ];
    }
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['rows' => $out, 'has_more' => count($rows) === $limit]);
    exit;
  }
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>توريد للمخزن (WHR) — 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-link {
    display: inline-block; padding: 10px 20px;
    color: #6b7280; text-decoration: none; font-size: .9rem;
  }
  .back-link:hover { color: #1d4ed8; }

  .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 { padding: 0 20px 40px; }

  .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; }
  .meta-value { font-size: .95rem; font-weight: 600; color: #1e3a5f; }

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

  .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-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="number"] { width: 110px; }
  .form-row select { min-width: 260px; }
  .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 { 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; width: 260px;
  }

  .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: opacity .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; }

  /* زر الحذف الصغير في الجدول */
  .btn-icon {
    background: none; border: none; cursor: pointer;
    font-size: 1.1rem; padding: 4px 8px; border-radius: 6px;
    transition: background .15s;
  }
  .btn-icon:hover { background: #fee2e2; }

  /* زر فتح */
  .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; }

  .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 { 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 {
    display: flex; flex-wrap: wrap; gap: 12px; align-items: center;
  }
  .divider { width: 1px; height: 32px; background: #e5e7eb; }

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

  /* شريط التحكم بالحذف الجماعي */
  .bulk-bar {
    display: none; align-items: center; gap: 12px;
    background: #fef9c3; border: 1px solid #fde047;
    border-radius: 8px; padding: 10px 18px; margin-bottom: 14px;
    font-size: .9rem; font-weight: 600; color: #713f12;
  }
  .bulk-bar.visible { display: flex; }

  /* شريط تحميل المزيد */
  #load-more-bar {
    text-align: center; padding: 16px;
    display: none;
  }
  #load-more-bar.visible { display: block; }

  /* ═══ رفع الصورة ═══ */
  .upload-area {
    border: 2px dashed #93c5fd; border-radius: 10px;
    padding: 28px; text-align: center; cursor: pointer;
    background: #eff6ff; transition: background .2s, border-color .2s;
    position: relative;
  }
  .upload-area:hover, .upload-area.dragover {
    background: #dbeafe; border-color: #2563eb;
  }
  .upload-area input[type="file"] {
    position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%;
  }
  .upload-area .upload-icon { font-size: 2.5rem; margin-bottom: 8px; }
  .upload-area p { font-size: .9rem; color: #2563eb; font-weight: 500; }
  .upload-area small { color: #6b7280; font-size: .78rem; }

  /* شريط التقدم */
  .progress-wrap {
    display: none; margin-top: 14px;
    background: #e5e7eb; border-radius: 20px;
    height: 14px; overflow: hidden;
  }
  .progress-wrap.visible { display: block; }
  .progress-bar {
    height: 100%; background: linear-gradient(90deg, #2563eb, #60a5fa);
    border-radius: 20px; width: 0%;
    transition: width .2s;
  }
  .progress-label {
    text-align: center; font-size: .78rem; color: #374151;
    margin-top: 6px; font-weight: 600;
  }

  /* معرض الصور */
  .img-gallery {
    display: flex; flex-wrap: wrap; gap: 12px; margin-top: 16px;
  }
  .img-thumb {
    position: relative; width: 110px; height: 110px;
    border-radius: 8px; overflow: hidden;
    border: 2px solid #e5e7eb;
    box-shadow: 0 2px 6px rgba(0,0,0,.1);
  }
  .img-thumb img {
    width: 100%; height: 100%; object-fit: cover; display: block;
  }
  .img-thumb a.fullscreen {
    position: absolute; inset: 0; display: flex;
    align-items: center; justify-content: center;
    background: rgba(0,0,0,.35); opacity: 0;
    color: #fff; font-size: 1.4rem; text-decoration: none;
    transition: opacity .2s;
  }
  .img-thumb:hover a.fullscreen { opacity: 1; }

  .upload-status {
    margin-top: 10px; font-size: .88rem; font-weight: 600;
    display: none;
  }
  .upload-status.ok  { color: #16a34a; display: block; }
  .upload-status.err { color: #dc2626; display: block; }
</style>
</head>
<body>

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

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

<!-- ════════════════ وضع التعديل ════════════════ -->
<div class="page-header">
  <div>
    <h1>📦 توريد للمخزن — تعديل</h1>
    <div class="subtitle">مراجعة وإدارة إيصال الاستلام</div>
  </div>

  <?php if ($receipt['receipt_no']): ?>
    <div class="doc-badge"><?= h($receipt['receipt_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"><?= $receipt['receipt_no'] ? h($receipt['receipt_no']) : '—' ?></span>
    </div>
    <div class="meta-item">
      <span class="meta-label">تاريخ الاستلام</span>
      <span class="meta-value"><?= h($receipt['received_at']) ?></span>
    </div>
    <div class="meta-item">
      <span class="meta-label">أنشئ بواسطة</span>
      <span class="meta-value"><?= h($receipt['created_by_name']) ?></span>
    </div>
    <?php if ($receipt['manager_by_name']): ?>
    <div class="meta-item">
      <span class="meta-label">المدير / التوقيت</span>
      <span class="meta-value"><?= h($receipt['manager_by_name']) ?> — <?= h($receipt['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 ($receipt['manager_reason']): ?>
  <div class="alert-danger">
    <span>⚠️</span>
    <div><strong>سبب الرفض:</strong> <?= h($receipt['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_token" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="add_item">
        <input type="hidden" name="receipt_id" value="<?= (int)$receipt['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 style="padding:8px 24px 0; font-size:.85rem; color:#6b7280;"><?= 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_token" value="<?= h($csrf) ?>">
              <input type="hidden" name="op" value="remove_item">
              <input type="hidden" name="receipt_id" value="<?= (int)$receipt['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>

  <!-- رفع صورة -->
  <div class="card">
    <div class="card-header">🖼️ رفع صورة للإيصال</div>
    <div class="card-body">
      <div class="upload-area" id="uploadArea">
        <input type="file" id="imageInput" accept="image/*">
        <div class="upload-icon">📤</div>
        <p>اسحب وأفلت الصورة هنا أو اضغط للاختيار</p>
        <small>الأنواع المقبولة: JPG, PNG, GIF, WEBP, BMP, SVG, TIFF</small>
      </div>
      <div class="progress-wrap" id="progressWrap">
        <div class="progress-bar" id="progressBar"></div>
      </div>
      <div class="progress-label" id="progressLabel"></div>
      <div class="upload-status" id="uploadStatus"></div>
      <div class="img-gallery" id="imgGallery"></div>
    </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_token" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="submit">
          <input type="hidden" name="receipt_id" value="<?= (int)$receipt['id'] ?>">
          <button type="submit" class="btn btn-warning">📤 إرسال للمراجعة</button>
        </form>
        <?php endif; ?>

        <?php if ($me['role'] === 'ADMIN' && $receipt['status'] === 'SUBMITTED'): ?>
        <form method="post" onsubmit="return confirm('اعتماد هذا الإيصال؟')">
          <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="approve">
          <input type="hidden" name="receipt_id" value="<?= (int)$receipt['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_token" value="<?= h($csrf) ?>">
          <input type="hidden" name="op" value="reject">
          <input type="hidden" name="receipt_id" value="<?= (int)$receipt['id'] ?>">
          <input type="text" name="reason" placeholder="سبب الرفض..." required>
          <button type="submit" class="btn btn-danger">✖ رفض</button>
        </form>
        <?php endif; ?>

        <?php if ($receipt['status'] === 'APPROVED'): ?>
          <span style="color:#16a34a;font-weight:600;">✔ تم اعتماد هذا الإيصال بشكل نهائي</span>
        <?php endif; ?>

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

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

<!-- JavaScript رفع الصورة -->
<script>
(function(){
  const area      = document.getElementById('uploadArea');
  const input     = document.getElementById('imageInput');
  const progWrap  = document.getElementById('progressWrap');
  const progBar   = document.getElementById('progressBar');
  const progLabel = document.getElementById('progressLabel');
  const status    = document.getElementById('uploadStatus');
  const gallery   = document.getElementById('imgGallery');
  const receiptId = <?= (int)$receipt['id'] ?>;
  const csrfToken = <?= json_encode($csrf) ?>;

  ['dragover','dragleave','drop'].forEach(ev => area.addEventListener(ev, e => e.preventDefault()));
  area.addEventListener('dragover', () => area.classList.add('dragover'));
  area.addEventListener('dragleave', () => area.classList.remove('dragover'));
  area.addEventListener('drop', e => {
    area.classList.remove('dragover');
    if (e.dataTransfer.files[0]) uploadFile(e.dataTransfer.files[0]);
  });
  input.addEventListener('change', () => { if (input.files[0]) uploadFile(input.files[0]); });

  function uploadFile(file) {
    const fd = new FormData();
    fd.append('op', 'upload_image');
    fd.append('csrf_token', csrfToken);
    fd.append('receipt_id', receiptId);
    fd.append('receipt_image', file);

    progWrap.classList.add('visible');
    progBar.style.width = '0%';
    progLabel.textContent = '0%';
    status.className = 'upload-status';
    status.textContent = '';

    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'wh_receipts.php');

    xhr.upload.addEventListener('progress', e => {
      if (e.lengthComputable) {
        const pct = Math.round((e.loaded / e.total) * 100);
        progBar.style.width = pct + '%';
        progLabel.textContent = pct + '%';
      }
    });

    xhr.addEventListener('load', () => {
      progBar.style.width = '100%';
      progLabel.textContent = '100%';
      try {
        const res = JSON.parse(xhr.responseText);
        if (res.ok) {
          status.className = 'upload-status ok';
          status.textContent = '✔ تم رفع الصورة بنجاح: ' + res.filename;
          // إضافة الصورة للمعرض
          const thumb = document.createElement('div');
          thumb.className = 'img-thumb';
          thumb.innerHTML = `
            <img src="${res.url}" alt="صورة الإيصال">
            <a class="fullscreen" href="${res.url}" target="_blank">🔍</a>
          `;
          gallery.appendChild(thumb);
        } else {
          status.className = 'upload-status err';
          status.textContent = '✖ ' + res.msg;
        }
      } catch(e) {
        status.className = 'upload-status err';
        status.textContent = '✖ خطأ غير متوقع أثناء الرفع.';
      }
      setTimeout(() => {
        progWrap.classList.remove('visible');
        progLabel.textContent = '';
      }, 2000);
    });

    xhr.addEventListener('error', () => {
      status.className = 'upload-status err';
      status.textContent = '✖ فشل الاتصال بالسيرفر.';
      progWrap.classList.remove('visible');
    });

    xhr.send(fd);
  }
})();
</script>

<?php else: /* ════════════════ قائمة الإيصالات ════════════════ */ ?>

<div class="page-header">
  <div>
    <h1>📦 توريد للمخزن (WHR)</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_token" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="create">
        <button type="submit" class="btn btn-primary">➕ إنشاء إيصال جديد</button>
        <span style="font-size:.82rem;color:#6b7280;margin-right:12px;">
          سيُسجَّل التاريخ والوقت تلقائياً عند الإنشاء
        </span>
      </form>
    </div>
  </div>

  <!-- شريط الحذف الجماعي -->
  <div class="bulk-bar" id="bulkBar">
    <span id="selectedCount">0</span> إيصال محدد (مسودات فقط)
    <button class="btn btn-danger" id="btnDeleteBulk" style="padding:6px 16px;font-size:.85rem;">
      🗑 حذف المحدد
    </button>
    <button class="btn btn-secondary" id="btnClearSel" style="padding:6px 14px;font-size:.85rem;">
      ✖ إلغاء التحديد
    </button>
  </div>

  <!-- جدول الإيصالات -->
  <div class="card">
    <div class="card-header">
      📋 آخر الإيصالات
      <span style="font-size:.8rem;color:#9ca3af;font-weight:400;margin-right:auto;">
        مرتبة من الأحدث للأقدم
      </span>
    </div>

    <table>
      <thead>
        <tr>
          <th>
            <input type="checkbox" id="chkAll" title="تحديد كل المسودات">
          </th>
          <th>#</th>
          <th>رقم الإيصال</th>
          <th>تاريخ الاستلام</th>
          <th>الحالة</th>
          <th>أنشئ بواسطة</th>
          <th>فتح</th>
          <th>حذف</th>
        </tr>
      </thead>
      <tbody id="receiptsBody">
        <?php foreach ($rows as $idx => $r):
          [$st_ar, $st_cls] = whr_status_ar($r['status']);
        ?>
        <tr data-id="<?= (int)$r['id'] ?>">
          <td>
            <?php if ($r['status'] === 'DRAFT'): ?>
              <input type="checkbox" class="row-check" value="<?= (int)$r['id'] ?>">
            <?php endif; ?>
          </td>
          <td><?= $idx + 1 ?></td>
          <td>
            <?php if ($r['receipt_no']): ?>
              <strong><?= h($r['receipt_no']) ?></strong>
            <?php else: ?>
              <span style="color:#9ca3af;font-style:italic;">لم يُولَّد بعد</span>
            <?php endif; ?>
          </td>
          <td><?= h($r['received_at']) ?></td>
          <td><span class="badge <?= $st_cls ?>"><?= $st_ar ?></span></td>
          <td><?= h($r['created_by_name']) ?></td>
          <td>
            <a href="wh_receipts.php?action=edit&id=<?= (int)$r['id'] ?>" class="btn-open">📂 فتح</a>
          </td>
          <td>
            <?php if ($r['status'] === 'DRAFT'): ?>
              <button class="btn-del-single btn-icon"
                      data-id="<?= (int)$r['id'] ?>"
                      title="حذف هذا الإيصال">🗑</button>
            <?php else: ?>
              <span style="color:#d1d5db;">—</span>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>

    <?php if (empty($rows)): ?>
      <div class="empty-state">
        <div class="icon">📦</div>
        <p>لا توجد إيصالات مسجلة بعد</p>
      </div>
    <?php endif; ?>

    <div id="load-more-bar" class="<?= count($rows) === 50 ? 'visible' : '' ?>">
      <button class="btn btn-secondary" id="btnLoadMore">⬇ تحميل المزيد</button>
    </div>

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

<form method="post" id="deleteForm" style="display:none;">
  <input type="hidden" name="csrf_token" value="<?= h($csrf) ?>">
  <input type="hidden" name="op" id="deleteOp" value="">
  <input type="hidden" name="receipt_id" id="deleteReceiptId" value="">
  <input type="hidden" name="selected_ids" id="deleteSelectedIds" value="">
</form>

<script>
(function(){
  const tbody     = document.getElementById('receiptsBody');
  const chkAll    = document.getElementById('chkAll');
  const bulkBar   = document.getElementById('bulkBar');
  const selCount  = document.getElementById('selectedCount');
  const btnBulk   = document.getElementById('btnDeleteBulk');
  const btnClear  = document.getElementById('btnClearSel');
  const loadBar   = document.getElementById('load-more-bar');
  const btnMore   = document.getElementById('btnLoadMore');
  const delForm   = document.getElementById('deleteForm');
  const csrfToken = <?= json_encode($csrf) ?>;

  let offset    = <?= count($rows) ?>;
  let loading   = false;
  let rowCounter = <?= count($rows) ?>;

  function updateBulkBar() {
    const checked = tbody.querySelectorAll('.row-check:checked');
    selCount.textContent = checked.length;
    bulkBar.classList.toggle('visible', checked.length > 0);
  }

  chkAll.addEventListener('change', function () {
    tbody.querySelectorAll('.row-check').forEach(c => c.checked = this.checked);
    updateBulkBar();
  });

  tbody.addEventListener('change', e => {
    if (!e.target.classList.contains('row-check')) return;
    const all     = tbody.querySelectorAll('.row-check');
    const checked = tbody.querySelectorAll('.row-check:checked');
    chkAll.indeterminate = checked.length > 0 && checked.length < all.length;
    chkAll.checked       = checked.length > 0 && checked.length === all.length;
    updateBulkBar();
  });

  tbody.addEventListener('click', e => {
    const btn = e.target.closest('.btn-del-single');
    if (!btn) return;
    if (!confirm('هل تريد حذف هذا الإيصال (مسودة)؟\nلا يمكن التراجع عن هذه العملية.')) return;
    document.getElementById('deleteOp').value          = 'delete_receipt';
    document.getElementById('deleteReceiptId').value   = btn.dataset.id;
    document.getElementById('deleteSelectedIds').value = '';
    delForm.submit();
  });

  btnBulk.addEventListener('click', () => {
    const ids = [...tbody.querySelectorAll('.row-check:checked')].map(c => c.value);
    if (ids.length === 0) return;
    if (!confirm('هل تريد حذف ' + ids.length + ' إيصال؟\nلا يمكن التراجع.')) return;
    document.getElementById('deleteOp').value          = 'delete_bulk';
    document.getElementById('deleteReceiptId').value   = '';
    document.getElementById('deleteSelectedIds').value = ids.join(',');
    delForm.submit();
  });

  btnClear.addEventListener('click', () => {
    tbody.querySelectorAll('.row-check').forEach(c => c.checked = false);
    chkAll.checked       = false;
    chkAll.indeterminate = false;
    updateBulkBar();
  });

  function loadMore() {
    if (loading) return;
    loading = true;
    btnMore.textContent = '⏳ جارٍ التحميل...';
    btnMore.disabled    = true;

    fetch('wh_receipts.php?ajax=1&offset=' + offset, {
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
      .then(r => r.json())
      .then(data => {
        data.rows.forEach(item => {
          rowCounter++;
          tbody.insertAdjacentHTML('beforeend', item.html);
        });
        offset += data.rows.length;
        loading  = false;
        if (data.has_more) {
          loadBar.classList.add('visible');
          btnMore.textContent = '⬇ تحميل المزيد';
          btnMore.disabled    = false;
        } else {
          loadBar.classList.remove('visible');
          btnMore.textContent = '✔ تم تحميل كل الإيصالات';
        }
      })
      .catch(() => {
        loading = false;
        btnMore.textContent = '⬇ تحميل المزيد';
        btnMore.disabled    = false;
      });
  }

  btnMore.addEventListener('click', loadMore);

  window.addEventListener('scroll', () => {
    if (loading) return;
    if (!loadBar.classList.contains('visible')) return;
    if ((window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 300)) loadMore();
  });

})();
</script>

<?php endif; ?>
</body>
</html>
