<?php
declare(strict_types=1);
/**
 * modules/invoices/list.php
 *
 * Invoices grid.
 * - Filters: status, date range, search
 * - Actions: View, PDF, Send, Mark Paid
 */

require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$errors = [];
$notice = null;

function n2($v): string { return number_format((float)$v, 2); }
function badge_status(string $s): string {
  $cls = [
    'draft'   => 'secondary',
    'sent'    => 'info',
    'partial' => 'warning',
    'paid'    => 'success',
    'void'    => 'dark'
  ][strtolower($s)] ?? 'secondary';
  return '<span class="badge text-bg-'.$cls.'">'.e(ucfirst($s)).'</span>';
}

/* ------------- Filters ------------- */
$status = isset($_GET['status']) && $_GET['status'] !== '' ? (string)$_GET['status'] : null;
$from   = isset($_GET['from'])   && $_GET['from']   !== '' ? (string)$_GET['from']   : null;
$to     = isset($_GET['to'])     && $_GET['to']     !== '' ? (string)$_GET['to']     : null;
$q      = isset($_GET['q'])      && $_GET['q']      !== '' ? trim((string)$_GET['q']) : null;

/* ------------- Query ------------- */
$sql = "
  SELECT
    i.id,
    i.invoice_no,
    i.invoice_date,
    i.due_date,
    i.status,
    i.total_amount,
    i.paid_total,
    i.bill_to_name,
    i.bill_to_email,
    i.booking_id,
    b.booking_ref
  FROM invoices i
  LEFT JOIN bookings b ON b.id = i.booking_id
  WHERE i.company_id = :cid
";
$args = [':cid'=>$cid];

if ($status) { $sql .= " AND i.status = :st"; $args[':st'] = $status; }
if ($from)   { $sql .= " AND i.invoice_date >= :from"; $args[':from'] = $from; }
if ($to)     { $sql .= " AND i.invoice_date <= :to";   $args[':to']   = $to;   }
if ($q) {
  $sql .= " AND (i.invoice_no LIKE :q OR i.bill_to_name LIKE :q OR i.bill_to_email LIKE :q OR b.booking_ref LIKE :q)";
  $args[':q'] = '%'.$q.'%';
}
$sql .= " ORDER BY COALESCE(i.invoice_date, i.created_at) DESC, i.id DESC LIMIT 400";

$stmt = db()->prepare($sql);
$stmt->execute($args);
$rows = $stmt->fetchAll();

/* ------------- UI ------------- */
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Invoices</h1>
  <div class="d-flex gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('invoices/generate_from_booking.php')) ?>">From Booking</a>
    <a class="btn btn-outline-primary" href="<?= e(url_modules('invoices/generate_corporate.php')) ?>">Corporate Invoice</a>
    <a class="btn btn-dark" href="<?= e(url_modules('invoices/add.php')) ?>">New Invoice</a>
  </div>
</div>

<?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
<?php if ($errors): ?><div class="alert alert-danger"><ul class="mb-0"><?php foreach($errors as $er) echo '<li>'.e($er).'</li>'; ?></ul></div><?php endif; ?>

<div class="card shadow-sm mb-3">
  <div class="card-body">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select class="form-select" name="status">
          <option value="">— All —</option>
          <?php foreach (['draft','sent','partial','paid','void'] as $st): ?>
            <option value="<?= e($st) ?>" <?= ($status===$st)?'selected':'' ?>><?= e(ucfirst($st)) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">From</label>
        <input type="date" class="form-control" name="from" value="<?= e($from ?? '') ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">To</label>
        <input type="date" class="form-control" name="to" value="<?= e($to ?? '') ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Search</label>
        <input class="form-control" name="q" placeholder="Invoice # / Client / Email / Booking Ref" value="<?= e($q ?? '') ?>">
      </div>
      <div class="col-md-1 d-grid">
        <button class="btn btn-primary">Filter</button>
      </div>
      <div class="col-md-1 d-grid">
        <a class="btn btn-outline-secondary" href="list.php">Reset</a>
      </div>
    </form>
  </div>
</div>

<div class="card shadow-sm">
  <div class="table-responsive">
    <table class="table align-middle mb-0">
      <thead class="table-light">
        <tr>
          <th>Invoice #</th>
          <th>Date</th>
          <th>Due</th>
          <th>Client</th>
          <th>Booking Ref</th>
          <th class="text-end">Total £</th>
          <th class="text-end">Paid £</th>
          <th class="text-end">Balance £</th>
          <th>Status</th>
          <th style="min-width:240px;">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($rows): foreach ($rows as $r):
          $total   = (float)($r['total_amount'] ?? 0);
          $paid    = (float)($r['paid_total'] ?? 0);
          $balance = max(0.0, $total - $paid);
        ?>
        <tr>
          <td><a href="<?= e(url_modules('invoices/view.php').'?id='.(int)$r['id']) ?>" class="text-decoration-none"><?= e($r['invoice_no'] ?? ('INV-'.$r['id'])) ?></a></td>
          <td><?= e($r['invoice_date'] ?? '—') ?></td>
          <td><?= e($r['due_date'] ?? '—') ?></td>
          <td>
            <?php if (!empty($r['bill_to_name'])): ?><div class="fw-semibold"><?= e($r['bill_to_name']) ?></div><?php endif; ?>
            <?php if (!empty($r['bill_to_email'])): ?><div class="text-muted small"><?= e($r['bill_to_email']) ?></div><?php endif; ?>
            <?php if (empty($r['bill_to_name']) && empty($r['bill_to_email'])): ?><span class="text-muted">—</span><?php endif; ?>
          </td>
          <td><?= e($r['booking_ref'] ?? '—') ?></td>
          <td class="text-end"><?= e(n2($total)) ?></td>
          <td class="text-end"><?= e(n2($paid)) ?></td>
          <td class="text-end"><?= e(n2($balance)) ?></td>
          <td><?= badge_status((string)$r['status']) ?></td>
          <td>
            <div class="d-flex flex-wrap gap-1">
              <a class="btn btn-sm btn-outline-primary" href="<?= e(url_modules('invoices/view.php').'?id='.(int)$r['id']) ?>">View</a>
              <a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('invoices/pdf.php').'?id='.(int)$r['id']) ?>" target="_blank">PDF</a>
              <a class="btn btn-sm btn-outline-success" href="<?= e(url_modules('invoices/send.php').'?id='.(int)$r['id']) ?>">Send</a>
              <a class="btn btn-sm btn-dark" href="<?= e(url_modules('invoices/mark_paid.php').'?id='.(int)$r['id']) ?>">Mark Paid</a>
            </div>
          </td>
        </tr>
        <?php endforeach; else: ?>
          <tr><td colspan="10" class="text-center text-muted py-4">No invoices found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php include dirname(__DIR__, 2) . '/includes/footer.php'; ?>
