<?php
// view: pages/purchases/invoice_view
$invoice = $invoice ?? null;
$lines = $lines ?? [];
$retCount = (int)($retCount ?? 0);
$retSum = (float)($retSum ?? 0);
$paidSum = (float)($paidSum ?? 0);
$dueAmount = (float)($dueAmount ?? 0);
if (!$invoice) return;

$st = strtoupper((string)$invoice['status']);
$badge = $st==='POSTED'?'success':($st==='DRAFT'?'warning':'secondary');
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-1">فاتورة شراء: <span class="fw-bold"><?= e((string)$invoice['inv_no']) ?></span></h4>
    <div class="text-muted small">
      الطرف / المورد: <?= e((string)$invoice['party_name'] ?? $invoice['supplier_name']) ?> —
      المخزن: <?= e((string)$invoice['warehouse_name']) ?> —
      التاريخ: <?= e(substr((string)$invoice['inv_date'],0,10)) ?>
    </div>
  </div>

  <div class="d-flex gap-2 flex-wrap">
    <a class="btn btn-outline-secondary" href="<?= e($purchase_invoices_url ?? url('/purchases/invoices')) ?>"><i class="fa-solid fa-arrow-right me-1"></i>رجوع</a>

    <?php if (can('purchases.print')): ?>
      <a class="btn btn-outline-primary" target="_blank" href="<?= e(url('/prints/purchase-invoice?id='.(int)$invoice['id'])) ?>">
        <i class="fa-solid fa-print me-1"></i>طباعة
      </a>
    <?php endif; ?>

    <?php if ($st==='DRAFT' && can('purchases.edit')): ?>
      <a class="btn btn-primary" href="<?= e(($purchase_invoice_form_url ?? url('/purchases/invoices/form')) . '?id='.(int)$invoice['id']) ?>">
        <i class="fa-solid fa-pen-to-square me-1"></i>تعديل
      </a>
    <?php endif; ?>

    <?php if ($st==='DRAFT' && can('purchases.post')): ?>
      <form method="post" class="d-inline" onsubmit="return confirm('تأكيد ترحيل فاتورة الشراء؟');">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="post">
        <button class="btn btn-success">
          <i class="fa-solid fa-circle-check me-1"></i>ترحيل
        </button>
      </form>
    <?php endif; ?>

    <?php if ($st==='DRAFT' && can('purchases.edit')): ?>
      <form method="post" class="d-inline" onsubmit="return confirm('تأكيد إلغاء الفاتورة (مسودة)؟');">
        <?= csrf_field() ?>
        <input type="hidden" name="action" value="cancel">
        <button class="btn btn-outline-danger">
          <i class="fa-solid fa-ban me-1"></i>إلغاء
        </button>
      </form>
    <?php endif; ?>

    <?php if ($st==='POSTED' && can('purchase_returns.create')): ?>
      <a class="btn btn-outline-dark" href="<?= e(($purchase_return_form_url ?? url('/purchases/returns/form')) . '?invoice_id='.(int)$invoice['id']) ?>">
        <i class="fa-solid fa-rotate-left me-1"></i>إنشاء مرتجع
      </a>
    <?php endif; ?>
  </div>
</div>

<div class="row g-3">
  <div class="col-md-8">
    <div class="card mb-3">
      <div class="card-header d-flex justify-content-between align-items-center">
        <div class="fw-bold">بنود الفاتورة</div>
        <span class="badge text-bg-<?= $badge ?>"><?= e($st) ?></span>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-bordered align-middle mb-0">
            <thead class="table-light">
              <tr>
                <th style="width:60px">م</th>
                <th>الصنف</th>
                <th style="width:160px">الوحدة</th>
                <th style="width:120px">الكمية</th>
                <th style="width:140px">السعر</th>
                <th style="width:140px">الإجمالي</th>
              </tr>
            </thead>
            <tbody>
              <?php $i=1; foreach ($lines as $ln): ?>
                <tr>
                  <td class="text-center"><?= $i++ ?></td>
                  <td><?= e((string)$ln['item_name']) ?></td>
                  <td class="text-center"><?= e((string)($ln['unit_name'] ?? '')) ?></td>
                  <td class="text-center"><?= e(format_qty((float)$ln['qty'])) ?></td>
                  <td class="text-center"><?= e(format_money((float)$ln['unit_price'])) ?></td>
                  <td class="text-center"><?= e(format_money((float)$ln['line_total'])) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <?php if (!empty($invoice['notes']) || !empty($invoice['discount_note']) || !empty($invoice['charges_note'])): ?>
      <div class="card">
        <div class="card-header fw-bold">ملاحظات</div>
        <div class="card-body">
          <?php if (!empty($invoice['discount_note'])): ?>
            <div class="mb-2"><span class="text-muted">ملاحظة الخصم:</span> <strong><?= e((string)$invoice['discount_note']) ?></strong></div>
          <?php endif; ?>
          <?php if (!empty($invoice['charges_note'])): ?>
            <div class="mb-2"><span class="text-muted">ملاحظة المصاريف:</span> <strong><?= e((string)$invoice['charges_note']) ?></strong></div>
          <?php endif; ?>
          <?php if (!empty($invoice['notes'])): ?>
            <div><?= e((string)$invoice['notes']) ?></div>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <div class="col-md-4">
    <div class="card mb-3">
      <div class="card-header fw-bold">ملخص</div>
      <div class="card-body">
        <div class="d-flex justify-content-between mb-2"><span class="text-muted">الإجمالي قبل الخصم</span><strong><?= e(format_money((float)$invoice['subtotal'])) ?></strong></div>
        <div class="d-flex justify-content-between mb-2"><span class="text-muted">الخصم</span><strong><?= e(format_money((float)$invoice['discount_amount'])) ?></strong></div>
        <?php if ((int)$invoice['tax_enabled'] === 1): ?>
          <div class="d-flex justify-content-between mb-2"><span class="text-muted">ض.ق.مضافة</span><strong><?= e(format_money((float)$invoice['tax_amount'])) ?></strong></div>
        <?php endif; ?>
        <?php if ((int)($invoice['wht_enabled'] ?? 0) === 1): ?>
          <div class="d-flex justify-content-between mb-2"><span class="text-muted">ضريبة ص/ت</span><strong><?= e(format_money((float)($invoice['wht_amount'] ?? 0))) ?></strong></div>
        <?php endif; ?>

        <?php if ((float)$invoice['extra_charges'] > 0): ?>
          <div class="d-flex justify-content-between mb-2"><span class="text-muted">مصاريف إضافية</span><strong><?= e(format_money((float)$invoice['extra_charges'])) ?></strong></div>
        <?php endif; ?>
        <hr>
        <div class="d-flex justify-content-between"><span class="fw-bold">الصافي</span><span class="fw-bold fs-5"><?= e(format_money((float)$invoice['total'])) ?></span></div>
        <div class="d-flex justify-content-between mt-2"><span class="text-muted">نوع السداد</span><strong><?php
          $pm = strtolower((string)($invoice['payment_mode'] ?? 'credit'));
          echo e($pm === 'cash' ? 'نقدي' : ($pm === 'partial' ? 'جزئي' : 'آجل'));
        ?></strong></div>
        <?php if (!empty($invoice['payment_note'])): ?>
          <div class="small text-muted mt-2">ملاحظة السداد: <?= e((string)$invoice['payment_note']) ?></div>
        <?php endif; ?>
      </div>
    </div>

    <?php if ($st === 'POSTED'): ?>
      <div class="card mb-3">
        <div class="card-header fw-bold">السداد</div>
        <div class="card-body">
          <?php
            $netTotal = (float)($invoice['total'] ?? 0) - (float)$retSum;
            $paid = (float)$paidSum;
            $due = max(0, (float)$dueAmount);
          ?>
          <div class="d-flex justify-content-between mb-2"><span class="text-muted">صافي الفاتورة بعد المرتجع</span><strong><?= e(format_money($netTotal)) ?></strong></div>
          <div class="d-flex justify-content-between mb-2"><span class="text-muted">مدفوع</span><strong><?= e(format_money($paid)) ?></strong></div>
          <hr>
          <div class="d-flex justify-content-between"><span class="fw-bold">المتبقي</span><span class="fw-bold fs-5"><?= e(format_money($due)) ?></span></div>
        </div>
      </div>
    <?php endif; ?>

    <?php if ($retCount > 0): ?>
      <div class="card">
        <div class="card-header fw-bold">مرتجعات على الفاتورة</div>
        <div class="card-body">
          <div class="d-flex justify-content-between"><span class="text-muted">عدد المرتجعات</span><strong><?= (int)$retCount ?></strong></div>
          <div class="d-flex justify-content-between"><span class="text-muted">إجمالي المرتجع</span><strong><?= e(format_money($retSum)) ?></strong></div>
          <a class="btn btn-sm btn-outline-secondary mt-2" href="<?= e(($purchase_returns_url ?? url('/purchases/returns')) . '?q=' . urlencode((string)$invoice['inv_no'])) ?>">عرض المرتجعات</a>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>
