<?php
declare(strict_types=1);
/**
 * modules/invoices/pdf.php
 *
 * Elegant, professional A4 invoice PDF:
 *  - Watermark: "BROWNHILL GROUP LIMITED"
 *  - Logo from public/assets/logo.png (with safe fallbacks)
 *  - Clean layout: Company header, Bill To, Invoice Info
 *  - Line items grid + Totals
 *  - Payment Details in a styled card (bank info)
 *  - Journey Details: MULTI-BOOKING support via invoice_bookings; falls back to single booking (invoices.booking_id)
 *
 * Requirements provided by app bootstrap:
 *   - Helpers: db(), e(), require_role(), current_user(), url_public(), project_root()
 */

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

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) exit('Not authorized.');

$iid = (int)($_GET['id'] ?? $_GET['invoice_id'] ?? 0);
if ($iid <= 0) exit('Missing invoice id.');

/* ---------------- Small helpers ---------------- */
function currency_symbol(?string $code): string {
  $c = strtoupper((string)($code ?: 'GBP'));
  return ['GBP'=>'£','USD'=>'$','EUR'=>'€','AUD'=>'$','CAD'=>'$','NOK'=>'kr','SEK'=>'kr','DKK'=>'kr','JPY'=>'¥'][$c] ?? ($c.' ');
}
function app_setting(int $companyId, string $key): ?string {
  // Support either (key, value) or (setting_key, setting_value)
  try {
    $s = db()->prepare("SELECT value FROM settings WHERE company_id=:cid AND `key`=:k LIMIT 1");
    $s->execute([':cid'=>$companyId, ':k'=>$key]);
    if ($row = $s->fetch()) return (string)$row['value'];
  } catch (Throwable $e) {}
  try {
    $s = db()->prepare("SELECT setting_value FROM settings WHERE company_id=:cid AND setting_key=:k LIMIT 1");
    $s->execute([':cid'=>$companyId, ':k'=>$key]);
    if ($row = $s->fetch()) return (string)$row['setting_value'];
  } catch (Throwable $e) {}
  return null;
}
function best_logo_url(): ?string {
  // Priority: companies.logo_url → public/assets/logo.png → public/assets/images/logo.png
  try {
    $co = db()->prepare("SELECT logo_url FROM companies WHERE id=:id LIMIT 1");
    $co->execute([':id'=>(int)(current_user()['company_id'] ?? 0)]);
    $r = $co->fetch() ?: [];
    if (!empty($r['logo_url'])) return url_public((string)$r['logo_url']);
  } catch (Throwable $e) {}
  $candidates = ['assets/logo.png','public/assets/logo.png','assets/images/logo.png'];
  foreach ($candidates as $rel) {
    if (function_exists('project_root')) {
      $abs = rtrim(project_root(), '/').'/public/'.$rel;
      if (@is_file($abs)) return url_public($rel);
    }
  }
  // Last resort (won’t break HTML; mPDF just won’t render image if missing)
  return url_public('assets/logo.png');
}

/* ---------------- Company info (with safe fallbacks) ---------------- */
$coStmt = db()->prepare("SELECT * FROM companies WHERE id=:id LIMIT 1");
$coStmt->execute([':id' => $cid]);
$co = $coStmt->fetch() ?: [];

$brandName = trim((string)($co['name'] ?? '')) ?: 'Brownhill Group Limited';
$logoUrl   = best_logo_url();
$companyAddress = trim((string)($co['address'] ?? '')) ?: 'Suite 109, 4-6 Wadsworth Road, Perivale, UB6 7JJ, London, United Kingdom';
$companyPhone   = trim((string)($co['phone']   ?? '')) ?: '+44 208 064 2662';
$companyEmail   = trim((string)($co['email']   ?? '')) ?: 'info@brown-hillchauffeurs.co.uk';
$companyWeb     = trim((string)($co['website'] ?? '')) ?: 'www.brown-hillchauffeurs.co.uk';

$contactLine = implode(' • ', array_filter([
  $companyAddress,
  'Phone: '.$companyPhone,
  'Email: '.$companyEmail,
  'Website: '.$companyWeb
]));

/* ---------------- Invoice + lines ---------------- */
$inv = db()->prepare("SELECT * FROM invoices WHERE id=:id AND company_id=:cid LIMIT 1");
$inv->execute([':id' => $iid, ':cid' => $cid]);
$invoice = $inv->fetch();
if (!$invoice) exit('Invoice not found.');

$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();

/* ---------------- Journey Details (MULTI-BOOKING via invoice_bookings; fallback to invoices.booking_id) ---------------- */
$journeys = [];
// Preferred: invoice_bookings junction
$stJ = db()->prepare("
  SELECT
    ib.booking_id, ib.booking_ref, ib.amount_invoiced,
    b.client_name, b.client_phone, b.client_email,
    b.pickup_date, b.pickup_time, b.pickup_address, b.via, b.dropoff_address,
    b.flight_number,
    b.pax_count, b.luggage_count,
    b.total_client_price, b.client_parking_fee, b.client_waiting_fee,
    b.notes, b.status
  FROM invoice_bookings ib
  JOIN bookings b
    ON b.company_id = ib.company_id
   AND b.id = ib.booking_id
  WHERE ib.company_id = :cid
    AND ib.invoice_id = :iid
  ORDER BY COALESCE(b.pickup_date, b.created_at), b.id
");
try {
  $stJ->execute([':cid'=>$cid, ':iid'=>$iid]);
  $journeys = $stJ->fetchAll() ?: [];
} catch (Throwable $e) {
  $journeys = [];
}

// Legacy single-booking fallback
if (!$journeys && !empty($invoice['booking_id'])) {
  $bk = db()->prepare("
    SELECT
      b.id AS booking_id, b.booking_ref, 0.00 AS amount_invoiced,
      b.client_name, b.client_phone, b.client_email,
      b.pickup_date, b.pickup_time, b.pickup_address, b.via, b.dropoff_address,
      b.flight_number,
      b.pax_count, b.luggage_count,
      b.total_client_price, b.client_parking_fee, b.client_waiting_fee,
      b.notes, b.status
    FROM bookings b
    WHERE b.company_id = :cid
      AND b.id = :bid
    LIMIT 1
  ");
  $bk->execute([':cid'=>$cid, ':bid'=>(int)$invoice['booking_id']]);
  if ($one = $bk->fetch()) $journeys = [$one];
}

/* ---------------- Totals (use stored; backfill if needed) ---------------- */
$subtotal = (float)($invoice['subtotal_amount'] ?? 0.00);
$discount = (float)($invoice['discount_amount'] ?? 0.00);
$vatRate  = (float)($invoice['vat_rate'] ?? 0.00);
$vatAmt   = (float)($invoice['vat_amount'] ?? 0.00);
$total    = (float)($invoice['total_amount'] ?? 0.00);
$paid     = (float)($invoice['paid_total'] ?? 0.00);
$currency = (string)($invoice['currency'] ?? 'GBP');
$CUR      = currency_symbol($currency);

if ($subtotal <= 0.0) {
  $sum = 0.0;
  foreach ($lines as $ln) {
    $qty  = (float)($ln['quantity'] ?? 0);
    $unit = (float)($ln['unit_price'] ?? 0);
    $lt   = ($ln['line_total'] !== null && $ln['line_total'] !== '') ? (float)$ln['line_total'] : ($qty * $unit);
    $sum += $lt;
  }
  $subtotal = $sum;
  if ($total <= 0.0) {
    $base = max(0.0, $subtotal - $discount);
    $vatAmt = $vatRate > 0 ? round($base * ($vatRate / 100), 2) : 0.0;
    $total  = $base + $vatAmt;
  }
}
$balance    = max(0.0, $total - $paid);
$invoiceNo  = trim((string)($invoice['invoice_no'] ?? '')) ?: ('INV-'.$invoice['id']);
$invoiceDate= !empty($invoice['invoice_date']) ? (string)$invoice['invoice_date'] : date('Y-m-d');
$dueDate    = (string)($invoice['due_date'] ?? '');
$statusText = ucfirst((string)($invoice['status'] ?? 'draft'));

/* ---------------- Bank details (card) ----------------
 * Pull from settings if available; otherwise use Brownhill defaults.
 * Keys supported (either `key` or `setting_key` in `settings` table):
 *   bank_name, bank_account_name, bank_sort_code, bank_account_number, bank_iban, bank_swift, bank_note
 */
$bank = [
  'name'    => app_setting($cid, 'bank_name')           ?: 'NatWest',
  'accname' => app_setting($cid, 'bank_account_name')   ?: 'Brownhill Group Limited',
  'sort'    => app_setting($cid, 'bank_sort_code')      ?: '60-02-60',
  'accno'   => app_setting($cid, 'bank_account_number') ?: '10330593',
  'iban'    => app_setting($cid, 'bank_iban')           ?: 'GB20NWBK60026010330593',
  'swift'   => app_setting($cid, 'bank_swift')          ?: 'NWBKGB2L',
  'note'    => app_setting($cid, 'bank_note')           ?: 'Please use the invoice number as the payment reference.'
];

/* ---------------- Display helpers ---------------- */
function n2(float $v): string { return number_format($v, 2); }
function n0(float $v): string { return number_format($v, 0); }

/* ---------------- Build HTML ---------------- */
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= e($brandName) ?> - Invoice <?= e($invoiceNo) ?></title>
<style>
  :root{
    --border:#e5e7eb;
    --muted:#6b7280;
    --ink:#0f172a;
    --soft:#f8fafc;
    --chip:#eef2ff;
    --chipb:#e0e7ff;
    --brand:#111827;
  }
  *{ box-sizing:border-box; }
  body{ font-family: Arial, Helvetica, sans-serif; font-size:12px; color:var(--ink); margin:0; padding:16px; }
  .header{ display:flex; justify-content:space-between; align-items:flex-start; border-bottom:1px solid var(--border); padding-bottom:12px; margin-bottom:16px; }
  .brand{ display:flex; align-items:flex-start; gap:12px; }
  .brand .title{ font-size:22px; font-weight:800; color:var(--brand); letter-spacing:.2px; }
  .badge{ display:inline-block; font-size:11px; padding:4px 10px; border-radius:999px; background:var(--chip); color:#3730a3; border:1px solid var(--chipb); }
  .muted{ color:var(--muted); }
  .grid-2{ display:grid; grid-template-columns:1fr 1fr; gap:12px; }
  .box{ border:1px solid var(--border); border-radius:10px; padding:10px; background:#fff; }
  .box .h{ font-weight:700; margin-bottom:6px; border-bottom:1px solid var(--border); padding-bottom:6px; color:#0b1220; }
  table.kv{ width:100%; border-collapse:collapse; }
  table.kv td{ padding:6px 6px; vertical-align:top; }
  table.grid{ width:100%; border-collapse:collapse; }
  table.grid th, table.grid td{ border:1px solid var(--border); padding:7px 8px; text-align:left; vertical-align:top; }
  table.grid thead th{ background:var(--soft); font-weight:700; }
  .totals{ width:100%; border-collapse:collapse; margin-top:8px; }
  .totals td{ padding:6px 8px; }
  .card{ border:1px solid var(--border); border-radius:10px; padding:12px; background:#fff; }
  .pill{ display:inline-block; background:#f1f5f9; border:1px solid #e2e8f0; padding:2px 8px; border-radius:999px; font-size:11px; color:#0f172a; }
  .note{ margin-top:8px; font-size:11px; color:#374151; }
  .page-break{ page-break-before: always; }

  /* Journey Details styles */
  .jd-wrap { margin-top: 6px; }
  .jd-card { border:1px solid var(--border); border-radius:12px; padding:10px; margin-bottom:10px; }
  .jd-head { display:flex; justify-content:space-between; align-items:baseline; margin-bottom:6px; }
  .jd-ref { font-weight:700; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }
  .jd-dt { color:var(--muted); }
  .jd-grid { display:grid; grid-template-columns:1fr 1fr; gap:6px 14px; }
  .lbl { color:var(--muted); text-transform:uppercase; font-size:10px; letter-spacing:.04em; }
  .val { font-size:12px; }
</style>
</head>
<body>

  <!-- Header -->
  <div class="header">
    <div class="brand">
      <?php if ($logoUrl): ?><img src="<?= e($logoUrl) ?>" alt="Logo" height="56"><?php endif; ?>
      <div>
        <div class="title"><?= e($brandName) ?> — Invoice</div>
        <div class="muted"><?= e($contactLine) ?></div>
      </div>
    </div>
    <div style="text-align:right;">
      <div class="badge"><?= e($statusText) ?></div>
      <div class="muted" style="margin-top:8px; line-height:1.5;">
        <div>Invoice #: <strong><?= e($invoiceNo) ?></strong></div>
        <div>Date: <?= e($invoiceDate) ?></div>
        <?php if ($dueDate !== ''): ?><div>Due: <?= e($dueDate) ?></div><?php endif; ?>
        <div>Currency: <?= e($currency) ?></div>
      </div>
    </div>
  </div>

  <!-- Bill-to & Summary -->
  <div class="grid-2">
    <div class="box">
      <div class="h">Invoice To</div>
      <table class="kv">
        <tr><td class="muted" width="36%">Name</td><td><?= e($invoice['bill_to_name'] ?? '—') ?></td></tr>
        <?php if (!empty($invoice['bill_to_email'])): ?>
          <tr><td class="muted">Email</td><td><?= e($invoice['bill_to_email']) ?></td></tr>
        <?php endif; ?>
        <?php if (!empty($invoice['bill_to_address'])): ?>
          <tr><td class="muted">Address</td><td><?= nl2br(e((string)$invoice['bill_to_address'])) ?></td></tr>
        <?php endif; ?>
      </table>
    </div>
    <div class="box">
      <div class="h">Summary</div>
      <table class="kv">
        <tr><td class="muted" width="45%">Subtotal</td><td><?= e($CUR) ?> <?= n2($subtotal) ?></td></tr>
        <tr><td class="muted">Discount</td><td><?= e($CUR) ?> <?= n2($discount) ?></td></tr>
        <tr><td class="muted">VAT (<?= n2($vatRate) ?>%)</td><td><?= e($CUR) ?> <?= n2($vatAmt) ?></td></tr>
        <tr><td class="muted"><strong>Total</strong></td><td><strong><?= e($CUR) ?> <?= n2($total) ?></strong></td></tr>
        <tr><td class="muted">Paid</td><td><?= e($CUR) ?> <?= n2($paid) ?></td></tr>
        <tr><td class="muted">Balance</td><td><?= e($CUR) ?> <?= n2($balance) ?></td></tr>
      </table>
      <div class="note"><span class="pill">Reference</span> Please quote <strong><?= e($invoiceNo) ?></strong> in your payment.</div>
    </div>
  </div>

  <!-- Line Items -->
  <div class="box" style="margin-top:12px;">
    <div class="h">Line Items</div>
    <table class="grid">
      <thead>
        <tr>
          <th style="width:48px;">#</th>
          <th>Description</th>
          <th style="width:80px; text-align:right;">Qty</th>
          <th style="width:110px; text-align:right;">Unit (<?= e($CUR) ?>)</th>
          <th style="width:120px; text-align:right;">Line Total (<?= e($CUR) ?>)</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($lines): ?>
          <?php foreach ($lines as $i => $ln): ?>
            <?php
              $qty  = (float)($ln['quantity'] ?? 0);
              $unit = (float)($ln['unit_price'] ?? 0);
              $lt   = ($ln['line_total'] !== null && $ln['line_total'] !== '') ? (float)$ln['line_total'] : ($qty * $unit);
            ?>
            <tr>
              <td><?= (int)($i+1) ?></td>
              <td><?= nl2br(e($ln['description'] ?? '—')) ?></td>
              <td style="text-align:right;"><?= n0($qty) ?></td>
              <td style="text-align:right;"><?= n2($unit) ?></td>
              <td style="text-align:right;"><?= n2($lt) ?></td>
            </tr>
          <?php endforeach; ?>
        <?php else: ?>
          <tr><td colspan="5" class="muted">No line items.</td></tr>
        <?php endif; ?>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="3"></td>
          <th style="text-align:right;" class="muted">Subtotal</th>
          <th style="text-align:right;"><?= e($CUR) ?> <?= n2($subtotal) ?></th>
        </tr>
        <tr>
          <td colspan="3"></td>
          <th style="text-align:right;" class="muted">Discount</th>
          <th style="text-align:right;"><?= e($CUR) ?> <?= n2($discount) ?></th>
        </tr>
        <tr>
          <td colspan="3"></td>
          <th style="text-align:right;" class="muted">VAT (<?= n2($vatRate) ?>%)</th>
          <th style="text-align:right;"><?= e($CUR) ?> <?= n2($vatAmt) ?></th>
        </tr>
        <tr>
          <td colspan="3"></td>
          <th style="text-align:right;">Total Due</th>
          <th style="text-align:right;"><?= e($CUR) ?> <?= n2($total) ?></th>
        </tr>
      </tfoot>
    </table>
  </div>

  <!-- Payment Details (Bank) -->
  <div class="card" style="margin-top:12px;">
    <div style="font-weight:700; margin-bottom:6px;">Payment Details</div>
    <table class="kv">
      <tr><td class="muted" width="32%">Bank</td><td><?= e($bank['name']) ?></td></tr>
      <tr><td class="muted">Account Name</td><td><?= e($bank['accname']) ?></td></tr>
      <tr><td class="muted">Sort Code</td><td><?= e($bank['sort']) ?></td></tr>
      <tr><td class="muted">Account Number</td><td><?= e($bank['accno']) ?></td></tr>
      <tr><td class="muted">IBAN</td><td><?= e($bank['iban']) ?></td></tr>
      <tr><td class="muted">SWIFT</td><td><?= e($bank['swift']) ?></td></tr>
    </table>
    <?php if (!empty($bank['note'])): ?>
      <div class="note"><?= nl2br(e($bank['note'])) ?></div>
    <?php endif; ?>
  </div>

  <?php if (!empty($invoice['notes'])): ?>
    <div class="box" style="margin-top:12px;">
      <div class="h">Notes</div>
      <div><?= nl2br(e((string)$invoice['notes'])) ?></div>
    </div>
  <?php endif; ?>

  <!-- Page 2+: Journey details -->
  <div class="page-break"></div>
  <div class="box">
    <div class="h">Journey Details</div>

    <?php if ($journeys): ?>
      <div class="jd-wrap">
        <?php foreach ($journeys as $j): ?>
          <?php
            $ref   = (string)($j['booking_ref'] ?? '');
            $pd    = (string)($j['pickup_date'] ?? '');
            $pt    = (string)($j['pickup_time'] ?? '');
            $fromA = trim((string)($j['pickup_address'] ?? ''));
            $via   = trim((string)($j['via'] ?? ''));
            $toA   = trim((string)($j['dropoff_address'] ?? ''));
            $cli   = trim((string)($j['client_name'] ?? ''));
            $cph   = trim((string)($j['client_phone'] ?? ''));
            $cem   = trim((string)($j['client_email'] ?? ''));
            $flt   = trim((string)($j['flight_number'] ?? ''));
            $pax   = (int)($j['pax_count'] ?? 0);
            $lug   = (int)($j['luggage_count'] ?? 0);
            $base  = (float)($j['total_client_price'] ?? 0);
            $pf    = (float)($j['client_parking_fee'] ?? 0);
            $wf    = (float)($j['client_waiting_fee'] ?? 0);
            $notes = trim((string)($j['notes'] ?? ''));
            $stat  = (string)($j['status'] ?? '');
          ?>
          <div class="jd-card">
            <div class="jd-head">
              <div class="jd-ref"><?= e($ref ?: '—') ?></div>
              <div class="jd-dt"><?= e(trim($pd.' '.($pt ?: ''))) ?></div>
            </div>

            <div class="jd-grid">
              <div>
                <div class="lbl">Client</div>
                <div class="val"><?= e($cli ?: '—') ?></div>
                <?php if ($cph): ?><div class="val" style="font-size:11px;"><?= e($cph) ?></div><?php endif; ?>
                <?php if ($cem): ?><div class="val" style="font-size:11px;"><?= e($cem) ?></div><?php endif; ?>
              </div>

              <div>
                <div class="lbl">Flight</div>
                <div class="val"><?= e($flt ?: '—') ?></div>
              </div>

              <div>
                <div class="lbl">Pickup</div>
                <div class="val"><?= e($fromA ?: '—') ?></div>
              </div>

              <div>
                <div class="lbl">Dropoff</div>
                <div class="val"><?= e($toA ?: '—') ?></div>
              </div>

              <?php if ($via): ?>
                <div>
                  <div class="lbl">Via</div>
                  <div class="val"><?= e($via) ?></div>
                </div>
              <?php endif; ?>

              <div>
                <div class="lbl">Party</div>
                <div class="val">Pax <?= (int)$pax ?> • Luggage <?= (int)$lug ?></div>
              </div>
            </div>

            <div style="height:8px;"></div>

            <div class="jd-grid">
              <div>
                <div class="lbl">Charges (Client)</div>
                <div class="val">
                  <?php
                    $bits = [];
                    if ($base > 0) $bits[] = "Base £".n2($base);
                    if ($pf   > 0) $bits[] = "Parking £".n2($pf);
                    if ($wf   > 0) $bits[] = "Waiting £".n2($wf);
                    echo $bits ? e(implode('  •  ', $bits)) : '<span class="muted">—</span>';
                  ?>
                </div>
              </div>
              <div>
                <div class="lbl">Status</div>
                <div class="val"><?= e($stat ?: '—') ?></div>
              </div>
            </div>

            <?php if ($notes): ?>
              <div style="height:8px;"></div>
              <div>
                <div class="lbl">Notes</div>
                <div class="val" style="white-space:pre-line;"><?= nl2br(e($notes)) ?></div>
              </div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    <?php else: ?>
      <div class="muted">No booking details for this invoice.</div>
    <?php endif; ?>
  </div>

</body>
</html>
<?php
$html = ob_get_clean();

/* ---------------- Output via mPDF (fallback to HTML) ---------------- */
if (!class_exists('\\Mpdf\\Mpdf')) {
  header('Content-Type: text/html; charset=utf-8');
  echo $html; exit;
}

$mpdf = new \Mpdf\Mpdf([
  'format'        => 'A4',
  'margin_left'   => 12,
  'margin_right'  => 12,
  'margin_top'    => 12,
  'margin_bottom' => 14,
]);

$mpdf->SetTitle('Invoice - ' . $invoiceNo);
$mpdf->SetAuthor($brandName);

/* Watermark — UPPERCASE exactly as requested */
$mpdf->SetWatermarkText('BROWNHILL GROUP LIMITED', 0.08); // 8% opacity-ish
$mpdf->showWatermarkText = true;

$mpdf->WriteHTML($html);
$filename = 'invoice_' . preg_replace('/[^A-Za-z0-9_\-]/', '_', $invoiceNo) . '.pdf';
$mpdf->Output($filename, 'I');
