<?php
// view: pages/purchases/invoices_index
$rows = $rows ?? [];
$q = $q ?? '';
$status = $status ?? '';
$from = $from ?? '';
$to = $to ?? '';
$for_return = (bool)($for_return ?? false);
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-1"><?= $for_return ? 'إنشاء مرتجع شراء' : 'فواتير الشراء' ?></h4>
    <div class="text-muted small"><?= $for_return ? 'اختر فاتورة شراء مرحّلة لإنشاء مرتجع' : 'إدارة فواتير الشراء (مسودات/ترحيل/طباعة)' ?></div>
  </div>
  <div class="d-flex gap-2">
    <?php if ($for_return): ?>
      <a class="btn btn-outline-secondary" href="<?= e($purchase_returns_url ?? url('/purchases/returns')) ?>">
        <i class="fa-solid fa-rotate-left me-1"></i> سجل المرتجعات
      </a>
    <?php endif; ?>
    <?php if (can('purchases.create')): ?>
      <a class="btn btn-primary" href="<?= e($purchase_invoice_form_url ?? url('/purchases/invoices/form')) ?>">
        <i class="fa-solid fa-plus me-1"></i> فاتورة شراء جديدة
      </a>
    <?php endif; ?>
  </div>
</div>

<div class="card mb-3">
  <div class="card-body">
    <form class="row g-2 align-items-end" method="get">
      <?php if ($for_return): ?>
        <input type="hidden" name="for_return" value="1">
      <?php endif; ?>
      <div class="col-md-4">
        <label class="form-label">بحث</label>
        <input name="q" class="form-control" value="<?= e($q) ?>" placeholder="رقم الفاتورة / المورد">
      </div>
      <div class="col-md-2">
        <label class="form-label">الحالة</label>
        <select name="status" class="form-select" <?= $for_return ? 'disabled' : '' ?>>
          <option value="">الكل</option>
          <option value="DRAFT" <?= $status==='DRAFT'?'selected':'' ?>>مسودة</option>
          <option value="POSTED" <?= $status==='POSTED'?'selected':'' ?>>مرحّلة</option>
          <option value="CANCELED" <?= $status==='CANCELED'?'selected':'' ?>>ملغاة</option>
        </select>
        <?php if ($for_return): ?>
          <input type="hidden" name="status" value="POSTED">
        <?php endif; ?>
      </div>
      <div class="col-md-2">
        <label class="form-label">من</label>
        <input type="date" name="from" class="form-control" value="<?= e($from) ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">إلى</label>
        <input type="date" name="to" class="form-control" value="<?= e($to) ?>">
      </div>
      <div class="col-md-2 d-grid">
        <button class="btn btn-outline-primary"><i class="fa-solid fa-magnifying-glass me-1"></i>بحث</button>
      </div>
    </form>
  </div>
</div>

<div class="card">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover mb-0">
        <thead class="table-light">
          <tr>
            <th style="width:70px">#</th>
            <th>رقم الفاتورة</th>
            <th>التاريخ</th>
            <th>المورد</th>
            <th>المخزن</th>
            <th class="text-end">الإجمالي</th>
            <th class="text-end">مدفوع</th>
            <th class="text-end">متبقي</th>
            <th style="width:120px">حالة السداد</th>
            <th style="width:120px">الحالة</th>
            <th style="width:170px"></th>
          </tr>
        </thead>
        <tbody>
        <?php if (!$rows): ?>
          <tr><td colspan="11" class="text-center text-muted py-4">لا توجد بيانات</td></tr>
        <?php else: ?>
          <?php foreach ($rows as $r): ?>
            <tr>
              <td><?= (int)$r['id'] ?></td>
              <td class="fw-bold"><?= e((string)$r['inv_no']) ?></td>
              <td><?= e(substr((string)$r['inv_date'],0,10)) ?></td>
              <td><?= e((string)$r['supplier_name']) ?></td>
              <td><?= e((string)$r['warehouse_name']) ?></td>
              <td class="text-end"><?= e(format_money((float)$r['total'])) ?></td>
              <?php
                $total = (float)$r['total'];
                $paid = (float)($r['paid_total'] ?? 0);
                $ret = (float)($r['ret_total'] ?? 0);
                $due = max(0, ($total - $ret) - $paid);
                $payStatus = '—';
                $payCls = 'secondary';
                if (strtoupper((string)$r['status']) === 'POSTED') {
                  if ($due <= 0.009) { $payStatus = 'مدفوع'; $payCls='success'; }
                  elseif ($paid > 0.009) { $payStatus = 'جزئي'; $payCls='warning'; }
                  else { $payStatus = 'غير مدفوع'; $payCls='secondary'; }
                }
              ?>
              <td class="text-end"><?= e(format_money($paid)) ?></td>
              <td class="text-end"><?= e(format_money($due)) ?></td>
              <td><span class="badge text-bg-<?= e($payCls) ?>"><?= e($payStatus) ?></span></td>
              <td>
                <?php
                  $st = strtoupper((string)$r['status']);
                  $cls = $st==='POSTED'?'success':($st==='DRAFT'?'warning':'secondary');
                ?>
                <span class="badge text-bg-<?= $cls ?>"><?= e($st) ?></span>
              </td>
              <td class="text-end">
                <?php if ($for_return && strtoupper((string)$r['status'])==='POSTED' && can('purchase_returns.create')): ?>
                  <a class="btn btn-sm btn-success" href="<?= e(($purchase_return_form_base_url ?? url('/purchases/returns/form')) . '?invoice_id='.(int)$r['id']) ?>" title="إنشاء مرتجع">
                    <i class="fa-solid fa-rotate-left me-1"></i>مرتجع
                  </a>
                <?php endif; ?>
                <a class="btn btn-sm btn-outline-secondary" href="<?= e(($purchase_invoice_view_base_url ?? url('/purchases/invoices/view')) . '?id='.(int)$r['id']) ?>">
                  <i class="fa-solid fa-eye"></i>
                </a>
                <?php if (can('purchases.print')): ?>
                  <a class="btn btn-sm btn-outline-primary" target="_blank" href="<?= e(url('/prints/purchase-invoice?id='.(int)$r['id'])) ?>" title="طباعة">
                    <i class="fa-solid fa-print"></i>
                  </a>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
