<?php
declare(strict_types=1);
/**
 * modules/bookings/pdf.php
 *
 * Journey Confirmation (A4)
 * - Title: "<CompanyName or Brown Hill Chauffeurs> - Journey Confirmation"
 * - Client details
 * - Journey details
 * - Driver details
 * - Vehicle details
 *
 * Prices are intentionally omitted.
 * Supports driver "own vehicle" via booking_vehicles.vehicle_reg_no/vehicle_type (free text)
 * with COALESCE against vehicles table when vehicle_id is present.
 */

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

$cid = current_user()['company_id'] ?? null; if (!$cid) exit('No company.');
$bid = (int)($_GET['booking_id'] ?? 0);      if ($bid <= 0) exit('No booking.');

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

$brandName  = trim($co['name'] ?? '') ?: 'Brown Hill Chauffeurs';
$logo       = !empty($co['logo_url']) ? url_public($co['logo_url']) : null;
$watermark  = $brandName;

/* ---- Contact line (explicit values as requested) ----
   Edit the three variables below to change the footer contact info. */
$city       = trim((string)($co['city'] ?? ''));
$country    = trim((string)($co['country'] ?? ''));
$cityCountry = $city && $country ? "$city, $country" : 'London, United Kingdom';

$contactPhone    = '+44208 064 2662';
$contactEmail    = 'info@brown-hillchauffeurs.co.uk';
$contactWhatsApp = '+44 7877 622145';

/* ---------------- Booking ---------------- */
$bookingStmt = 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 = :id AND b.company_id = :cid
  LIMIT 1
");
$bookingStmt->execute([':id' => $bid, ':cid' => $cid]);
$b = $bookingStmt->fetch();
if (!$b) exit('Booking not found.');

/* ---------------- Assignments (drivers & vehicles) ----------------
 * Use COALESCE to ensure own-vehicle free-text is used when present.
 */
$bvStmt = db()->prepare("
  SELECT
    bv.sequence_order,
    d.name  AS driver_name,
    d.phone AS driver_phone,
    COALESCE(bv.vehicle_reg_no, v.reg_no) AS reg_no,
    COALESCE(bv.vehicle_type,   v.type)   AS vehicle_type
  FROM booking_vehicles bv
  LEFT JOIN drivers  d ON d.id = bv.driver_id
  LEFT JOIN vehicles v ON v.id = bv.vehicle_id
  WHERE bv.booking_id = :bid
  ORDER BY bv.sequence_order
");
$bvStmt->execute([':bid' => $bid]);
$assignments = $bvStmt->fetchAll();

/* ---------------- Helpers ---------------- */
$pickupDT = trim(
  ($b['pickup_date'] ?? '') .
  (($b['pickup_time'] ?? '') !== '' ? ' ' . $b['pickup_time'] : '')
);
$adType = ($b['booking_type'] ?? '') === 'As Directed'
  ? 'As Directed' . ($b['hours'] ? ' (' . (float)$b['hours'] . 'h)' : '')
  : ($b['booking_type'] ?? '—');

/* ---------------- Build HTML ---------------- */
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= e($brandName) ?> - Journey Confirmation</title>
<style>
  :root {
    --border:#e5e7eb;
    --muted:#6b7280;
    --text:#111827;
    --heading:#0f172a;
    --soft:#f8fafc;
  }
  * { box-sizing: border-box; }
  body { font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: var(--text); margin: 0; padding: 18px; }
  .header {
    display:flex; justify-content:space-between; align-items:center;
    border-bottom:1px solid var(--border); padding-bottom:10px; margin-bottom:14px;
  }
  .brand {
    display:flex; align-items:center; gap:10px;
  }
  .brand .title { font-size: 20px; font-weight: 700; color: var(--heading); }
  .muted { color: var(--muted); }
  .pill {
    display:inline-block; font-size:11px; padding:3px 8px; border-radius:999px; background:#eef2ff; color:#3730a3; border:1px solid #e0e7ff;
  }
  .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:4px; color:var(--heading); }
  table.kv { width:100%; border-collapse:collapse; }
  table.kv td { padding:5px 6px; vertical-align:top; }
  table.grid { width:100%; border-collapse:collapse; }
  table.grid th, table.grid td { border:1px solid var(--border); padding:6px 8px; text-align:left; }
  table.grid thead th { background: var(--soft); font-weight:700; }
  .footer-note { margin-top:14px; font-size:11px; color:var(--muted); text-align:center; }
</style>
</head>
<body>

  <div class="header">
    <div class="brand">
      <?php if ($logo): ?><img src="<?= e($logo) ?>" alt="Logo" height="42"><?php endif; ?>
      <div>
        <div class="title"><?= e($brandName) ?> - Journey Confirmation</div>
        <div class="muted">
          Ref: <strong><?= e($b['booking_ref'] ?? '—') ?></strong>
          <?php if ($pickupDT): ?> • Pickup: <?= e($pickupDT) ?><?php endif; ?>
          <?php if (!empty($b['partner_name'])): ?> • Partner: <?= e($b['partner_name']) ?><?php endif; ?>
        </div>
      </div>
    </div>
    <div>
      <?php if (!empty($b['status'])): ?><span class="pill"><?= e($b['status']) ?></span><?php endif; ?>
    </div>
  </div>

  <div class="grid-2">
    <!-- Client Details -->
    <div class="box">
      <div class="h">Client Details</div>
      <table class="kv">
        <tr><td class="muted" width="35%">Name</td><td><?= e($b['client_name'] ?? '—') ?></td></tr>
        <tr><td class="muted">Phone</td><td><?= e($b['client_phone'] ?? '—') ?></td></tr>
        <tr><td class="muted">Email</td><td><?= e($b['client_email'] ?? '—') ?></td></tr>
        <tr><td class="muted">Passengers / Luggage</td><td><?= (int)($b['pax_count'] ?? 0) ?> / <?= (int)($b['luggage_count'] ?? 0) ?></td></tr>
        <tr><td class="muted">Flight No.</td><td><?= e($b['flight_number'] ?? '—') ?></td></tr>
      </table>
    </div>

    <!-- Journey Details -->
    <div class="box">
      <div class="h">Journey Details</div>
      <table class="kv">
        <tr><td class="muted" width="35%">Type</td><td><?= e($adType) ?></td></tr>
        <tr><td class="muted">Pickup</td>
            <td><?= e($pickupDT) ?><?= !empty($b['pickup_address']) ? ' | ' . e($b['pickup_address']) : '' ?></td></tr>
        <tr><td class="muted">Via</td><td><?= e($b['via'] ?? '—') ?></td></tr>
        <tr><td class="muted">Dropoff</td><td><?= e($b['dropoff_address'] ?? '—') ?></td></tr>
        <tr><td class="muted">Notes</td><td><?= nl2br(e($b['notes'] ?? '—')) ?></td></tr>
      </table>
    </div>
  </div>

  <!-- Driver Details -->
  <div class="box" style="margin-top:12px;">
    <div class="h">Driver Details</div>
    <table class="grid">
      <thead>
        <tr>
          <th style="width:10%;">#</th>
          <th>Driver Name</th>
          <th>Phone</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($assignments): ?>
          <?php foreach ($assignments as $i => $row): ?>
            <tr>
              <td><?= (int)$row['sequence_order'] ?: ($i+1) ?></td>
              <td><?= e($row['driver_name'] ?? '—') ?></td>
              <td><?= e($row['driver_phone'] ?? '—') ?></td>
            </tr>
          <?php endforeach; ?>
        <?php else: ?>
          <tr><td>1</td><td>—</td><td>—</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- Vehicle Details -->
  <div class="box" style="margin-top:12px;">
    <div class="h">Vehicle Details</div>
    <table class="grid">
      <thead>
        <tr>
          <th style="width:10%;">#</th>
          <th>Registration</th>
          <th>Type</th>
        </tr>
      </thead>
      <tbody>
        <?php if ($assignments): ?>
          <?php foreach ($assignments as $i => $row): ?>
            <tr>
              <td><?= (int)$row['sequence_order'] ?: ($i+1) ?></td>
              <td><?= e($row['reg_no'] ?? '—') ?></td>
              <td><?= e($row['vehicle_type'] ?? '—') ?></td>
            </tr>
          <?php endforeach; ?>
        <?php else: ?>
          <tr><td>1</td><td>—</td><td>—</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- Contact line (no duplication) -->
  <div class="footer-note">
    <?= e($cityCountry) ?> • Tel: <?= e($contactPhone) ?> • Email: <?= e($contactEmail) ?> • WhatsApp: <?= e($contactWhatsApp) ?>
  </div>

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

/* ---------------- Output via mPDF (fallback to HTML if library missing) ---------------- */
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' => 12,
]);

$mpdf->SetTitle('Journey Confirmation - ' . ($b['booking_ref'] ?? 'Booking'));
$mpdf->SetAuthor($brandName);
$mpdf->SetWatermarkText($watermark);
$mpdf->showWatermarkText = true;

$mpdf->WriteHTML($html);
$filename = 'journey_confirmation_' . preg_replace('/[^A-Za-z0-9_\-]/', '_', (string)($b['booking_ref'] ?? 'booking')) . '.pdf';
$mpdf->Output($filename, 'I');
