<?php
// view: pages/sales/invoice_view
$inv = $inv ?? [];
$lines = $lines ?? [];
$salesReturnSummary = $salesReturnSummary ?? ['count'=>0,'total'=>0.0];

$formatUrl = function(string $fmt) use ($inv) {
  return url('/prints/sales-invoice') . '?id=' . (int)$inv['id'] . '&format=' . urlencode($fmt);
};

$isDraft = strtoupper((string)($inv['status'] ?? '')) === 'DRAFT';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <h4 class="mb-0">فاتورة مبيعات: <?= e($inv['invoice_no'] ?? '') ?></h4>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-dark" href="<?= e(url($sales_invoices_url ?? '/sales/invoices')) ?>">رجوع</a>
    <?php if ($isDraft && can('sales.invoices.edit')): ?>
      <a class="btn btn-outline-primary" href="<?= e(url($sales_invoice_form_url ?? '/sales/invoices/form')) ?>?id=<?= (int)$inv['id'] ?>">تعديل</a>
      <form method="post" action="<?= e(url('/sales/invoices/delete-draft')) ?>" class="d-inline" onsubmit="return confirm('سيتم حذف الفاتورة المسودة نهائيًا. هل تريد المتابعة؟');">
        <?= csrf_field() ?>
        <input type="hidden" name="id" value="<?= (int)$inv['id'] ?>">
        <button type="submit" class="btn btn-outline-danger">حذف المسودة</button>
      </form>
    <?php endif; ?>
    <?php if (can('sales.invoices.print')): ?>
      <div class="btn-group">
        <button type="button" class="btn btn-dark dropdown-toggle" data-bs-toggle="dropdown">طباعة</button>
        <ul class="dropdown-menu dropdown-menu-end">
          <li><a class="dropdown-item" href="<?= e($formatUrl('a4')) ?>" target="_blank">A4</a></li>
          <li><a class="dropdown-item" href="<?= e($formatUrl('receipt')) ?>" target="_blank">Receipt 80mm</a></li>
        </ul>
      </div>
    <?php endif; ?>
    <?php if (strtoupper((string)($inv['status'] ?? ''))==='POSTED' && can('sales_returns.create')): ?>
      <a class="btn btn-outline-danger" href="<?= e(url($sales_return_form_url ?? '/sales/returns/form')) ?>?invoice_id=<?= (int)$inv['id'] ?>">إنشاء مرتجع بيع</a>
    <?php endif; ?>
  </div>
</div>

<div class="row g-3">
  <div class="col-md-4">
    <div class="card p-3">
      <div class="text-muted small">الطرف / العميل</div>
      <?php $partyCode = (string)($inv['party_code'] ?? $inv['customer_code'] ?? ''); ?>
      <div class="fw-bold"><?= e((string)($inv['party_name'] ?? $inv['customer_name'] ?? '-')) ?><?= $partyCode !== '' ? ' <span class="text-muted">(' . e($partyCode) . ')</span>' : '' ?></div>
      <div class="text-muted small mt-2">التاريخ</div>
      <div><?= e(substr((string)$inv['invoice_date'],0,10)) ?></div>
      <div class="text-muted small mt-2">المخزن</div>
      <div><?= e($inv['warehouse_name'] ?? '') ?></div>
      <div class="text-muted small mt-2">الحالة</div>
      <div>
        <?php if (strtoupper((string)$inv['status'])==='POSTED'): ?>
          <span class="badge bg-success">مرحّلة</span>
        <?php else: ?>
          <span class="badge bg-secondary">مسودة</span>
        <?php endif; ?>
      </div>
      <div class="text-muted small mt-2">نوع السداد</div>
      <div>
        <?php $pm = strtolower((string)($inv['payment_mode'] ?? 'credit')); ?>
        <?= e($pm === 'cash' ? 'نقدي' : ($pm === 'partial' ? 'دفع جزئي' : 'آجل')) ?>
      </div>
      <div class="text-muted small mt-2">المدفوع / المتبقي</div>
      <div><?= format_money($inv['paid_amount'] ?? 0) ?> / <?= format_money($inv['due_amount'] ?? 0) ?></div>
      <div class="text-muted small mt-2">الخزنة</div>
      <div><?= e($inv['cashbox_name'] ?? '-') ?></div>
    </div>
  </div>

  <div class="col-md-8">
    <div class="card p-3">
      <div class="table-responsive">
        <table class="table table-bordered table-sm align-middle mb-0">
          <thead class="table-light">
            <tr>
              <th>#</th>
              <th>الصنف</th>
              <th class="text-end">الكمية</th>
              <th class="text-end">السعر</th>
              <th class="text-end">الإجمالي</th>
            </tr>
          </thead>
          <tbody>
            <?php $pieces = 0; foreach ($lines as $i => $ln): $pieces += (float)$ln['qty']; ?>
              <tr>
                <td><?= $i+1 ?></td>
                <td><?= e($ln['item_name'] ?? '') ?></td>
                <td class="text-end"><?= format_qty($ln['qty']) ?></td>
                <td class="text-end"><?= format_money($ln['price']) ?></td>
                <td class="text-end"><?= format_money($ln['line_total']) ?></td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$lines): ?>
              <tr><td colspan="5" class="text-center text-muted py-4">لا توجد أصناف</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      <div class="d-flex justify-content-between text-muted small mt-2">
        <div>إجمالي عدد القطع: <b><?= format_qty($pieces) ?></b></div>
      </div>
    </div>

    <div class="card p-3 mt-3">
      <div class="row">
        <div class="col-md-6">
          <div class="text-muted small">ملاحظات</div>
          <div><?= e($inv['notes'] ?? '') ?></div>
          <div class="mt-3 border-top pt-3">
            <div class="text-muted small">مرتجعات البيع المرحّلة</div>
            <div class="fw-bold"><?= (int)($salesReturnSummary['count'] ?? 0) ?> مستند</div>
            <div class="small">بقيمة <?= e(format_money((float)($salesReturnSummary['total'] ?? 0))) ?></div>
            <?php if (can('sales_returns.view')): ?>
              <a class="btn btn-sm btn-outline-secondary mt-2" href="<?= e((url($sales_returns_url ?? '/sales/returns')) . '?q=' . urlencode((string)($inv['invoice_no'] ?? ''))) ?>">عرض المرتجعات</a>
            <?php endif; ?>
          </div>
        </div>
        <div class="col-md-6">
          <div class="d-flex justify-content-between"><span>قبل الخصم</span><span><?= format_money($inv['subtotal'] ?? $inv['total'] ?? 0) ?></span></div>
          <div class="d-flex justify-content-between"><span>الخصم</span><span><?= format_money($inv['discount_amount'] ?? 0) ?></span></div>
          <div class="d-flex justify-content-between"><span>الصافي بعد الخصم</span><span><?= format_money($inv['net_after_discount'] ?? 0) ?></span></div>
          <div class="d-flex justify-content-between"><span>VAT</span><span><?= format_money($inv['vat_amount'] ?? 0) ?></span></div>
          <hr class="my-2">
          <div class="d-flex justify-content-between fw-bold"><span>الإجمالي</span><span><?= format_money($inv['grand_total'] ?? $inv['total'] ?? 0) ?></span></div>
          <div class="d-flex justify-content-between"><span>المدفوع الآن</span><span><?= format_money($inv['paid_amount'] ?? 0) ?></span></div>
          <div class="d-flex justify-content-between text-danger fw-bold"><span>المتبقي</span><span><?= format_money($inv['due_amount'] ?? 0) ?></span></div>
        </div>
      </div>
    </div>
  </div>
</div>
