<?php
// GET /api/jobcards/pdf.php?job_card_id=X&type=client|internal&token=XXX
// GET /api/jobcards/pdf.php?pdf_token=XXX  (public client link from emails)
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$token = $_GET['token'] ?? '';
$pdfToken = $_GET['pdf_token'] ?? '';

if ($pdfToken) {
  // Public PDF access token — no login required, type locked to token record
  $db = getDB();
  $pts = $db->prepare("SELECT * FROM pdf_access_tokens WHERE token = ? AND expires_at > NOW() LIMIT 1");
  $pts->execute([$pdfToken]);
  $ptRow = $pts->fetch();
  if (!$ptRow) {
    http_response_code(403);
    die('This link has expired or is invalid. Please contact us for a new copy.');
  }
  // Force job_card_id and type from the token — cannot be overridden by GET params
  $_GET['job_card_id'] = $ptRow['job_card_id'];
  $_GET['type'] = $ptRow['type']; // always 'client' for email links
  $user = ['id' => 0, 'role_id' => 0, 'full_name' => 'Public'];
} elseif ($token) {
  $db = getDB();
  $ts = $db->prepare("SELECT u.id, u.role_id, u.full_name, u.email FROM user_tokens ut JOIN users u ON u.id = ut.user_id WHERE ut.token = ? AND ut.expires_at > NOW() AND u.is_active = 1");
  $ts->execute([$token]);
  $tokenUser = $ts->fetch();
  if (!$tokenUser) {
    http_response_code(401);
    die('Unauthorised');
  }
  $user = $tokenUser;
} else {
  $user = requireAuth();
}

$db = getDB();
$jobCardId = (int) ($_GET['job_card_id'] ?? 0);
$type = $_GET['type'] ?? 'client'; // client | internal
if (!$jobCardId)
  die('Job card ID required');

// ── Fetch all data ───────────────────────────────────────────
$stmt = $db->prepare("
    SELECT jc.*, c.company_name AS client_name, c.vat_no AS client_vat,
           u.full_name AS assigned_name,
           v.registration AS vehicle_reg, v.make AS vehicle_make, v.model AS vehicle_model,
           v.cost_per_km, v.quote_rate_per_km
    FROM job_cards jc
    LEFT JOIN clients c ON c.id = jc.client_id
    LEFT JOIN users u ON u.id = jc.assigned_to
    LEFT JOIN fleet_vehicles v ON v.id = jc.vehicle_id
    WHERE jc.id = ?
");
$stmt->execute([$jobCardId]);
$jc = $stmt->fetch();
if (!$jc)
  die('Job card not found');

// Report
$rStmt = $db->prepare("SELECT r.*, u.full_name AS submitted_by FROM job_card_reports r LEFT JOIN users u ON u.id = r.submitted_by WHERE r.job_card_id = ?");
$rStmt->execute([$jobCardId]);
$report = $rStmt->fetch();

// ── Team members: lead tech (assigned_to) UNION extras — same as costing engine ──
$tStmt = $db->prepare("
    SELECT u.id AS user_id, u.full_name, 'Lead Technician' AS role
    FROM users u
    WHERE u.id = (SELECT assigned_to FROM job_cards WHERE id = ?)
      AND u.id IS NOT NULL
    UNION
    SELECT u2.id, u2.full_name,
           COALESCE(NULLIF(jct.role,''), 'Technician') AS role
    FROM job_card_technicians jct
    JOIN users u2 ON u2.id = jct.user_id
    WHERE jct.job_card_id = ?
      AND jct.user_id != (SELECT assigned_to FROM job_cards WHERE id = ?)
");
$tStmt->execute([$jobCardId, $jobCardId, $jobCardId]);
$techs = $tStmt->fetchAll();

// Time logs (internal only)
$tlStmt = $db->prepare("SELECT tl.*, u.full_name AS user_name FROM job_card_time_logs tl JOIN users u ON u.id = tl.user_id WHERE tl.job_card_id = ? ORDER BY tl.event_time ASC");
$tlStmt->execute([$jobCardId]);
$timeLogs = $tlStmt->fetchAll();

// ── Labour calculation (mirrors costing.php exactly) ─────────────────────────
$defaultDays = 21.67;
$defaultHours = 8.0;
try {
  foreach ($db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group IN ('hr','finance')")->fetchAll() as $s) {
    if ($s['setting_key'] === 'working_days_per_month')
      $defaultDays = (float) $s['setting_value'];
    if ($s['setting_key'] === 'working_hours_per_day')
      $defaultHours = (float) $s['setting_value'];
  }
} catch (Exception $ignored) {
}

require_once __DIR__ . '/_costing_engine.php';
$segs = calcSegments($timeLogs);
$drivingMin = $segs['driving_min'];
$workingMin = $segs['working_min'];
$pausedMin = $segs['paused_travel_min'] + $segs['paused_work_min'];
$totalBillableMin = $drivingMin + $workingMin;

// Per-tech labour breakdown
$labourRows = [];
$totalLabourCost = 0;
$teamForLabour = !empty($techs) ? $techs : [];
if (empty($teamForLabour)) {
  // Fallback: use unique users from time logs
  $seen = [];
  foreach ($timeLogs as $l) {
    if (!isset($seen[$l['user_id']])) {
      $seen[$l['user_id']] = true;
      $teamForLabour[] = ['user_id' => $l['user_id'], 'full_name' => $l['user_name'], 'role' => 'Technician'];
    }
  }
}
foreach ($teamForLabour as $tm) {
  $tid = (int) $tm['user_id'];
  $rStmt = $db->prepare("
        SELECT es.basic_salary, es.salary_type,
               COALESCE(e.days_per_month, ?) AS days_pm,
               COALESCE(e.hours_per_day,  ?) AS hours_pd
        FROM users u
        LEFT JOIN employees e ON e.user_id = u.id
        LEFT JOIN employee_salaries es ON es.employee_id = e.id
        WHERE u.id = ?
        ORDER BY es.effective_date DESC LIMIT 1
    ");
  $rStmt->execute([$defaultDays, $defaultHours, $tid]);
  $r = $rStmt->fetch();
  $hourlyRate = 0;
  if ($r) {
    $dpm = (float) ($r['days_pm'] ?: $defaultDays);
    $hpd = (float) ($r['hours_pd'] ?: $defaultHours);
    if ($r['salary_type'] === 'hourly') {
      $hourlyRate = (float) $r['basic_salary'];
    } elseif ($r['salary_type'] === 'monthly') {
      $mh = $dpm * $hpd;
      $hourlyRate = $mh > 0 ? round((float) $r['basic_salary'] / $mh, 4) : 0;
    } elseif ($r['salary_type'] === 'daily') {
      $hourlyRate = $hpd > 0 ? round((float) $r['basic_salary'] / $hpd, 4) : 0;
    }
  }
  $techLabour = round(($totalBillableMin / 60) * $hourlyRate, 2);
  $totalLabourCost += $techLabour;
  $labourRows[] = [
    'name' => $tm['full_name'],
    'role' => $tm['role'] ?? 'Technician',
    'hourly_rate' => round($hourlyRate, 2),
    'driving_hrs' => round($drivingMin / 60, 2),
    'working_hrs' => round($workingMin / 60, 2),
    'paused_hrs' => round($pausedMin / 60, 2),
    'total_hrs' => round($totalBillableMin / 60, 2),
    'labour_cost' => $techLabour,
  ];
}
$totalLabourCost = round($totalLabourCost, 2);

// Notes (internal only)
$nStmt = $db->prepare("SELECT jcn.*, u.full_name AS user_name FROM job_card_notes jcn JOIN users u ON u.id = jcn.user_id WHERE jcn.job_card_id = ? AND jcn.is_private = 0 ORDER BY jcn.created_at ASC");
$nStmt->execute([$jobCardId]);
$notes = $nStmt->fetchAll();

// Slips (internal only)
$slStmt = $db->prepare("SELECT s.*, u.full_name AS captured_by FROM slips s LEFT JOIN users u ON u.id = s.user_id WHERE s.job_card_id = ? ORDER BY s.slip_date");
$slStmt->execute([$jobCardId]);
$slips = $slStmt->fetchAll();

// Stock issued (internal only)
$stStmt = $db->prepare("SELECT st.*, si.name AS item_name, si.unit, si.sku FROM stock_transactions st JOIN stock_items si ON si.id = st.stock_item_id WHERE st.job_card_id = ? AND st.transaction_type IN ('issue_jobcard','return') ORDER BY st.transaction_date");
$stStmt->execute([$jobCardId]);
$stockItems = $stStmt->fetchAll();

// ── Net stock items by item — group issue/return into single rows ──────────
$stockNetMap = [];
foreach ($stockItems as $si) {
  $key = $si['stock_item_id'] . '_' . $si['unit_cost'];
  $mult = $si['transaction_type'] === 'return' ? -1 : 1;
  if (!isset($stockNetMap[$key])) {
    $stockNetMap[$key] = [
      'item_name' => $si['item_name'],
      'sku' => $si['sku'] ?? '',
      'unit' => $si['unit'] ?? '',
      'unit_cost' => (float) $si['unit_cost'],
      'net_qty' => 0,
      'net_total' => 0,
    ];
  }
  $stockNetMap[$key]['net_qty'] += $mult * (float) $si['quantity'];
  $stockNetMap[$key]['net_total'] += $mult * (float) $si['unit_cost'] * (float) $si['quantity'];
}
// Only keep rows where net qty != 0
$stockNetItems = array_values(array_filter($stockNetMap, fn($r) => $r['net_qty'] != 0));

// Images (both PDFs)
$imgStmt = $db->prepare("SELECT * FROM job_card_images WHERE job_card_id = ? ORDER BY created_at ASC");
$imgStmt->execute([$jobCardId]);
$images = $imgStmt->fetchAll();

// Costing summary (internal)
$odoStart = (int) $jc['odo_start'];
$odoEnd = (int) $jc['odo_end'];
$kmTravelled = ($odoStart && $odoEnd) ? max(0, $odoEnd - $odoStart) : 0;
$travelCost = $kmTravelled * (float) ($jc['cost_per_km'] ?? 0);
$slipsTotal = array_sum(array_column($slips, 'amount'));
$consumablesCost = 0;
foreach ($stockNetItems as $si) {
  $consumablesCost += $si['net_total'];
}

// Company settings
$sets = [];
try {
  foreach ($db->query("SELECT setting_key, setting_value FROM settings WHERE setting_group='general'")->fetchAll() as $s) {
    $sets[$s['setting_key']] = $s['setting_value'];
  }
} catch (Exception $e) {
}
$company = $sets['company_name'] ?? 'Elegant Work';
$logoPath = $sets['company_logo'] ?? null;
$logoBase64 = null;
if ($logoPath) {
  $logoAbsPath = __DIR__ . '/../../' . $logoPath;
  if (file_exists($logoAbsPath)) {
    $ext = strtolower(pathinfo($logoAbsPath, PATHINFO_EXTENSION));
    $mimeMap = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp', 'svg' => 'image/svg+xml'];
    $mime = $mimeMap[$ext] ?? 'image/png';
    $logoBase64 = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($logoAbsPath));
  }
}

// Helpers
function fmt_date($d)
{
  return $d ? date('d M Y', strtotime($d)) : '—';
}
function fmt_dt($d)
{
  return $d ? date('d M Y H:i', strtotime($d)) : '—';
}
function fmt_r($n)
{
  return 'R ' . number_format((float) $n, 2);
}
function esc($s)
{
  return htmlspecialchars($s ?? '', ENT_QUOTES);
}

$statusLabels = ['draft' => 'Draft', 'assigned' => 'Assigned', 'travelling' => 'Travelling', 'on_site' => 'On Site', 'working' => 'Working', 'completed' => 'Completed', 'internal_complete' => 'Complete', 'invoiced' => 'Invoiced', 'cancelled' => 'Cancelled'];
$statusLabel = $statusLabels[$jc['status']] ?? ucfirst($jc['status']);
$isClient = $type === 'client';
$pageTitle = $isClient ? 'Job Completion Certificate' : 'Internal Job Card Report';

// Event labels for timeline

header('Content-Type: text/html; charset=utf-8');
?><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title><?= esc($pageTitle) ?> — <?= esc($jc['job_number']) ?></title>
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    body {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 11pt;
      color: #1a1a2e;
      background: #fff;
    }

    .page {
      max-width: 800px;
      margin: 0 auto;
      padding: 32px;
    }

    /* Header */
    .header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding-bottom: 18px;
      border-bottom: 3px solid #1a3a6b;
      margin-bottom: 22px;
    }

    .company-name {
      font-size: 22pt;
      font-weight: 800;
      color: #1a3a6b;
    }

    .doc-title {
      font-size: 13pt;
      font-weight: 700;
      color: #1a3a6b;
      text-align: right;
    }

    .doc-meta {
      font-size: 9pt;
      color: #666;
      text-align: right;
      margin-top: 4px;
    }

    .job-number {
      font-size: 18pt;
      font-weight: 800;
      color: #2563eb;
      text-align: right;
    }

    /* Info grid */
    .info-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 0;
      margin-bottom: 22px;
      border: 1px solid #d1d5db;
      border-radius: 6px;
      overflow: hidden;
    }

    .info-grid.three {
      grid-template-columns: 1fr 1fr 1fr;
    }

    .info-cell {
      padding: 10px 14px;
      border-bottom: 1px solid #d1d5db;
    }

    .info-cell:nth-last-child(-n+2) {
      border-bottom: none;
    }

    .info-grid.three .info-cell:nth-last-child(-n+3) {
      border-bottom: none;
    }

    .info-label {
      font-size: 8pt;
      font-weight: 700;
      color: #6b7280;
      text-transform: uppercase;
      letter-spacing: .04em;
      margin-bottom: 3px;
    }

    .info-value {
      font-size: 10.5pt;
      font-weight: 600;
      color: #111;
    }

    /* Section */
    .section {
      margin-bottom: 22px;
    }

    .section-title {
      font-size: 11pt;
      font-weight: 800;
      color: #1a3a6b;
      text-transform: uppercase;
      letter-spacing: .06em;
      padding-bottom: 6px;
      border-bottom: 2px solid #e5e7eb;
      margin-bottom: 12px;
    }

    /* Text block */
    .text-block {
      background: #f9fafb;
      border: 1px solid #e5e7eb;
      border-radius: 5px;
      padding: 12px 14px;
      font-size: 10.5pt;
      line-height: 1.6;
      white-space: pre-wrap;
      min-height: 36px;
    }

    /* Table */
    table {
      width: 100%;
      border-collapse: collapse;
      font-size: 10pt;
    }

    th {
      background: #1a3a6b;
      color: #fff;
      text-align: left;
      padding: 8px 10px;
      font-size: 9pt;
    }

    td {
      padding: 8px 10px;
      border-bottom: 1px solid #e5e7eb;
      vertical-align: top;
    }

    tr:last-child td {
      border-bottom: none;
    }

    tr:nth-child(even) td {
      background: #f9fafb;
    }

    .text-right {
      text-align: right;
    }

    .total-row td {
      font-weight: 700;
      background: #eff6ff !important;
      border-top: 2px solid #1a3a6b;
    }

    /* Timeline */
    .timeline {
      list-style: none;
      padding: 0;
    }

    .timeline li {
      display: flex;
      gap: 12px;
      padding: 8px 0;
      border-bottom: 1px solid #f3f4f6;
      font-size: 10pt;
    }

    .timeline li:last-child {
      border-bottom: none;
    }

    .tl-dot {
      width: 28px;
      height: 28px;
      border-radius: 50%;
      background: #eff6ff;
      border: 2px solid #2563eb;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12pt;
      flex-shrink: 0;
    }

    .tl-body {
      flex: 1;
    }

    .tl-label {
      font-weight: 600;
    }

    .tl-meta {
      font-size: 9pt;
      color: #6b7280;
    }

    /* Signature */
    .sig-box {
      border: 2px solid #d1d5db;
      border-radius: 6px;
      background: #fff;
      min-height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
    }

    .sig-box img {
      max-height: 120px;
      max-width: 100%;
    }

    /* Status badge */
    .badge {
      display: inline-block;
      padding: 3px 10px;
      border-radius: 20px;
      font-size: 9pt;
      font-weight: 700;
    }

    .badge-completed {
      background: #dcfce7;
      color: #166534;
    }

    .badge-invoiced {
      background: #dbeafe;
      color: #1e40af;
    }

    .badge-working {
      background: #fef3c7;
      color: #92400e;
    }

    /* Footer */
    .footer {
      margin-top: 32px;
      padding-top: 14px;
      border-top: 1px solid #d1d5db;
      font-size: 9pt;
      color: #6b7280;
      display: flex;
      justify-content: space-between;
    }

    /* Internal watermark */
    <?php if (!$isClient): ?>
      body::before {
        content: 'INTERNAL';
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%) rotate(-35deg);
        font-size: 90pt;
        font-weight: 900;
        color: rgba(0, 0, 0, .04);
        pointer-events: none;
        z-index: 0;
      }

    <?php endif; ?>

    @media print {
      body {
        font-size: 10pt;
      }

      .page {
        padding: 0;
        max-width: 100%;
      }

      .no-print {
        display: none !important;
      }

      @page {
        margin: 18mm 15mm;
      }
    }
  </style>
</head>

<body>
  <div class="page">

    <!-- Print button -->
    <div class="no-print" style="margin-bottom:18px;display:flex;gap:10px">
      <button onclick="window.print()"
        style="background:#1a3a6b;color:#fff;border:none;padding:9px 22px;border-radius:6px;font-size:11pt;font-weight:700;cursor:pointer">🖨️
        Print / Save as PDF</button>
      <button onclick="window.close()"
        style="background:#f3f4f6;color:#374151;border:none;padding:9px 16px;border-radius:6px;cursor:pointer">✕
        Close</button>
      <?php if (!$pdfToken): ?>
        <?php if ($isClient): ?>
          <a href="?job_card_id=<?= $jobCardId ?>&type=internal&token=<?= urlencode($_GET['token'] ?? '') ?>"
            target="_blank"
            style="background:#f3f4f6;color:#374151;border:none;padding:9px 16px;border-radius:6px;cursor:pointer;text-decoration:none;font-size:11pt">🔒
            Internal PDF</a>
        <?php else: ?>
          <a href="?job_card_id=<?= $jobCardId ?>&type=client&token=<?= urlencode($_GET['token'] ?? '') ?>" target="_blank"
            style="background:#f3f4f6;color:#374151;border:none;padding:9px 16px;border-radius:6px;cursor:pointer;text-decoration:none;font-size:11pt">📄
            Client PDF</a>
        <?php endif; ?>
      <?php endif; ?>
    </div>

    <!-- Header -->
    <div class="header">
      <div>
        <?php if ($logoBase64): ?>
          <img src="<?= $logoBase64 ?>" alt="<?= esc($company) ?>"
            style="max-height:60px;max-width:220px;object-fit:contain;display:block;margin-bottom:6px">
        <?php else: ?>
          <div class="company-name"><?= esc($company) ?></div>
        <?php endif; ?>
        <div style="font-size:10pt;color:#6b7280;margin-top:4px">
          <?= $isClient ? 'Job Completion Certificate' : 'Internal Job Card Report' ?>
        </div>
      </div>
      <div>
        <div class="job-number"><?= esc($jc['job_number']) ?></div>
        <div class="doc-meta">Generated: <?= date('d M Y H:i') ?></div>
        <div style="margin-top:6px"><span class="badge badge-<?= esc($jc['status']) ?>"><?= esc($statusLabel) ?></span>
        </div>
      </div>
    </div>

    <!-- Job Info -->
    <div class="section">
      <div class="section-title">Job Details</div>
      <div class="info-grid">
        <div class="info-cell">
          <div class="info-label">Job Title</div>
          <div class="info-value"><?= esc($jc['title']) ?></div>
        </div>
        <div class="info-cell">
          <div class="info-label">Client</div>
          <div class="info-value"><?= esc($jc['client_name'] ?? '—') ?></div>
        </div>
        <div class="info-cell">
          <div class="info-label">Job Type</div>
          <div class="info-value"><?= esc(ucfirst(str_replace('_', ' ', $jc['job_type']))) ?></div>
        </div>
        <div class="info-cell">
          <div class="info-label">Priority</div>
          <div class="info-value"><?= esc(ucfirst($jc['priority'])) ?></div>
        </div>
        <div class="info-cell">
          <div class="info-label">Site Name</div>
          <div class="info-value"><?= esc($jc['site_name'] ?? '—') ?></div>
        </div>
        <div class="info-cell">
          <div class="info-label">Site Address</div>
          <div class="info-value"><?= esc($jc['site_address'] ?? '—') ?></div>
        </div>
        <div class="info-cell">
          <div class="info-label">Scheduled Date</div>
          <div class="info-value"><?= fmt_date($jc['scheduled_date']) ?></div>
        </div>
        <div class="info-cell">
          <div class="info-label">Completed</div>
          <div class="info-value"><?= fmt_dt($jc['completed_at']) ?></div>
        </div>
      </div>
    </div>

    <!-- Technicians -->
    <?php if ($techs): ?>
      <div class="section">
        <div class="section-title">Team</div>
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Role</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($techs as $t): ?>
              <tr>
                <td style="font-weight:<?= $t['role'] === 'Lead Technician' ? '700' : '400' ?>">
                  <?= esc($t['full_name']) ?>
                  <?php if ($t['role'] === 'Lead Technician'): ?>
                    <span
                      style="display:inline-block;margin-left:6px;padding:1px 7px;background:#dbeafe;color:#1e40af;border-radius:10px;font-size:8pt;font-weight:700">LEAD</span>
                  <?php endif; ?>
                </td>
                <td><?= esc(ucfirst($t['role'] ?? 'Technician')) ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>

    <?php if ($jc['odo_start'] || $jc['odo_end']): ?>
      <div class="section">
        <div class="section-title">Vehicle & Travel</div>
        <div class="info-grid three">
          <div class="info-cell">
            <div class="info-label">Vehicle</div>
            <div class="info-value">
              <?= $jc['vehicle_reg'] ? esc($jc['vehicle_make'] . ' ' . $jc['vehicle_model'] . ' (' . $jc['vehicle_reg'] . ')') : '—' ?>
            </div>
          </div>
          <div class="info-cell">
            <div class="info-label">ODO Start</div>
            <div class="info-value"><?= $jc['odo_start'] ? number_format((int) $jc['odo_start']) . ' km' : '—' ?></div>
          </div>
          <div class="info-cell">
            <div class="info-label">ODO End</div>
            <div class="info-value"><?= $jc['odo_end'] ? number_format((int) $jc['odo_end']) . ' km' : '—' ?></div>
          </div>
          <?php if ($kmTravelled): ?>
            <div class="info-cell">
              <div class="info-label">Distance Travelled</div>
              <div class="info-value"><?= number_format($kmTravelled) ?> km</div>
            </div>
          <?php endif; ?>
        </div>
      </div>
    <?php endif; ?>

    <!-- Work Performed -->
    <?php if ($report): ?>
      <div class="section">
        <div class="section-title">Work Performed</div>
        <div class="text-block"><?= esc($report['work_performed']) ?></div>
      </div>

      <?php if ($report['materials_used']): ?>
        <div class="section">
          <div class="section-title">Materials / Parts Used</div>
          <div class="text-block"><?= esc($report['materials_used']) ?></div>
        </div>
      <?php endif; ?>

      <?php if ($report['issues_found']): ?>
        <div class="section">
          <div class="section-title">Issues Found</div>
          <div class="text-block"><?= esc($report['issues_found']) ?></div>
        </div>
      <?php endif; ?>

      <?php if ($report['recommendations']): ?>
        <div class="section">
          <div class="section-title">Recommendations</div>
          <div class="text-block"><?= esc($report['recommendations']) ?></div>
        </div>
      <?php endif; ?>
    <?php endif; ?>

    <?php if ($isClient): ?>
      <!-- CLIENT: Stock items used (qty only, no prices) -->
      <?php if ($stockNetItems): ?>
        <div class="section">
          <div class="section-title">Parts &amp; Materials Used</div>
          <table>
            <thead>
              <tr>
                <th>Item</th>
                <th>SKU</th>
                <th class="text-right">Net Qty</th>
                <th>Unit</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($stockNetItems as $si): ?>
                <tr>
                  <td><?= esc($si['item_name']) ?></td>
                  <td><?= esc($si['sku'] ?? '—') ?></td>
                  <td class="text-right">
                    <?= $si['net_qty'] == floor($si['net_qty']) ? (int) $si['net_qty'] : number_format($si['net_qty'], 2) ?>
                  </td>
                  <td><?= esc($si['unit'] ?? '') ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>

      <!-- CLIENT VIEW: Signature & Sign-off -->
      <div class="section">
        <div class="section-title">Client Sign-Off</div>
        <div class="info-grid">
          <div class="info-cell">
            <div class="info-label">Signed By</div>
            <div class="info-value"><?= esc($report['client_name_signed'] ?? $jc['client_name_signed'] ?? '—') ?></div>
          </div>
          <div class="info-cell">
            <div class="info-label">Satisfied with work</div>
            <div class="info-value"><?= ($report && $report['client_satisfied']) ? '✅ Yes' : '❌ No / Not recorded' ?>
            </div>
          </div>
        </div>
        <?php if ($report && $report['signature_data']): ?>
          <div style="margin-top:12px">
            <div class="info-label" style="margin-bottom:6px">Signature</div>
            <div class="sig-box"><img src="<?= $report['signature_data'] ?>" alt="Client Signature"></div>
          </div>
        <?php else: ?>
          <div style="margin-top:12px">
            <div class="info-label" style="margin-bottom:6px">Signature</div>
            <div class="sig-box" style="height:90px"><span style="color:#9ca3af;font-size:9pt">No signature captured</span>
            </div>
          </div>
        <?php endif; ?>
      </div>

    <?php else: ?>
      <!-- INTERNAL VIEW: Notes, Timeline, Costs -->

      <?php if ($notes): ?>
        <div class="section">
          <div class="section-title">Notes</div>
          <table>
            <thead>
              <tr>
                <th>Date</th>
                <th>By</th>
                <th>Note</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($notes as $n): ?>
                <tr>
                  <td style="white-space:nowrap"><?= fmt_dt($n['created_at']) ?></td>
                  <td><?= esc($n['user_name']) ?></td>
                  <td><?= esc($n['note']) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>

      <?php if ($timeLogs): ?>

        <!-- Labour Hours Breakdown -->
        <?php if (!empty($labourRows)): ?>
          <div class="section">
            <div class="section-title">Labour Hours</div>
            <table>
              <thead>
                <tr>
                  <th>Technician</th>
                  <th>Role</th>
                  <th class="text-right">Drive</th>
                  <th class="text-right">Work</th>
                  <th class="text-right">Paused</th>
                  <th class="text-right">Billable Hrs</th>
                  <th class="text-right">Rate/hr</th>
                  <th class="text-right">Labour Cost</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($labourRows as $lr): ?>
                  <tr>
                    <td style="font-weight:<?= $lr['role'] === 'Lead Technician' ? '700' : '400' ?>">
                      <?= esc($lr['name']) ?>
                      <?php if ($lr['role'] === 'Lead Technician'): ?>
                        <span
                          style="display:inline-block;margin-left:6px;padding:1px 7px;background:#dbeafe;color:#1e40af;border-radius:10px;font-size:7.5pt;font-weight:700">LEAD</span>
                      <?php endif; ?>
                    </td>
                    <td style="font-size:9pt;color:#6b7280"><?= esc(ucfirst($lr['role'])) ?></td>
                    <td class="text-right"><?= number_format($lr['driving_hrs'], 2) ?>h</td>
                    <td class="text-right"><?= number_format($lr['working_hrs'], 2) ?>h</td>
                    <td class="text-right" style="color:#9ca3af"><?= number_format($lr['paused_hrs'], 2) ?>h</td>
                    <td class="text-right" style="font-weight:700"><?= number_format($lr['total_hrs'], 2) ?>h</td>
                    <td class="text-right">
                      <?= $lr['hourly_rate'] > 0 ? fmt_r($lr['hourly_rate']) : '<span style="color:#9ca3af">—</span>' ?></td>
                    <td class="text-right" style="font-weight:700">
                      <?= $lr['labour_cost'] > 0 ? fmt_r($lr['labour_cost']) : '<span style="color:#9ca3af">—</span>' ?></td>
                  </tr>
                <?php endforeach; ?>
                <?php if (count($labourRows) > 1): ?>
                  <tr class="total-row">
                    <td colspan="5">Total</td>
                    <td class="text-right"><?= number_format($totalBillableMin / 60, 2) ?>h</td>
                    <td></td>
                    <td class="text-right"><?= fmt_r($totalLabourCost) ?></td>
                  </tr>
                <?php endif; ?>
              </tbody>
            </table>
            <?php if (count($labourRows) > 1): ?>
              <div style="margin-top:8px;font-size:8.5pt;color:#6b7280;font-style:italic">
                * Team shared the same site timeline. Each tech's cost = their hourly rate × shared billable hours.
              </div>
            <?php endif; ?>
          </div>
        <?php endif; ?>

        <!-- Timeline -->
        <div class="section">
          <div class="section-title">Timeline</div>
          <ul class="timeline">
            <?php
            $tlIcons = [
              'depart' => '🚗',
              'arrive_site' => '📍',
              'start_work' => '🔧',
              'pause_work' => '⏸',
              'resume_work' => '▶️',
              'pause_travel' => '⏸',
              'resume_travel' => '▶️',
              'depart_site' => '🚗',
              'arrive_base' => '🏠',
              'completed' => '✅',
              'internal_complete' => '✅',
              'invoiced' => '🧾',
              'cancelled' => '❌',
              'no_charge' => '🆓',
            ];
            $tlLabels = [
              'depart' => 'Departed to Site',
              'arrive_site' => 'Arrived on Site',
              'start_work' => 'Started Work',
              'pause_work' => 'Work Paused',
              'resume_work' => 'Work Resumed',
              'pause_travel' => 'Travel Paused',
              'resume_travel' => 'Travel Resumed',
              'depart_site' => 'Departed Site',
              'arrive_base' => 'Arrived at Base',
              'completed' => 'Job Completed',
              'internal_complete' => 'Job Completed (Internal)',
              'invoiced' => 'Invoiced',
              'cancelled' => 'Cancelled',
              'no_charge' => 'No Charge',
            ];
            $tlCount = count($timeLogs);
            foreach ($timeLogs as $idx => $tl):
              $icon = $tlIcons[$tl['event_type']] ?? '🕐';
              $label = $tlLabels[$tl['event_type']] ?? ucfirst(str_replace('_', ' ', $tl['event_type']));
              // Duration to next event
              $durStr = '';
              if ($idx + 1 < $tlCount) {
                $diffMin = round((strtotime($timeLogs[$idx + 1]['event_time']) - strtotime($tl['event_time'])) / 60);
                if ($diffMin > 0) {
                  $h = floor($diffMin / 60);
                  $m = $diffMin % 60;
                  $durStr = $h > 0 ? "{$h}h" . ($m > 0 ? " {$m}m" : '') : "{$m}m";
                }
              }
              ?>
              <li>
                <div class="tl-dot"><?= $icon ?></div>
                <div class="tl-body">
                  <div class="tl-label"><?= esc($label) ?></div>
                  <div class="tl-meta">
                    <?= fmt_dt($tl['event_time']) ?> — <?= esc($tl['user_name']) ?>
                    <?php if ($durStr): ?>
                      <span
                        style="display:inline-block;margin-left:10px;padding:1px 8px;background:#f3f4f6;border-radius:10px;color:#374151;font-size:8pt;font-weight:600">⏱
                        <?= esc($durStr) ?></span>
                    <?php endif; ?>
                  </div>
                </div>
              </li>
            <?php endforeach; ?>
          </ul>
        </div>
      <?php endif; ?>

      <?php if ($slips): ?>
        <div class="section">
          <div class="section-title">Expense Slips</div>
          <table>
            <thead>
              <tr>
                <th>Date</th>
                <th>Merchant</th>
                <th>Category</th>
                <th>Captured By</th>
                <th class="text-right">Amount</th>
              </tr>
            </thead>
            <tbody>
              <?php $slTotal = 0;
              foreach ($slips as $s):
                $slTotal += (float) $s['amount']; ?>
                <tr>
                  <td><?= fmt_date($s['slip_date']) ?></td>
                  <td><?= esc($s['merchant'] ?? '—') ?></td>
                  <td><?= esc($s['category'] ?? '—') ?></td>
                  <td><?= esc($s['captured_by'] ?? '—') ?></td>
                  <td class="text-right"><?= fmt_r($s['amount']) ?></td>
                </tr>
              <?php endforeach; ?>
              <tr class="total-row">
                <td colspan="4">Total Slips</td>
                <td class="text-right"><?= fmt_r($slTotal) ?></td>
              </tr>
            </tbody>
          </table>
        </div>
      <?php endif; ?>

      <?php if ($stockNetItems): ?>
        <div class="section">
          <div class="section-title">Stock / Consumables Issued</div>
          <table>
            <thead>
              <tr>
                <th>Item</th>
                <th>SKU</th>
                <th class="text-right">Net Qty</th>
                <th class="text-right">Unit Cost</th>
                <th class="text-right">Net Total</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($stockNetItems as $si): ?>
                <tr>
                  <td><?= esc($si['item_name']) ?></td>
                  <td><?= esc($si['sku'] ?? '—') ?></td>
                  <td class="text-right">
                    <?= $si['net_qty'] == floor($si['net_qty']) ? (int) $si['net_qty'] : number_format($si['net_qty'], 2) ?>
                    <?= esc($si['unit'] ?? '') ?></td>
                  <td class="text-right"><?= fmt_r($si['unit_cost']) ?></td>
                  <td class="text-right"><?= fmt_r($si['net_total']) ?></td>
                </tr>
              <?php endforeach; ?>
              <tr class="total-row">
                <td colspan="4">Total Consumables</td>
                <td class="text-right"><?= fmt_r($consumablesCost) ?></td>
              </tr>
            </tbody>
          </table>
        </div>
      <?php endif; ?>

      <!-- Cost Summary -->
      <div class="section">
        <div class="section-title">Cost Summary</div>
        <table>
          <thead>
            <tr>
              <th>Category</th>
              <th class="text-right">Amount</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($totalLabourCost > 0): ?>
              <tr>
                <td>Labour (<?= number_format($totalBillableMin / 60, 2) ?> hrs × <?= count($labourRows) ?>
                  tech<?= count($labourRows) > 1 ? 's' : '' ?>)</td>
                <td class="text-right"><?= fmt_r($totalLabourCost) ?></td>
              </tr>
            <?php endif; ?>
            <?php if ($travelCost > 0): ?>
              <tr>
                <td>Travel (<?= number_format($kmTravelled) ?> km @ <?= fmt_r($jc['cost_per_km']) ?>/km)</td>
                <td class="text-right"><?= fmt_r($travelCost) ?></td>
              </tr>
            <?php endif; ?>
            <?php if ($consumablesCost > 0): ?>
              <tr>
                <td>Consumables / Stock</td>
                <td class="text-right"><?= fmt_r($consumablesCost) ?></td>
              </tr>
            <?php endif; ?>
            <?php if ($slipsTotal > 0): ?>
              <tr>
                <td>Expense Slips</td>
                <td class="text-right"><?= fmt_r($slipsTotal) ?></td>
              </tr>
            <?php endif; ?>
            <tr class="total-row">
              <td>Total Cost</td>
              <td class="text-right"><?= fmt_r($totalLabourCost + $travelCost + $consumablesCost + $slipsTotal) ?></td>
            </tr>
            <?php if ($jc['invoice_amount'] > 0): ?>
              <tr style="background:#f0fdf4 !important">
                <td style="font-weight:700">Invoice Amount</td>
                <td class="text-right" style="font-weight:700;color:#166534"><?= fmt_r($jc['invoice_amount']) ?></td>
              </tr>
              <tr style="background:#f0fdf4 !important">
                <?php $netProfit = (float) $jc['invoice_amount'] - ($totalLabourCost + $travelCost + $consumablesCost + $slipsTotal); ?>
                <td style="font-weight:700">Net <?= $netProfit >= 0 ? 'Profit' : 'Loss' ?></td>
                <td class="text-right" style="font-weight:700;color:<?= $netProfit >= 0 ? '#166534' : '#991b1b' ?>">
                  <?= fmt_r($netProfit) ?></td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Signature (internal too) -->
      <?php if ($report): ?>
        <div class="section">
          <div class="section-title">Client Sign-Off</div>
          <div class="info-grid">
            <div class="info-cell">
              <div class="info-label">Signed By</div>
              <div class="info-value"><?= esc($report['client_name_signed'] ?? '—') ?></div>
            </div>
            <div class="info-cell">
              <div class="info-label">Satisfied</div>
              <div class="info-value"><?= $report['client_satisfied'] ? '✅ Yes' : '❌ No' ?></div>
            </div>
          </div>
          <?php if ($report['signature_data']): ?>
            <div style="margin-top:10px">
              <div class="sig-box"><img src="<?= $report['signature_data'] ?>" alt="Signature"></div>
            </div>
          <?php endif; ?>
          <?php if ($report['submitted_by']): ?>
            <div style="margin-top:8px;font-size:9pt;color:#6b7280">Report submitted by <?= esc($report['submitted_by']) ?> on
              <?= fmt_dt($report['submitted_at'] ?? '') ?>
            </div>
          <?php endif; ?>
        </div>
      <?php endif; ?>

    <?php endif; // end internal view ?>

    <!-- Photos — both PDFs -->
    <?php if ($images): ?>
      <div class="section">
        <div class="section-title">Site Photos</div>
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px">
          <?php foreach ($images as $img):
            $imgPath = __DIR__ . '/../../' . $img['file_path'];
            $imgSrc = null;
            if (file_exists($imgPath)) {
              $ext = strtolower(pathinfo($imgPath, PATHINFO_EXTENSION));
              $mimeMap = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp'];
              $mime = $mimeMap[$ext] ?? 'image/jpeg';
              $imgSrc = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($imgPath));
            }
            if (!$imgSrc)
              continue;
            ?>
            <div style="border:1px solid #e5e7eb;border-radius:5px;overflow:hidden">
              <img src="<?= $imgSrc ?>" alt="<?= esc($img['caption'] ?? '') ?>"
                style="width:100%;height:160px;object-fit:cover;display:block">
              <?php if ($img['caption'] || $img['image_type']): ?>
                <div style="padding:5px 8px;font-size:8pt;color:#6b7280;background:#f9fafb">
                  <?php if ($img['image_type']): ?><span
                      style="font-weight:700;text-transform:uppercase"><?= esc($img['image_type']) ?></span><?php endif; ?>
                  <?php if ($img['caption']): ?> — <?= esc($img['caption']) ?><?php endif; ?>
                </div>
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    <?php endif; ?>

    <!-- Footer -->
    <div class="footer">
      <span><?= esc($company) ?> · <?= esc($jc['job_number']) ?></span>
      <span><?= $isClient ? 'Client Copy' : 'Internal Copy — Confidential' ?> · <?= date('d M Y') ?></span>
    </div>

  </div>
  <script>
    // Auto-trigger print dialog for convenience
    // window.onload = () => { if(window.location.search.includes('print=1')) window.print(); }
  </script>
</body>

</html>