<?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_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();
$id     = (int)($_GET['id'] ?? 0);
$action = $_GET['action'] ?? 'edit';
$error_message = null;

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

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

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

        // صورة الدفع إلزامية (من wh_receipts.php احنا أصلاً ما بنبعتش غير لو في صورة)
        if (empty($r['image_path'])) {
            exit("يجب أن يحتوي الإيصال على صورة دفع قبل الاعتماد.");
        }

        $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_view.php?id=".$receipt_id);
    }

    if ($op === 'reject') {
        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]);

        redirect("wh_receipts_view.php?id=".$receipt_id);
    }
}

/* ───────── جلب بيانات الإيصال ───────── */

if ($id <= 0) {
    http_response_code(400);
    exit("Bad id");
}

$receipt = fetch_receipt($pdo, $id);
if (!$receipt) {
    http_response_code(404);
    exit("Not found");
}
$items = fetch_receipt_items($pdo, $id);

[$status_ar, $status_cls] = whr_status_ar($receipt['status']);
$can_moderate = ($me['role'] === 'ADMIN' && $receipt['status'] === 'SUBMITTED');
?>
<!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; }
.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; letter-spacing: .6px; }
.meta-value { font-size: .95rem; font-weight: 600; color: #1e3a5f; }

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

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

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

.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-success   { background: #16a34a; color: #fff; }
.btn-success:hover   { background: #15803d; }
.btn-danger    { background: #dc2626; color: #fff; }
.btn-danger:hover    { background: #b91c1c; }
.btn-secondary { background: #e5e7eb; color: #374151; }
.btn-secondary:hover { background: #d1d5db; }

.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: 260px;
}
.reject-row input:focus {
    outline:none;
    border-color:#dc2626;
}

/* عرض صورة الإيصال */
.receipt-img {
    max-width: 100%;
    height: auto;
    border-radius: 8px;
    border:1px solid #e5e7eb;
}
</style>
</head>
<body>

<a class="back-link" href="wh_receipts.php">← العودة لقائمة الإيصالات</a>

<div class="page-header">
  <div>
    <h1>📥 عرض إيصال توريد</h1>
    <div class="subtitle">مراجعة واعتماد إيصال التوريد من أمين المخزن</div>
  </div>
  <div class="doc-badge">
    <?= $receipt['receipt_no'] ? h($receipt['receipt_no']) : 'بدون رقم بعد' ?>
  </div>
</div>

<div class="content">

  <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 (!empty($receipt['manager_reason'])): ?>
  <div class="alert-danger">
    <span>⚠️</span>
    <div><strong>سبب الرفض:</strong> <?= h($receipt['manager_reason']) ?></div>
  </div>
  <?php endif; ?>

  <!-- صورة إيصال الدفع -->
  <div class="card">
    <div class="card-header">🧾 صورة إيصال الدفع</div>
    <div class="card-body">
      <?php if (!empty($receipt['image_path'])): ?>
        <a href="<?= h($receipt['image_path']) ?>" target="_blank" style="display:inline-block;margin-bottom:10px;">
          <img src="<?= h($receipt['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($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>

        <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="receipt_id" value="<?= (int)$receipt['id'] ?>">
          <input type="text" name="reason" placeholder="سبب الرفض..." required>
          <button type="submit" class="btn btn-danger">✖ رفض</button>
        </form>

      </div>
    </div>
  </div>
  <?php elseif ($receipt['status'] === 'APPROVED'): ?>
  <div class="card">
    <div class="card-header">ℹ حالة الإيصال</div>
    <div class="card-body">
      <span style="color:#16a34a;font-weight:600;">✔ تم اعتماد هذا الإيصال وتم احتسابه في رصيد المخزون.</span>
    </div>
  </div>
  <?php endif; ?>

</div>

</body>
</html>
