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

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

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

function fetch_invoice(PDO $pdo, int $id): ?array {
  $st = $pdo->prepare("
    SELECT inv.*, o.name AS outlet_name,
           d.name AS distributor_name, u.name AS created_by_name
    FROM invoices inv
    JOIN outlets o ON o.id=inv.outlet_id
    LEFT JOIN distributors d ON d.id=inv.distributor_id
    JOIN users u ON u.id=inv.created_by
    WHERE inv.id=?
  ");
  $st->execute([$id]);
  $r = $st->fetch();
  return $r ?: null;
}
function fetch_invoice_items(PDO $pdo, int $invoiceId): array {
  $st = $pdo->prepare("
    SELECT ii.*, CONCAT(p.name,' - ',LPAD(i.issue_month,2,'0'),'/',i.issue_year) AS issue_label
    FROM invoice_items ii
    JOIN issues i ON i.id=ii.issue_id
    JOIN products p ON p.id=i.product_id
    WHERE ii.invoice_id=?
    ORDER BY issue_label
  ");
  $st->execute([$invoiceId]);
  return $st->fetchAll();
}
function fetch_invoice_payments(PDO $pdo, int $invoiceId): array {
  $st = $pdo->prepare("
    SELECT pa.amount_allocated,
           p.payment_no, p.amount AS payment_amount, p.method, p.paid_at, p.notes
    FROM payment_allocations pa
    JOIN payments p ON p.id=pa.payment_id
    WHERE pa.invoice_id=?
    ORDER BY p.paid_at DESC, p.id DESC
  ");
  $st->execute([$invoiceId]);
  return $st->fetchAll();
}

if ($action === 'view' && $id > 0) {
  $inv = fetch_invoice($pdo, $id);
  if (!$inv) { http_response_code(404); exit("Invoice not found"); }
  $items = fetch_invoice_items($pdo, $id);
  $pays  = fetch_invoice_payments($pdo, $id);
} else {
  $inv = null; $items = []; $pays = [];
  $rows = $pdo->query("
    SELECT inv.id, inv.invoice_no, inv.issued_at, inv.status, inv.currency,
           inv.total_amount, inv.total_paid, inv.balance_due,
           o.name AS outlet_name
    FROM invoices inv
    JOIN outlets o ON o.id=inv.outlet_id
    ORDER BY inv.id DESC
    LIMIT 200
  ")->fetchAll();
}

function inv_status_ar(string $s): array {
  return match($s) {
    'ISSUED'        => ['صادرة',     'badge-submitted'],
    'PARTIALLY_PAID'=> ['مدفوعة جزئياً','badge-partial'],
    'PAID'          => ['مسددة',     'badge-approved'],
    'CANCELLED'     => ['ملغاة',     'badge-rejected'],
    default         => [$s,           'badge-draft'],
  };
}
function source_ar(string $s): string {
  return match($s) {
    'DIRECT_SALE'             => 'بيع مباشر',
    'CONSIGNMENT_SETTLEMENT'  => 'تسوية أمانة',
    default                   => $s,
  };
}
function method_ar(string $s): string {
  return match($s) {
    'CASH'         => 'نقداً',
    'BANK_TRANSFER'=> 'تحويل بنكي',
    'CHEQUE'       => 'شيك',
    default        => $s,
  };
}
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>الفواتير (INV) — MGZ</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
<style>
  *, *::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; transition: color .2s; }
  .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; }

  /* بطاقات الإجماليات */
  .totals-grid { display: grid; grid-template-columns: repeat(3,1fr); gap: 16px; margin-bottom: 24px; }
  .total-card { background: #fff; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,.07); padding: 20px; text-align: center; }
  .total-card .t-label { font-size: .8rem; color: #6b7280; margin-bottom: 8px; }
  .total-card .t-value { font-size: 1.5rem; font-weight: 700; }
  .t-blue  { color: #2563eb; }
  .t-green { color: #16a34a; }
  .t-red   { color: #dc2626; }

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

  .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; justify-content: space-between; gap: 8px; }
  .card-header-right { display: flex; align-items: center; gap: 8px; }

  .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: .82rem; padding: 11px 16px; 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: 11px 16px; font-size: .88rem; color: #374151; text-align: right; }
  tfoot td { padding: 11px 16px; font-size: .9rem; font-weight: 700; color: #1e3a5f; text-align: right; background: #f8faff; border-top: 2px solid #e5e7eb; }

  .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-partial   { background: #fef3c7; color: #92400e; }
  .badge-approved  { background: #d1fae5; color: #065f46; }
  .badge-rejected  { background: #fee2e2; color: #991b1b; }

  .source-badge { display: inline-block; padding: 3px 10px; border-radius: 6px; font-size: .78rem; font-weight: 600; background: #ede9fe; color: #4c1d95; }

  .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; text-decoration: none; transition: background .2s; }
  .btn-primary { background: #2563eb; color: #fff; } .btn-primary:hover { background: #1d4ed8; }
  .btn-success { background: #16a34a; color: #fff; } .btn-success:hover { background: #15803d; }

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

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

  .num-blue  { color: #2563eb; font-weight: 700; }
  .num-green { color: #16a34a; font-weight: 700; }
  .num-red   { color: #dc2626; font-weight: 700; }
  .num-orange{ color: #d97706; font-weight: 700; }
</style>
</head>
<body>

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

<?php if ($action === 'view' && $inv):
  [$status_ar, $status_cls] = inv_status_ar($inv['status']);
  $balance = (float)$inv['balance_due'];
?>

<!-- ===== عرض الفاتورة ===== -->
<div class="page-header">
  <div>
    <h1>📄 فاتورة</h1>
    <div class="subtitle"><?= source_ar($inv['source_type']) ?> — <?= h($inv['outlet_name']) ?></div>
  </div>
  <div class="doc-badge"><?= h($inv['invoice_no']) ?></div>
</div>

<div class="content">

  <!-- Meta Bar -->
  <div class="meta-bar">
    <div class="meta-item"><span class="meta-label">رقم الفاتورة</span><span class="meta-value"><?= h($inv['invoice_no']) ?></span></div>
    <div class="meta-item"><span class="meta-label">المنفذ</span><span class="meta-value"><?= h($inv['outlet_name']) ?></span></div>
    <?php if ($inv['distributor_name']): ?>
    <div class="meta-item"><span class="meta-label">الموزع</span><span class="meta-value"><?= h($inv['distributor_name']) ?></span></div>
    <?php endif; ?>
    <div class="meta-item"><span class="meta-label">المصدر</span><span class="source-badge"><?= source_ar($inv['source_type']) ?> #<?= (int)$inv['source_id'] ?></span></div>
    <div class="meta-item"><span class="meta-label">التاريخ</span><span class="meta-value"><?= h($inv['issued_at']) ?></span></div>
    <div class="meta-item"><span class="meta-label">العملة</span><span class="meta-value">ريال عماني</span></div>
    <div class="meta-item"><span class="meta-label">أنشئ بواسطة</span><span class="meta-value"><?= h($inv['created_by_name']) ?></span></div>
    <div class="meta-item"><span class="meta-label">الحالة</span><span class="badge <?= $status_cls ?>"><?= $status_ar ?></span></div>
  </div>

  <!-- بطاقات الإجماليات -->
  <div class="totals-grid">
    <div class="total-card">
      <div class="t-label">إجمالي الفاتورة</div>
      <div class="t-value t-blue"><?= omr((float)$inv['total_amount']) ?></div>
    </div>
    <div class="total-card">
      <div class="t-label">المدفوع</div>
      <div class="t-value t-green"><?= omr((float)$inv['total_paid']) ?></div>
    </div>
    <div class="
total-card">
      <div class="t-label">الرصيد المتبقي</div>
      <div class="t-value <?= $balance > 0 ? 't-red' : 't-green' ?>">
        <?= omr($balance) ?>
      </div>
    </div>
  </div>

  <!-- بنود الفاتورة -->
  <div class="card">
    <div class="card-header">
      <div class="card-header-right">📋 بنود الفاتورة</div>
    </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><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>
          <td><?= omr((float)$it['unit_price']) ?></td>
          <td class="num-blue"><?= omr((float)$it['line_total']) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="4">الإجمالي</td>
          <td class="num-blue"><?= omr((float)$inv['total_amount']) ?> <?= h($inv['currency']) ?></td>
        </tr>
      </tfoot>
    </table>
    <?php endif; ?>
  </div>

  <!-- المدفوعات المرتبطة -->
  <div class="card">
    <div class="card-header">
      <div class="card-header-right">💳 المدفوعات المرتبطة</div>
      <?php if ($balance > 0 && $me['role'] === 'ADMIN'): ?>
      <a href="payments.php?action=new&outlet_id=<?= (int)$inv['outlet_id'] ?>&invoice_id=<?= (int)$inv['id'] ?>" class="btn btn-success" style="font-size:.85rem;padding:7px 16px;">
        ➕ إضافة تحصيل
      </a>
      <?php endif; ?>
    </div>
    <?php if (empty($pays)): ?>
      <div class="empty-state"><div class="icon">💳</div><p>لا توجد مدفوعات مرتبطة بعد</p></div>
    <?php else: ?>
    <div class="table-meta"><?= count($pays) ?> تحصيل</div>
    <table>
      <thead>
        <tr>
          <th>#</th><th>رقم التحصيل</th><th>التاريخ</th><th>طريقة الدفع</th>
          <th>قيمة التحصيل</th><th>المخصص لهذه الفاتورة</th><th>ملاحظات</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($pays as $idx => $p): ?>
        <tr>
          <td><?= $idx + 1 ?></td>
          <td><strong><?= h($p['payment_no']) ?></strong></td>
          <td><?= h($p['paid_at']) ?></td>
          <td><?= method_ar($p['method']) ?></td>
          <td class="num-blue"><?= omr((float)$p['payment_amount']) ?></td>
          <td class="num-green"><?= omr((float)$p['amount_allocated']) ?></td>
          <td><?= h($p['notes'] ?? '') ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="5">إجمالي المدفوع</td>
          <td class="num-green"><?= omr((float)$inv['total_paid']) ?> <?= h($inv['currency']) ?></td>
          <td></td>
        </tr>
      </tfoot>
    </table>
    <?php endif; ?>
  </div>

  <!-- شريط الرصيد -->
  <?php if ($balance > 0): ?>
  <div style="background:#fef2f2; border:1px solid #fca5a5; border-radius:10px; padding:16px 24px; display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:12px;">
    <div style="color:#991b1b; font-weight:600; font-size:.95rem;">
      ⚠️ الرصيد المتبقي غير مسدد: <strong><?= omr($balance) ?> <?= h($inv['currency']) ?></strong>
    </div>
    <?php if ($me['role'] === 'ADMIN'): ?>
    <a href="payments.php?action=new&outlet_id=<?= (int)$inv['outlet_id'] ?>&invoice_id=<?= (int)$inv['id'] ?>" class="btn btn-primary">
      💲 تسجيل تحصيل
    </a>
    <?php endif; ?>
  </div>
  <?php else: ?>
  <div style="background:#d1fae5; border:1px solid #6ee7b7; border-radius:10px; padding:16px 24px; color:#065f46; font-weight:600;">
    ✔ تم سداد الفاتورة بالكامل
  </div>
  <?php endif; ?>

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

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

<div class="page-header">
  <div>
    <h1>📄 الفواتير (INV)</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">📄 آخر 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><th>الرصيد</th><th>عرض</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $idx => $r):
          [$st_ar, $st_cls] = inv_status_ar($r['status']);
          $bal = (float)$r['balance_due'];
        ?>
        <tr>
          <td><?= $idx + 1 ?></td>
          <td><strong><?= h($r['invoice_no']) ?></strong></td>
          <td><?= h($r['issued_at']) ?></td>
          <td><?= h($r['outlet_name']) ?></td>
          <td><span class="badge <?= $st_cls ?>"><?= $st_ar ?></span></td>
          <td class="num-blue"><?= omr((float)$r['total_amount']) ?> <small><?= h($r['currency']) ?></small></td>
          <td class="num-green"><?= omr((float)$r['total_paid']) ?></td>
          <td class="<?= $bal > 0 ? 'num-red' : 'num-green' ?>"><?= omr($bal) ?></td>
          <td><a href="invoices.php?action=view&id=<?= (int)$r['id'] ?>" class="btn-open">📂 عرض</a></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php endif; ?>
  </div>
</div>

<?php endif; ?>

</body>
</html>
