<?php
declare(strict_types=1);
/**
 * modules/invoices/view.php
 *
 * View a single invoice with actions (PDF / Send / Mark Paid / Mark Unpaid).
 */

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'));

$iid = (int)($_GET['id'] ?? 0);
if ($iid <= 0) redirect(url_modules('invoices/list.php'));

$errors = [];
$notice = null;

/* Fetch invoice */
$invStmt = db()->prepare("SELECT * FROM invoices WHERE id = :id AND company_id = :cid LIMIT 1");
$invStmt->execute([':id'=>$iid, ':cid'=>$cid]);
$invoice = $invStmt->fetch();
if (!$invoice) redirect(url_modules('invoices/list.php'));

/* Lines */
$linesStmt = db()->prepare("
  SELECT id, description, quantity, unit_price, line_total
  FROM invoice_lines
  WHERE invoice_id = :iid
  ORDER BY id ASC
");
$linesStmt->execute([':iid'=>$iid]);
$lines = $linesStmt->fetchAll();

/* Optional booking snapshot */
$booking = null;
if (!empty($invoice['booking_id'])) {
  $bk = db()->prepare("
    SELECT b.*, p.name AS partner_name
    FROM bookings b
    LEFT JOIN partners p ON p.id=b.partner_id
    WHERE b.id=:bid AND b.company_id=:cid
    LIMIT 1
  ");
  $bk->execute([':bid'=>(int)$invoice['booking_id'], ':cid'=>$cid]);
  $booking = $bk->fetch() ?: null;
}

function badge_status_invoice(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>';
}
function n2($v): string { return number_format((float)$v, 2); }

$subtotal = (float)($invoice['subtotal_amount'] ?? 0);
$discount = (float)($invoice['discount_amount'] ?? 0);
$vatRate  = (float)($invoice['vat_rate'] ?? 0);
$vatAmt   = (float)($invoice['vat_amount'] ?? 0);
$total    = (float)($invoice['total_amount'] ?? 0);
$paid     = (float)($invoice['paid_total'] ?? 0);
$balance  = max(0.0, $total - $paid);

include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="position-sticky top-0 z-3 pb-2" style="background:#f8fafc;">
  <div class="d-flex justify-content-between align-items-center pt-2 mb-2">
    <div>
      <h1 class="h4 mb-0">Invoice <?= e($invoice['invoice_no'] ?? ('#'.$invoice['id'])) ?> <?= badge_status_invoice((string)$invoice['status']) ?></h1>
      <div class="small text-muted">
        Date: <?= e($invoice['invoice_date'] ?? '') ?> • Due: <?= e($invoice['due_date'] ?? '') ?>
        <?php if (!empty($invoice['booking_id'])): ?>
          • Booking: <a href="<?= e(url_modules('bookings/edit.php').'?id='.(int)$invoice['booking_id']) ?>">#<?= e($invoice['booking_id']) ?></a>
        <?php endif; ?>
      </div>
    </div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary" target="_blank" href="<?= e(url_modules('invoices/pdf.php').'?id='.(int)$invoice['id']) ?>">PDF</a>
      <a class="btn btn-outline-secondary" href="<?= e(url_modules('invoices/send.php').'?id='.(int)$invoice['id']) ?>">Send Email</a>

      <form method="post" action="<?= e(url_modules('invoices/mark_paid.php')) ?>" class="d-inline">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="id" value="<?= (int)$invoice['id'] ?>">
        <input type="hidden" name="action" value="mark_paid">
        <button class="btn btn-success" <?= strtolower((string)$invoice['status'])==='paid' ? 'disabled' : '' ?>>
          Mark Paid
        </button>
      </form>

      <form method="post" action="<?= e(url_modules('invoices/mark_paid.php')) ?>" class="d-inline" onsubmit="return confirm('Reset payments and mark as UNPAID?');">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="id" value="<?= (int)$invoice['id'] ?>">
        <input type="hidden" name="action" value="mark_unpaid">
        <button class="btn btn-outline-danger" <?= (float)$invoice['paid_total']<=0 ? 'disabled' : '' ?>>Mark Unpaid</button>
      </form>

      <a class="btn btn-outline-secondary" href="<?= e(url_modules('invoices/list.php')) ?>">Back</a>
    </div>
  </div>
</div>

<div class="row g-3">
  <div class="col-12 col-lg-8">
    <div class="card shadow-sm mb-3">
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-7">
            <h2 class="h6 text-uppercase text-muted mb-2">Invoice To</h2>
            <div class="border rounded p-2 bg-light">
              <div class="fw-bold"><?= e($invoice['bill_to_name'] ?? '—') ?></div>
              <?php if (!empty($invoice['bill_to_email'])): ?><div class="small text-muted"><?= e($invoice['bill_to_email']) ?></div><?php endif; ?>
              <?php if (!empty($invoice['bill_to_address'])): ?><div class="mt-1"><?= nl2br(e((string)$invoice['bill_to_address'])) ?></div><?php endif; ?>
            </div>
          </div>
          <div class="col-md-5">
            <h2 class="h6 text-uppercase text-muted mb-2">Invoice Info</h2>
            <table class="table table-sm mb-0">
              <tr><td class="text-muted">Invoice #</td><td class="text-end"><?= e($invoice['invoice_no'] ?? ('#'.$invoice['id'])) ?></td></tr>
              <tr><td class="text-muted">Invoice Date</td><td class="text-end"><?= e($invoice['invoice_date'] ?? '') ?></td></tr>
              <tr><td class="text-muted">Due Date</td><td class="text-end"><?= e($invoice['due_date'] ?? '') ?></td></tr>
              <tr><td class="text-muted">Status</td><td class="text-end"><?= badge_status_invoice((string)$invoice['status']) ?></td></tr>
            </table>
          </div>
        </div>
      </div>
    </div>

    <div class="card shadow-sm">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Line Items</h2>
        <div class="table-responsive">
          <table class="table align-middle">
            <thead class="table-light">
              <tr>
                <th style="width:48px;">#</th>
                <th>Description</th>
                <th class="text-end" style="width:120px;">Qty</th>
                <th class="text-end" style="width:140px;">Unit £</th>
                <th class="text-end" style="width:160px;">Line Total £</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($lines): foreach ($lines as $i => $ln): ?>
                <tr>
                  <td><?= (int)($i+1) ?></td>
                  <td><?= nl2br(e($ln['description'] ?? '—')) ?></td>
                  <td class="text-end"><?= number_format((float)($ln['quantity'] ?? 0), 0) ?></td>
                  <td class="text-end"><?= number_format((float)($ln['unit_price'] ?? 0), 2) ?></td>
                  <td class="text-end"><?= number_format((float)($ln['line_total'] ?? 0), 2) ?></td>
                </tr>
              <?php endforeach; else: ?>
                <tr><td colspan="5" class="text-muted">No line items.</td></tr>
              <?php endif; ?>
            </tbody>
            <tfoot>
              <tr><td colspan="3"></td><th class="text-end text-muted">Subtotal</th><th class="text-end"><?= n2($subtotal) ?></th></tr>
              <tr><td colspan="3"></td><th class="text-end text-muted">Discount</th><th class="text-end"><?= n2($discount) ?></th></tr>
              <tr><td colspan="3"></td><th class="text-end text-muted">VAT (<?= n2($vatRate) ?>%)</th><th class="text-end"><?= n2($vatAmt) ?></th></tr>
              <tr><td colspan="3"></td><th class="text-end">Total Due</th><th class="text-end"><?= n2($total) ?></th></tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>

    <?php if (!empty($invoice['notes'])): ?>
      <div class="card shadow-sm mt-3">
        <div class="card-body">
          <h2 class="h6 text-uppercase text-muted mb-2">Notes</h2>
          <div><?= nl2br(e((string)$invoice['notes'])) ?></div>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <div class="col-12 col-lg-4">
    <div class="card shadow-sm mb-3">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Summary</h2>
        <div class="p-2 border rounded bg-light">
          <div class="d-flex justify-content-between small"><div class="text-muted">Total</div><div>£ <?= n2($total) ?></div></div>
          <div class="d-flex justify-content-between small"><div class="text-muted">Paid</div><div>£ <?= n2($paid) ?></div></div>
          <div class="d-flex justify-content-between fw-bold"><div>Balance</div><div>£ <?= n2($balance) ?></div></div>
        </div>

        <div class="mt-3 d-grid gap-2">
          <a class="btn btn-outline-secondary" target="_blank" href="<?= e(url_modules('invoices/pdf.php').'?id='.(int)$invoice['id']) ?>">Download PDF</a>
          <a class="btn btn-outline-secondary" href="<?= e(url_modules('invoices/send.php').'?id='.(int)$invoice['id']) ?>">Send via Email</a>
        </div>
      </div>
    </div>

    <?php if ($booking): ?>
      <?php $pickupDT = trim(($booking['pickup_date'] ?? '').(empty($booking['pickup_time']) ? '' : (' '.$booking['pickup_time']))); ?>
      <div class="card shadow-sm">
        <div class="card-body">
          <h2 class="h6 text-uppercase text-muted mb-3">Linked Booking</h2>
          <div class="d-flex justify-content-between">
            <div>
              <div class="fw-bold"><?= e($booking['booking_ref'] ?? '—') ?></div>
              <div class="small text-muted"><?= e($booking['booking_type'] ?? 'Transfer') ?></div>
            </div>
            <div><a class="btn btn-sm btn-outline-secondary" href="<?= e(url_modules('bookings/edit.php').'?id='.(int)$booking['id']) ?>">Open</a></div>
          </div>
          <hr>
          <div class="small">
            <div><span class="text-muted">Client:</span> <?= e($booking['client_name'] ?? '—') ?><?php if (!empty($booking['client_phone'])): ?> • <?= e($booking['client_phone']) ?><?php endif; ?></div>
            <?php if (!empty($booking['client_email'])): ?><div class="text-muted"><?= e($booking['client_email']) ?></div><?php endif; ?>
            <div class="mt-2"><span class="text-muted">Pickup:</span> <?= e($pickupDT ?: '—') ?></div>
            <?php if (!empty($booking['pickup_address'])): ?><div><?= e($booking['pickup_address']) ?></div><?php endif; ?>
            <?php if (!empty($booking['via'])): ?><div><span class="text-muted">Via:</span> <?= e($booking['via']) ?></div><?php endif; ?>
            <?php if (!empty($booking['dropoff_address'])): ?><div><span class="text-muted">Dropoff:</span> <?= e($booking['dropoff_address']) ?></div><?php endif; ?>
            <?php if (!empty($booking['status'])): ?><div class="mt-2"><span class="text-muted">Status:</span> <?= e($booking['status']) ?></div><?php endif; ?>
          </div>
        </div>
      </div>
    <?php endif; ?>
  </div>
</div>

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