<?php
declare(strict_types=1);
/**
 * modules/quotes/pdf.php
 *
 * Professional quote PDF (A4) with:
 *  - Brand header (logo + company contact)
 *  - Quote header (ref/date/status)
 *  - Client details & Company details
 *  - Line items with totals & discount
 *  - Notes
 *  - T&Cs (from settings.key='quote_terms') on a separate page
 *  - Watermark from settings.key='quote_watermark' or brand name
 *
 * LOGO UPLOAD PATH PREFERENCE (in this order):
 *   1) companies.logo_url (absolute or relative in /public)
 *   2) /public/uploads/branding/logo.png   <-- RECOMMENDED: upload here
 *   3) /public/assets/images/logo.png
 */

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

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

$qid = (int)($_GET['id'] ?? $_GET['quote_id'] ?? 0);
if ($qid <= 0) exit('Missing quote id.');

/* ---------------- Company (branding) ----------------
 * Defaults for all PDFs (used if DB fields are empty)
 */
$DEFAULT_CO = [
  'name'    => 'Brownhill Group Limited',
  'phone'   => '+44 208 064 2662',
  'email'   => 'info@brown-hillchauffeurs.co.uk',
  'website' => 'www.brown-hillchauffeurs.co.uk',
  'address' => 'Suite 109, 4-6 Wadsworth Road, Perivale, UB6 7JJ London United Kingdom',
];

$coStmt = db()->prepare("SELECT * FROM companies WHERE id = :id LIMIT 1");
$coStmt->execute([':id' => $cid]);
$coRow = $coStmt->fetch() ?: [];

$brandName = trim((string)($coRow['name'] ?? '')) ?: $DEFAULT_CO['name'];
$phone     = trim((string)($coRow['phone'] ?? '')) ?: $DEFAULT_CO['phone'];
$email     = trim((string)($coRow['email'] ?? '')) ?: $DEFAULT_CO['email'];
$website   = trim((string)($coRow['website'] ?? '')) ?: $DEFAULT_CO['website'];
$address   = trim((string)($coRow['address'] ?? '')) ?: $DEFAULT_CO['address'];

/* Resolve logo URL:
 * 1) companies.logo_url (relative under /public or full URL)
 * 2) /public/uploads/branding/logo.png (recommended place to upload)
 * 3) /public/assets/images/logo.png
 */
$logoUrl = null;
if (!empty($coRow['logo_url'])) {
  // Assume relative path inside /public OR absolute
  $logoUrl = str_starts_with((string)$coRow['logo_url'], 'http')
    ? (string)$coRow['logo_url']
    : url_public((string)$coRow['logo_url']);
} else {
  $cand1 = project_root() . '/public/uploads/branding/logo.png';
  $cand2 = project_root() . '/public/assets/images/logo.png';
  if (is_file($cand1)) {
    $logoUrl = url_public('uploads/branding/logo.png');
  } elseif (is_file($cand2)) {
    $logoUrl = url_public('assets/images/logo.png');
  }
}

/* ---------------- Quote ---------------- */
$qStmt = db()->prepare("
  SELECT q.*,
         p.name AS partner_name,
         c.name AS corporate_name
    FROM quotes q
    LEFT JOIN partners  p ON p.id = q.partner_id
    LEFT JOIN corporates c ON c.id = q.corporate_id
   WHERE q.id = :id AND q.company_id = :cid
   LIMIT 1
");
$qStmt->execute([':id' => $qid, ':cid' => $cid]);
$quote = $qStmt->fetch();
if (!$quote) exit('Quote not found.');

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

/* ---------------- Totals ---------------- */
$subTotal = 0.0;
foreach ($lines as $ln) {
  $qty  = (int)($ln['quantity'] ?? 1);
  $unit = (float)($ln['unit_price'] ?? 0);
  $lt   = ($ln['line_total'] ?? '') !== '' ? (float)$ln['line_total'] : ($qty * $unit);
  $subTotal += $lt;
}
$discount = (float)($quote['discount'] ?? 0.0);
$grand    = max(0.0, $subTotal - $discount);

/* ---------------- Terms & Conditions (from settings) ---------------- */
/* ---------------- Terms & Conditions (from settings) ---------------- */
$terms = '';
try {
  // Preferred source: settings table (key='quote_terms')
  $s = db()->prepare("SELECT value FROM settings WHERE company_id=:cid AND `key`='quote_terms' LIMIT 1");
  $s->execute([':cid' => $cid]);
  $row = $s->fetch();
  if ($row && isset($row['value']) && trim((string)$row['value']) !== '') {
    $terms = (string)$row['value'];
  }
} catch (Throwable $e) { /* ignore and try file fallback */ }

if ($terms === '') {
  // File fallback: place your T&Cs as HTML or plain text in either path below
  $candidates = [
    project_root().'/public/uploads/branding/quote_terms.html',
    project_root().'/public/uploads/branding/quote_terms.txt',
  ];
  foreach ($candidates as $path) {
    if (is_file($path)) {
      $buf = @file_get_contents($path);
      if (is_string($buf) && trim($buf) !== '') {
        $terms = $buf;
        break;
      }
    }
  }
}

if ($terms === '') {
// Final hardcoded fallback — Brownhill Group Limited T&Cs (full version)
$terms = <<<TEXT
BROWNHILL GROUP LIMITED — TERMS & CONDITIONS

**1) User Responsibilities**  
You are responsible for:  
- Providing accurate information when generating a quotation.  
- Notifying us immediately of any changes in your booking details.  

---

**2) Waiting Time Charges**  
Complimentary waiting time:  
- Airport pickups (inbound): 60 minutes  
- All other pickups (outbound): 15 minutes  

Includes:  
- Meet & greet  
- Flight monitoring  
- Onboard Wi-Fi (Business & First Class Chauffeured vehicles)  
- Bottled water (Business & First Class Chauffeured vehicles)  
- Luggage assistance by chauffeur  
- Chauffeur monitored by the company  

*If your flight is delayed, we will check the flight information in advance and adjust your pickup time accordingly.  
In the case of connecting flights, please note we can only check the flight details printed on this voucher.*  

Waiting time exceeding complimentary limits will be charged as follows (per hour):  
- Business Sedan: £50  
- First Class Sedan: £55  
- Business Van: £55  
- Economy Sedan: £40  
- Economy Van (MPV5): £45  
- Economy Mini Bus: £50  

---

**3) Airport Parking Charges**  
Airport parking charges will apply in addition to the booking fee. Passengers may choose one of the following payment options:  

- **Cash Payment:** Paid directly to the driver in cash at the end of the journey.  
- **Online Payment:** The Company will provide a secure payment link for parking charges.  

The driver will provide the passenger with the original parking receipt as confirmation of the incurred charges.  

---

**4) Congestion Charges**  
If the journey goes through a congestion zone, the £7.50 charge will be paid by the client.  

---

**5) Additional Drop-off Charges**  
- Business Sedan: £10  
- First Class Sedan: £15  
- Business Van: £15  
- Economy Sedan: £7  
- Economy Van (MPV5): £9  
- Economy Mini Bus: £12  

---

**6) Cancellation Policy**  
- You can cancel your booking free of charge if you notify us at least 24 hours before the scheduled pick-up time.  
- Cancellations made within 24 hours will be charged the full service fee.  

---

**7) Driver Information**  
Driver details will be provided to you via email 12 hours before your service time.  

---

**8) Arrival Meeting Point**  
For airport arrivals, our chauffeur driver will greet you in the arrival hall holding a sign with your name.  

---

**9) Departure Meeting Point**  
For hotel departures, you will be picked up at the main lobby.  

---

**10) Payment**  
**Payment Methods:**  
All payments shall be made by payment link, BACS, or direct credit transfer to the bank account details provided on the invoice, quoting the specified payment reference.  
- If the client uses the payment link, a 3% charge will be added to the invoice.  
- Bank transfers have no extra fees.  

**Late Payment:**  
In the event of late payment, the Company reserves the right to:  
- Charge interest on the overdue amount at 1% per month (calculated daily) until full payment is received; and/or  
- Suspend or withhold further services until all overdue amounts are settled in full.  

*This applies to both individual car-hire services and FIT/Group services operated by minibuses/coaches.*  

---

**11) Disclaimer**  
The final service fee may vary slightly based on unforeseen circumstances.  
Brown Hill Chauffeurs is not liable for delays caused by factors beyond our control (e.g., traffic congestion).  

---

**12) Modifications to Terms & Conditions**  
Brown Hill Chauffeurs reserves the right to modify these terms and conditions at any time.  
Any changes will be communicated to you promptly.  

---

**13) Contact Us**  
If you have any questions regarding these Terms, please contact us:  
Phone: +44 (0)208 064 2662  
Email: info@brown-hillchauffeurs.co.uk  
Website: www.brown-hillchauffeurs.co.uk  

© Brownhill Group Limited. All rights reserved.
TEXT;
}


/* ---------------- Watermark (optional override) ---------------- */
$watermark = $brandName;
try {
  $ws = db()->prepare("SELECT value FROM settings WHERE company_id=:cid AND `key`='quote_watermark' LIMIT 1");
  $ws->execute([':cid' => $cid]);
  $wrow = $ws->fetch();
  $wmSet = isset($wrow['value']) ? trim((string)$wrow['value']) : '';
  if ($wmSet !== '') $watermark = $wmSet;
} catch (Throwable $e) { /* ignore */ }

/* ---------------- Display helpers ---------------- */
$quoteRef   = trim((string)($quote['quote_ref'] ?? '')) ?: ('Q-' . $qid);
$quoteDate  = !empty($quote['quote_date']) ? (string)$quote['quote_date'] : date('Y-m-d');
$statusText = ucfirst((string)($quote['status'] ?? 'draft'));

/* ---------------- Build HTML ---------------- */
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= e($brandName) ?> - Quote <?= e($quoteRef) ?></title>
<style>
  :root{
    --border:#e5e7eb;
    --muted:#6b7280;
    --text:#111827;
    --heading:#0f172a;
    --soft:#f8fafc;
    --primary:#0b3b6a;
  }
  *{ box-sizing:border-box; }
  body{ font-family: Arial, Helvetica, sans-serif; font-size:12px; color:var(--text); margin:0; padding:18px; }

  /* Header */
  .header{ display:flex; justify-content:space-between; gap:18px; align-items:center; border-bottom:2px solid var(--border); padding-bottom:12px; margin-bottom:16px; }
  .brand{ display:flex; gap:12px; align-items:center; }
  .brand .title{ font-size:24px; font-weight:800; color:var(--primary); letter-spacing:.3px; }
  .brand img{ display:block; }

  .contact{
    text-align:right; font-size:11px; line-height:1.4;
    color:#374151;
  }
  .contact .name{ font-weight:700; color:#111827; font-size:13px; }

  .muted{ color:var(--muted); }
  .pill{ display:inline-block; font-size:11px; padding:4px 10px; border-radius:999px; background:#e6f0ff; color:#0b3b6a; border:1px solid #c7dcff; }

  .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:8px; border-bottom:1px solid var(--border); padding-bottom:6px; color:var(--heading); }

  table.kv{ width:100%; border-collapse:collapse; }
  table.kv td{ padding:6px 8px; vertical-align:top; }

  table.grid{ width:100%; border-collapse:collapse; margin-top:6px; }
  table.grid th, table.grid td{ border:1px solid var(--border); padding:8px 10px; text-align:left; vertical-align:top; }
  table.grid thead th{ background:#f3f6fb; font-weight:700; }

  .totals{ width:100%; border-collapse:collapse; margin-top:10px; }
  .totals td{ padding:6px 8px; }
  .totals .lbl{ text-align:right; color:#374151; }
  .totals .amt{ text-align:right; font-weight:700; }

  .note{ font-size:11px; color:#374151; }

  .footer-note{ margin-top:14px; font-size:11px; color:var(--muted); }

  .page-break{ page-break-before: always; }
  .terms{ white-space:pre-wrap; font-size:11px; color:#374151; line-height:1.5; }
</style>
</head>
<body>

  <div class="header">
    <div class="brand">
      <?php if ($logoUrl): ?><img src="<?= e($logoUrl) ?>" alt="Logo" height="54"><?php endif; ?>
      <div>
        <div class="title">QUOTE</div>
        <div class="muted">
          Ref: <strong><?= e($quoteRef) ?></strong> •
          Date: <?= e($quoteDate) ?>
          <?php if (!empty($quote['partner_name'])): ?> • Partner: <?= e($quote['partner_name']) ?><?php endif; ?>
          <?php if (!empty($quote['corporate_name'])): ?> • Corporate: <?= e($quote['corporate_name']) ?><?php endif; ?>
        </div>
      </div>
    </div>
    <div class="contact">
      <div class="name"><?= e($brandName) ?></div>
      <div><?= e($address) ?></div>
      <div>Tel: <?= e($phone) ?></div>
      <div>Email: <?= e($email) ?></div>
      <div>Web: <?= e($website) ?></div>
      <div style="margin-top:6px;"><?php if (!empty($statusText)): ?><span class="pill"><?= e($statusText) ?></span><?php endif; ?></div>
    </div>
  </div>

  <div class="grid-2">
    <div class="box">
      <div class="h">Client</div>
      <table class="kv">
        <tr><td class="muted" width="35%">Name</td><td><?= e($quote['client_name'] ?? '—') ?></td></tr>
        <tr><td class="muted">Email</td><td><?= e($quote['client_email'] ?? '—') ?></td></tr>
        <tr><td class="muted">Reference</td><td><?= e($quoteRef) ?></td></tr>
      </table>
    </div>
    <div class="box">
      <div class="h">Company</div>
      <table class="kv">
        <tr><td class="muted" width="35%">Company</td><td><?= e($brandName) ?></td></tr>
        <tr><td class="muted">Address</td><td><?= nl2br(e($address)) ?></td></tr>
        <tr><td class="muted">Phone</td><td><?= e($phone) ?></td></tr>
        <tr><td class="muted">Email</td><td><?= e($email) ?></td></tr>
        <tr><td class="muted">Website</td><td><?= e($website) ?></td></tr>
      </table>
    </div>
  </div>

  <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 £</th>
          <th style="width:120px; text-align:right;">Line Total £</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($lines): ?>
          <?php foreach ($lines as $i => $ln):
            $qty  = (int)($ln['quantity'] ?? 1);
            $unit = (float)($ln['unit_price'] ?? 0);
            $lt   = ($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;"><?= number_format($qty, 0) ?></td>
            <td style="text-align:right;"><?= number_format($unit, 2) ?></td>
            <td style="text-align:right;"><?= number_format($lt, 2) ?></td>
          </tr>
          <?php endforeach; ?>
        <?php else: ?>
          <tr><td colspan="5" class="muted">No items.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>

    <table class="totals">
      <tr>
        <td style="width:60%;"></td>
        <td class="lbl" style="width:20%;">Subtotal</td>
        <td class="amt" style="width:20%;"><?= number_format($subTotal, 2) ?></td>
      </tr>
      <tr>
        <td></td>
        <td class="lbl">Discount</td>
        <td class="amt"><?= number_format($discount, 2) ?></td>
      </tr>
      <tr>
        <td></td>
        <td class="lbl"><strong>Grand Total</strong></td>
        <td class="amt"><strong><?= number_format($grand, 2) ?></strong></td>
      </tr>
    </table>
  </div>

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

  <div class="page-break"></div>
  <div class="box">
    <div class="h">Terms &amp; Conditions</div>
    <div class="terms"><?= nl2br(e($terms)) ?></div>
  </div>

  <div class="footer-note">
    <?= e($address) ?> • Tel: <?= e($phone) ?> • Email: <?= e($email) ?> • Web: <?= e($website) ?>
  </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('Quote - ' . $quoteRef);
$mpdf->SetAuthor($brandName);
$mpdf->SetWatermarkText($watermark);
$mpdf->showWatermarkText = true;

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