<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_login();
$pdo = db();
$cid = (int)$_SESSION['company_id'];
csrf_bootstrap();
?>
<?php
$msg = $_GET['msg'] ?? null;
$rows=$pdo->prepare("SELECT i.*, c.full_name customer_name
                     FROM invoices i JOIN customers c ON c.id=i.customer_id
                     WHERE i.company_id=? ORDER BY i.id DESC LIMIT 200");
$rows->execute([$cid]);
$list=$rows->fetchAll(PDO::FETCH_ASSOC);
render_layout('الفواتير','الفواتير <span class="mx-1">/</span> قائمة الفواتير', function() use($list,$msg){ ?>
<div class="container-fluid mt-3">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div><div class="fw-bold fs-4">قائمة الفواتير</div><div class="text-secondary small">Invoice-based + Draft accounting</div></div>
    <a class="btn btn-outline-dark" href="/journal/daily_posting.php"><i class="bi bi-journal-plus"></i> صفحة الترحيل</a>
  </div>
  <?php if($msg): ?><div class="alert alert-success mt-3"><?= h($msg) ?></div><?php endif; ?>
  <div class="card cardx mt-3">
    <div class="table-responsive p-3">
      <table class="table align-middle mb-0">
        <thead><tr class="text-secondary small"><th>#</th><th>رقم</th><th>العميل</th><th>التاريخ</th><th class="text-end">الإجمالي</th><th class="text-end">مدفوع</th><th>الحالة</th><th class="text-end">إجراءات</th></tr></thead>
        <tbody>
          <?php foreach($list as $r): ?>
          <tr>
            <td class="text-secondary"><?= (int)$r['id'] ?></td>
            <td class="fw-semibold"><?= h($r['invoice_no']) ?></td>
            <td><?= h($r['customer_name']) ?></td>
            <td class="text-secondary"><?= h($r['invoice_date']) ?></td>
            <td class="text-end fw-semibold"><?= nf($r['total']) ?></td>
            <td class="text-end"><?= nf($r['paid']) ?></td>
            <td><span class="badge bg-secondary-subtle border"><?= h($r['status']) ?></span></td>
            <td class="text-end">
              <a class="btn btn-outline-dark btn-sm" href="/tourism/payment_create.php?invoice_id=<?= (int)$r['id'] ?>"><i class="bi bi-cash-coin"></i> تحصيل</a>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php }); ?>
