<?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';
require_once __DIR__ . '/../app/ledger.php';
require_once __DIR__ . '/../app/notify.php';
require_once __DIR__ . '/../app/audit.php';

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

/* ═══════════════════════════════════════════
   دوال مساعدة
   ═══════════════════════════════════════════ */

function fetch_issues_with_stock(PDO $pdo): array {
    return $pdo->query("
        SELECT
            i.id,
            p.name                                 AS product_name,
            i.issue_month,
            i.issue_year,
            i.issue_number,
            i.title,
            (
              COALESCE((
                  SELECT SUM(wri.qty)
                  FROM warehouse_receipt_items wri
                  JOIN warehouse_receipts wr ON wr.id = wri.receipt_id
                  WHERE wri.issue_id = i.id AND wr.status IN ('APPROVED','SUBMITTED')
              ),0)
              -
              COALESCE((
                  SELECT SUM(ddi.qty)
                  FROM distributor_dispatch_items ddi
                  JOIN distributor_dispatches dd ON dd.id = ddi.dispatch_id
                  WHERE ddi.issue_id = i.id AND dd.status = 'APPROVED'
              ),0)
              +
              COALESCE((
                  SELECT SUM(wrti.qty)
                  FROM warehouse_return_items wrti
                  JOIN warehouse_returns wrt ON wrt.id = wrti.return_id
                  WHERE wrti.issue_id = i.id AND wrt.status = 'APPROVED'
              ),0)
            ) AS warehouse_balance
        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_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'],
    };
}

$csrf          = csrf_token();
$error_message = null;

/* ═══════════════════════════════════════════
   معالجة POST
   ═══════════════════════════════════════════ */

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

    /* إنشاء إيصال جديد + صنف واحد + صورة + إرسال للمراجعة (من المودال) */
    if ($op === 'create_and_submit') {
        $issue_id    = (int)($_POST['issue_id'] ?? 0);
        $qty         = (int)($_POST['qty'] ?? 0);
        $received_at = date('Y-m-d H:i:s');

        if ($issue_id <= 0 || $qty <= 0) {
            $error_message = "برجاء اختيار الإصدار وإدخال كمية صحيحة.";
        } else {
            $st = $pdo->prepare("
                SELECT
                    COALESCE((
                        SELECT SUM(wri.qty)
                        FROM warehouse_receipt_items wri
                        JOIN warehouse_receipts wr ON wr.id = wri.receipt_id
                        WHERE wri.issue_id = ? AND wr.status IN ('APPROVED','SUBMITTED')
                    ),0)
                    -
                    COALESCE((
                        SELECT SUM(ddi.qty)
                        FROM distributor_dispatch_items ddi
                        JOIN distributor_dispatches dd ON dd.id = ddi.dispatch_id
                        WHERE ddi.issue_id = ? AND dd.status = 'APPROVED'
                    ),0)
                    +
                    COALESCE((
                        SELECT SUM(wrti.qty)
                        FROM warehouse_return_items wrti
                        JOIN warehouse_returns wrt ON wrt.id = wrti.return_id
                        WHERE wrti.issue_id = ? AND wrt.status = 'APPROVED'
                    ),0)
                AS warehouse_balance
            ");
            $st->execute([$issue_id, $issue_id, $issue_id]);
            $current_balance = (int)$st->fetchColumn();

            // رفع صورة الإيصال (إلزامية)
            $image_url = save_upload('receipt_image', 'whr');
            if (!$image_url) {
                $error_message = "يجب إرفاق صورة صحيحة للإيصال (صورة أو PDF وبحجم مناسب).";
            } else {
                // 1) إنشاء إيصال بحالة SUBMITTED (مرسل للمراجعة)
                $st = $pdo->prepare("
                    INSERT INTO warehouse_receipts (receipt_no, received_at, created_by, status, image_path)
                    VALUES (NULL, ?, ?, 'SUBMITTED', ?)
                ");
                $st->execute([$received_at, (int)$me['id'], $image_url]);
                $receipt_id = (int)$pdo->lastInsertId();

                // 2) توليد رقم الإيصال
                $no = next_doc_no(
                    $pdo,
                    'WHR',
                    (new DateTimeImmutable($received_at))->format('Y-m-d')
                );
                $pdo->prepare("UPDATE warehouse_receipts SET receipt_no=? WHERE id=?")
                    ->execute([$no, $receipt_id]);

                // 3) إضافة الصنف
                $st = $pdo->prepare("
                    INSERT INTO warehouse_receipt_items (receipt_id, issue_id, qty)
                    VALUES (?,?,?)
                ");
                $st->execute([$receipt_id, $issue_id, $qty]);

                // 4) إشعار الإدارة + Audit
                notify_role($pdo, 'ADMIN', 'توريد مخزن جديد للمراجعة', 'يوجد إيصال توريد جديد بانتظار الاعتماد', 'WH_RECEIPT', $receipt_id, 'modules/wh_receipts.php');
                audit_log($pdo, (int)$me['id'], 'SUBMIT', 'warehouse_receipts', $receipt_id, ['issue_id'=>$issue_id,'qty'=>$qty]);

                header("Location: wh_receipts.php");
                exit;
            }
        }
    }
    /* حذف إيصال 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");
    }

    /* طلب عرض تفاصيل إيصال في المودال (AJAX) */
    if ($op === 'view_receipt') {
        $receipt_id = (int)($_POST['receipt_id'] ?? 0);
        $r    = fetch_receipt($pdo, $receipt_id);
        $items = fetch_receipt_items($pdo, $receipt_id);

        if (!$r) {
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode(['ok'=>false,'msg'=>'Receipt not found']);
            exit;
        }

        [$status_ar, $status_cls] = whr_status_ar($r['status']);
        $can_moderate = ($me['role'] === 'ADMIN' && $r['status'] === 'SUBMITTED');

        ob_start();
        ?>
        <div class="modal-body-inner">
          <div class="meta-bar">
            <div class="meta-item">
              <span class="meta-label">رقم الإيصال</span>
              <span class="meta-value"><?= $r['receipt_no'] ? h($r['receipt_no']) : '—' ?></span>
            </div>
            <div class="meta-item">
              <span class="meta-label">تاريخ الاستلام</span>
              <span class="meta-value"><?= h($r['received_at']) ?></span>
            </div>
            <div class="meta-item">
              <span class="meta-label">أنشئ بواسطة</span>
              <span class="meta-value"><?= h($r['created_by_name']) ?></span>
            </div>
            <?php if ($r['manager_by_name']): ?>
            <div class="meta-item">
              <span class="meta-label">المدير / التوقيت</span>
              <span class="meta-value">
                <?= h($r['manager_by_name']) ?> — <?= h($r['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 (!empty($r['manager_reason'])): ?>
          <div class="alert-danger">
            <span>⚠️</span>
            <div><strong>سبب الرفض:</strong> <?= h($r['manager_reason']) ?></div>
          </div>
          <?php endif; ?>

          <div class="card">
            <div class="card-header">🧾 صورة إيصال الدفع</div>
            <div class="card-body">
              <?php if (!empty($r['image_path'])): ?>
                <a href="<?= h($r['image_path']) ?>" target="_blank" style="display:inline-block;margin-bottom:10px;">
                  <img src="<?= h($r['image_path']) ?>" alt="صورة إيصال الدفع" class="receipt-img">
                </a>
                <div style="font-size:.8rem;color:#6b7280;">اضغط على الصورة لفتحها في نافذة جديدة.</div>
              <?php else: ?>
                <p style="color:#b91c1c;font-weight:600;">⚠ لا توجد صورة إيصال مرفوعة لهذا المستند.</p>
              <?php endif; ?>
            </div>
          </div>

          <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>
                </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>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
            <?php endif; ?>
          </div>

          <?php if ($can_moderate): ?>
          <div class="card">
            <div class="card-header">⚙️ إجراءات الإدارة</div>
            <div class="card-body">
              <div class="actions-bar">
                <form method="post" onsubmit="return confirm('اعتماد هذا الإيصال وتسجيله في رصيد المخزون؟');">
                  <input type="hidden" name="csrf" value="<?= h($GLOBALS['csrf']) ?>">
                  <input type="hidden" name="op" value="approve_receipt">
                  <input type="hidden" name="receipt_id" value="<?= (int)$r['id'] ?>">
                  <button type="submit" class="btn btn-success">✔ اعتماد الإيصال</button>
                </form>

                <form method="post" class="reject-row">
                  <input type="hidden" name="csrf" value="<?= h($GLOBALS['csrf']) ?>">
                  <input type="hidden" name="op" value="reject_receipt">
                  <input type="hidden" name="receipt_id" value="<?= (int)$r['id'] ?>">
                  <input type="text" name="reason" placeholder="سبب الرفض..." required>
                  <button type="submit" class="btn btn-danger">✖ رفض</button>
                </form>
              </div>
            </div>
          </div>
          <?php endif; ?>
        </div>
        <?php
        $html = ob_get_clean();
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['ok'=>true,'html'=>$html]);
        exit;
    }

    /* اعتماد من داخل نفس الصفحة */
    if ($op === 'approve_receipt') {
        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");
        if (empty($r['image_path'])) exit("يجب أن يحتوي الإيصال على صورة دفع قبل الاعتماد.");

        // Post to ledger (WAREHOUSE qty_in) - idempotent per (receipt, issue)
        $items = fetch_receipt_items($pdo, $receipt_id);
        $chk = $pdo->prepare("SELECT 1 FROM inventory_ledger WHERE ref_type='WH_RECEIPT' AND ref_id=? AND issue_id=? AND entity_type='WAREHOUSE' AND entity_id IS NULL AND status='POSTED' LIMIT 1");
        foreach ($items as $it) {
            $issueId = (int)$it['issue_id'];
            $qty     = (int)$it['qty'];
            if ($issueId <= 0 || $qty <= 0) continue;
            $chk->execute([$receipt_id, $issueId]);
            if (!$chk->fetchColumn()) {
                ledger_post($pdo, 'WAREHOUSE', null, $issueId, $qty, 0, 'WH_RECEIPT', $receipt_id, (int)$me['id'], 'Warehouse receipt 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]);

        // Notify creator + audit
        notify_user($pdo, (int)$r['created_by'], 'تم اعتماد توريد المخزن', 'تم اعتماد إيصال توريد المخزن.', 'WH_RECEIPT', $receipt_id, 'modules/wh_receipts.php');
        audit_log($pdo, (int)$me['id'], 'APPROVE', 'warehouse_receipts', $receipt_id, ['status'=>'APPROVED']);

        redirect("wh_receipts.php");
    }

    /* رفض من داخل نفس الصفحة */
    if ($op === 'reject_receipt') {
        require_role(['ADMIN']);
        $receipt_id = (int)($_POST['receipt_id'] ?? 0);
        $reason = trim($_POST['reason'] ?? '');
        if ($reason === '') exit("سبب الرفض مطلوب");

        $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]);

        // Notify creator + audit
        notify_user($pdo, (int)$r['created_by'], 'تم رفض توريد المخزن', $reason, 'WH_RECEIPT', $receipt_id, 'modules/wh_receipts.php');
        audit_log($pdo, (int)$me['id'], 'REJECT', 'warehouse_receipts', $receipt_id, ['status'=>'REJECTED','reason'=>$reason]);

        redirect("wh_receipts.php");
    }
}

/* ═══════════════════════════════════════════
   جلب بيانات جدول آخر الإيصالات + الأصناف
   ═══════════════════════════════════════════ */

$rows = $pdo->query("
    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 200
")->fetchAll();

/* جلب الأصناف لكل إيصال (اسم إصدار + كمية) */
$receipt_ids = array_column($rows, 'id');
$items_by_receipt = [];
if (!empty($receipt_ids)) {
    $placeholders = implode(',', array_fill(0, count($receipt_ids), '?'));
    $st = $pdo->prepare("
        SELECT
            wri.receipt_id,
            wri.qty,
            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 IN ($placeholders)
        ORDER BY p.name, i.issue_number
    ");
    $st->execute($receipt_ids);
    while ($r = $st->fetch()) {
        $items_by_receipt[$r['receipt_id']][] = $r;
    }
}

$issues_with_stock = fetch_issues_with_stock($pdo);
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>توريد للمخزن (WHR) — 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">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: 'Tajawal', 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; }

.content { padding: 0 20px 40px; }

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

.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-danger    { background: #dc2626; color: #fff; }
.btn-danger:hover    { background: #b91c1c; }

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

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

.alert-danger {
    background: #fef2f2;
    border: 1px solid #fca5a5;
    border-radius: 8px;
    padding: 10px 15px;
    color: #991b1b;
    margin-bottom: 15px;
    font-size: 0.9rem;
    position: relative;
}

.receipt-img {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    border:1px solid #e5e7eb;
}

/* مودال الإنشاء + مودال العرض */
#receiptModal,
#viewModal {
    position:fixed; inset:0;
    background:rgba(0,0,0,.45);
    display:none;
    align-items:center;
    justify-content:center;
    z-index:9999;
}
.modal-box {
    background:#fff;
    width:95%;
    max-width:500px;
    max-height:90vh;
    overflow:auto;
    border-radius:12px;
    box-shadow:0 10px 30px rgba(15,23,42,.4);
    padding:18px 18px 20px;
}
.modal-header {
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:10px;
}
.modal-title {
    font-size:1rem;
    font-weight:700;
    margin:0;
}
.modal-close {
    border:none;
    background:transparent;
    font-size:1.4rem;
    cursor:pointer;
}
.meta-bar {
    background:#fff;
    border-radius:10px;
    padding:16px 16px;
    margin-bottom:15px;
    box-shadow:0 1px 4px rgba(0,0,0,.06);
    display:flex;
    flex-wrap:wrap;
    gap:16px;
    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:.9rem;font-weight:600;color:#1e3a5f; }

.actions-bar {
    display:flex;
    flex-wrap:wrap;
    gap:12px;
    align-items:center;
}
.reject-row {
    display:flex;
    flex-wrap:wrap;
    gap:10px;
    align-items:center;
}
.reject-row input {
    padding: 9px 14px;
    border: 1px solid #fca5a5;
    border-radius: 7px;
    font-size: .9rem;
    font-family: inherit;
    width: 220px;
}
.reject-row input:focus { outline:none;border-color:#dc2626; }

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

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

<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">

  <?php if ($error_message): ?>
    <div class="alert-danger">
      <span><?= $error_message ?></span>
      <span onclick="this.parentElement.style.display='none';"
            style="position:absolute;left:10px;top:5px;cursor:pointer;font-weight:bold;">
        ×
      </span>
    </div>
  <?php endif; ?>

  <!-- زر إنشاء إيصال جديد -->
  <div class="card">
    <div class="card-header">➕ إنشاء إيصال توريد جديد</div>
    <div class="card-body">
      <button type="button" class="btn btn-primary" onclick="openReceiptModal()">
        ➕ إنشاء إيصال
      </button>
    </div>
  </div>

  <!-- جدول آخر الإيصالات مع عمودين للإصدار والكمية + عمود فتح -->
  <div class="card">
    <div class="card-header">📋 آخر الإيصالات</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>
          <th>فتح</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $idx => $r):
          [$st_ar, $st_cls] = whr_status_ar($r['status']);
          $items = $items_by_receipt[$r['id']] ?? [];
          if (empty($items)) {
              $items = [[
                  'issue_label' => 'لا توجد أصناف',
                  'qty'         => '',
              ]];
          }
          $rowspan = count($items);
        ?>
        <?php foreach ($items as $i_idx => $it): ?>
        <tr>
          <?php if ($i_idx === 0): ?>
            <td rowspan="<?= $rowspan ?>"><?= $idx + 1 ?></td>
            <td rowspan="<?= $rowspan ?>">
              <?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 rowspan="<?= $rowspan ?>"><?= h($r['received_at']) ?></td>
            <td rowspan="<?= $rowspan ?>"><span class="badge <?= $st_cls ?>"><?= $st_ar ?></span></td>
            <td rowspan="<?= $rowspan ?>"><?= h($r['created_by_name']) ?></td>
          <?php endif; ?>
          <td><?= h($it['issue_label']) ?></td>
          <td><?= $it['qty'] !== '' ? (int)$it['qty'] : '' ?></td>
          <?php if ($i_idx === 0): ?>
          <td rowspan="<?= $rowspan ?>">
            <button type="button" class="btn-open" onclick="openViewModal(<?= (int)$r['id'] ?>)">
              📂 فتح
            </button>
          </td>
          <?php endif; ?>
        </tr>
        <?php endforeach; ?>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>

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

<!-- مودال إنشاء إيصال توريد -->
<div id="receiptModal">
  <div class="modal-box">
    <div class="modal-header">
      <h2 class="modal-title">إنشاء إيصال توريد جديد</h2>
      <button type="button" class="modal-close" onclick="closeReceiptModal()">×</button>
    </div>

    <form method="post" enctype="multipart/form-data">
      <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
      <input type="hidden" name="op" value="create_and_submit">

      <div style="display:flex;flex-direction:column;gap:10px;">
        <label>
          <span style="font-size:.8rem;color:#374151;">الإصدار</span>
          <select name="issue_id" id="modal_issue_id" required
                  style="width:100%;padding:8px 10px;border:1px solid #d1d5db;border-radius:7px;font-size:.9rem;">
            <option value="">— اختر الإصدار —</option>
            <?php foreach ($issues_with_stock as $iss):
              $labelParts = [];
              $labelParts[] = $iss['product_name'];

              if (!empty($iss['issue_number'])) {
                  $labelParts[] = 'عدد ' . (int)$iss['issue_number'];
              }
              if (!empty($iss['title'])) {
                  $labelParts[] = $iss['title'];
              }

              $datePart  = str_pad((int)$iss['issue_month'], 2, '0', STR_PAD_LEFT) . '/' . $iss['issue_year'];
              $niceLabel = implode(' — ', $labelParts) . ' | ' . $datePart;
              $balance   = (int)$iss['warehouse_balance'];
            ?>
              <option value="<?= (int)$iss['id'] ?>"
                      data-balance="<?= $balance ?>">
                <?= h($niceLabel) ?> (رصيد المخزن الحالي: <?= $balance ?>)
              </option>
            <?php endforeach; ?>
          </select>
        </label>

        <div id="modal_balance_box" style="
          font-size:.8rem;
          color:#0f766e;
          background:#ecfdf5;
          border:1px solid #a7f3d0;
          border-radius:8px;
          padding:8px 10px;
          display:none;
        ">
          رصيد المخزن الحالي من هذا الإصدار: <span id="modal_balance_qty" style="font-weight:700;"></span>
        </div>

        <label>
          <span style="font-size:.8rem;color:#374151;">الكمية المورَّدة</span>
          <input type="number" name="qty" min="1" step="1" required
                 style="width:100%;padding:8px 10px;border:1px solid #d1d5db;border-radius:7px;font-size:.9rem;">
        </label>

        <label>
          <span style="font-size:.8rem;color:#374151;">صورة الإيصال</span>
          <input type="file" name="receipt_image" accept=".jpg,.jpeg,.png,.gif,.webp,.bmp,.svg,.tiff,.pdf"
                 style="width:100%;font-size:.85rem;" required>
        </label>
      </div>

      <div style="display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-top:14px;">
        <button type="submit"
                style="flex:1 1 160px;background:#2563eb;color:#fff;border:none;border-radius:8px;padding:8px 12px;font-size:.9rem;font-weight:600;cursor:pointer;">
          📤 إرسال للمراجعة
        </button>
        <button type="button" onclick="closeReceiptModal()"
                style="flex:1 1 120px;background:#f3f4f6;color:#374151;border:none;border-radius:8px;padding:8px 12px;font-size:.9rem;font-weight:600;cursor:pointer;">
          إلغاء
        </button>
      </div>
    </form>
  </div>
</div>

<!-- مودال عرض إيصال (للاطلاع / الاعتماد / الرفض) -->
<div id="viewModal">
  <div class="modal-box">
    <div class="modal-header">
      <h2 class="modal-title">عرض إيصال توريد</h2>
      <button type="button" class="modal-close" onclick="closeViewModal()">×</button>
    </div>
    <div id="viewModalBody">
      <!-- يتم تعبئته بـ AJAX -->
      <div style="text-align:center;padding:20px;font-size:.9rem;color:#6b7280;">جاري التحميل...</div>
    </div>
  </div>
</div>

<script>
function openReceiptModal() {
  document.getElementById('receiptModal').style.display = 'flex';
}
function closeReceiptModal() {
  document.getElementById('receiptModal').style.display = 'none';
}

function openViewModal(id) {
  const modal = document.getElementById('viewModal');
  const body  = document.getElementById('viewModalBody');
  modal.style.display = 'flex';
  body.innerHTML = '<div style="text-align:center;padding:20px;font-size:.9rem;color:#6b7280;">جاري التحميل...</div>';

  fetch('wh_receipts.php', {
    method: 'POST',
    headers: {'X-Requested-With':'XMLHttpRequest'},
    body: new FormData(Object.assign(document.createElement('form'), {
      innerHTML: `
        <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
        <input type="hidden" name="op" value="view_receipt">
        <input type="hidden" name="receipt_id" value="${id}">
      `
    }))
  })
  .then(r => r.json())
  .then(data => {
    if (data.ok) {
      body.innerHTML = data.html;
    } else {
      body.innerHTML = '<div style="text-align:center;padding:20px;color:#b91c1c;">'+(data.msg || 'خطأ في جلب البيانات')+'</div>';
    }
  })
  .catch(() => {
    body.innerHTML = '<div style="text-align:center;padding:20px;color:#b91c1c;">تعذّر الاتصال بالخادم</div>';
  });
}

function closeViewModal() {
  document.getElementById('viewModal').style.display = 'none';
}

/* عند اختيار الإصدار، إظهار رصيد المخزن الحالي من data-balance */
const issueSelect = document.getElementById('modal_issue_id');
const balBox      = document.getElementById('modal_balance_box');
const balSpan     = document.getElementById('modal_balance_qty');

if (issueSelect) {
  issueSelect.addEventListener('change', function() {
    const opt   = this.options[this.selectedIndex];
    const bal   = opt ? opt.getAttribute('data-balance') : null;
    if (bal === null || bal === '' || isNaN(bal)) {
      balBox.style.display = 'none';
      balSpan.textContent  = '';
    } else {
      balSpan.textContent  = bal;
      balBox.style.display = 'block';
    }
  });
}
</script>

</body>
</html>
