<?php
// GET /api/checklists/pdf.php?instance_id=X&token=XXX
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

// Auth via token in query string (opens in new tab)
$token = $_GET['token'] ?? '';
if ($token) {
    $db   = getDB();
    $ts   = $db->prepare("SELECT u.* 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]);
    $user = $ts->fetch();
    if (!$user) { http_response_code(401); die('Unauthorised'); }
} else {
    $user = requireAuth();
    $db   = getDB();
}

$instanceId  = (int)($_GET['instance_id'] ?? 0);
$pdfType     = $_GET['type'] ?? 'submission'; // submission | blank

if (!$instanceId && $pdfType === 'submission') die('Instance ID required');

$templateId = (int)($_GET['template_id'] ?? 0);

// ── Fetch data ────────────────────────────────────────────────
if ($pdfType === 'submission' && $instanceId) {
    $iStmt = $db->prepare("
        SELECT ci.*,
               t.name AS template_name, t.description AS template_description, t.linked_type,
               u.full_name AS assigned_to_name,
               cb.full_name AS completed_by_name,
               v.registration AS vehicle_reg, CONCAT(v.make, ' ', v.model) AS vehicle_name
        FROM checklist_instances ci
        LEFT JOIN checklist_templates t ON t.id = ci.template_id
        LEFT JOIN users u  ON u.id = ci.user_id
        LEFT JOIN users cb ON cb.id = ci.completed_by
        LEFT JOIN fleet_vehicles v ON v.id = ci.vehicle_id
        WHERE ci.id = ?
    ");
    $iStmt->execute([$instanceId]);
    $instance = $iStmt->fetch();
    if (!$instance) die('Instance not found');
    $templateId = $instance['template_id'];
}

$tStmt = $db->prepare("SELECT * FROM checklist_templates WHERE id = ?");
$tStmt->execute([$templateId]);
$template = $tStmt->fetch();
if (!$template) die('Template not found');

$items = $db->prepare("
    SELECT ti.*,
           cii.answer_bool, cii.answer_text, cii.note, cii.image_filename, cii.photo_filename, cii.completed_at
    FROM checklist_template_items ti
    LEFT JOIN checklist_instance_items cii
        ON cii.instance_id = ? AND cii.template_item_id = ti.id
    WHERE ti.template_id = ?
    ORDER BY ti.sort_order ASC, ti.id ASC
");
$items->execute([$instanceId ?? 0, $templateId]);
$allItems = $items->fetchAll();

// Fetch all images for this instance from multi-image table
$imagesByItem = [];
if ($instanceId) {
    $imgStmt = $db->prepare("
        SELECT template_item_id, filename
        FROM checklist_item_images
        WHERE instance_id = ?
        ORDER BY uploaded_at ASC
    ");
    $imgStmt->execute([$instanceId]);
    foreach ($imgStmt->fetchAll() as $img) {
        $imagesByItem[$img['template_item_id']][] = $img['filename'];
    }
    // Fallback: if no multi-image rows, pull legacy single image_filename
    foreach ($allItems as $it) {
        if (empty($imagesByItem[$it['id']]) && !empty($it['image_filename'])) {
            $imagesByItem[$it['id']][] = $it['image_filename'];
        }
    }
}

// Company logo — build absolute URL from the stored relative path
$logoStmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = 'company_logo' LIMIT 1");
$logoStmt->execute();
$logoRaw = $logoStmt->fetchColumn() ?: null;

// Convert relative path (e.g. "uploads/settings/logo.png") to an absolute URL
// so the browser can load it regardless of where this PHP file sits.
$logoUrl = null;
if ($logoRaw) {
    $scheme   = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host     = $_SERVER['HTTP_HOST'] ?? '';
    // App root = two directories up from api/checklists/
    $appRoot  = rtrim(dirname(dirname(dirname($_SERVER['SCRIPT_NAME']))), '/');
    $logoUrl  = $scheme . '://' . $host . $appRoot . '/' . ltrim($logoRaw, '/');
}

// Company name
$nameStmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = 'company_name' LIMIT 1");
$nameStmt->execute();
$companyName = $nameStmt->fetchColumn() ?: 'Elegant Work';

function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES); }

$isBlank     = ($pdfType === 'blank');
$statusColor = '#16a34a';
$statusLabel = 'Completed';
if (!$isBlank && isset($instance)) {
    $statusMap   = ['pending' => ['#d97706','Pending'], 'in_progress' => ['#0284c7','In Progress'], 'completed' => ['#16a34a','Completed'], 'missed' => ['#dc2626','Missed']];
    [$statusColor, $statusLabel] = $statusMap[$instance['status'] ?? ''] ?? ['#6b7280','Unknown'];
}

header('Content-Type: text/html; charset=utf-8');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?= h($template['name']) ?> — Checklist <?= $isBlank ? 'Form' : 'Report' ?></title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
  * { margin:0; padding:0; box-sizing:border-box; }
  body { font-family:'Inter',sans-serif; font-size:13px; color:#1a1a2e; background:#fff; padding:0; }
  @media print { body { padding:0; } .no-print { display:none !important; } }

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

  /* Header */
  .header { display:flex; align-items:flex-start; justify-content:space-between; padding-bottom:20px; border-bottom:2px solid #1b4b8a; margin-bottom:24px; }
  .header-left img { max-height:52px; max-width:160px; object-fit:contain; }
  .header-left .company { font-size:20px; font-weight:700; color:#1b4b8a; }
  .header-right { text-align:right; }
  .header-right .doc-title { font-size:18px; font-weight:700; color:#1b4b8a; margin-bottom:4px; }
  .header-right .doc-sub { font-size:11px; color:#6b7280; }

  /* Status badge */
  .status-badge { display:inline-block; padding:3px 12px; border-radius:20px; font-size:11px; font-weight:600; color:#fff; margin-left:8px; }

  /* Info grid */
  .info-grid { display:grid; grid-template-columns:1fr 1fr 1fr; gap:12px; margin-bottom:24px; background:#f8faff; border:1px solid #e2e8f0; border-radius:8px; padding:16px; }
  .info-item label { display:block; font-size:10px; font-weight:600; color:#6b7280; text-transform:uppercase; letter-spacing:.5px; margin-bottom:3px; }
  .info-item span { font-size:13px; font-weight:500; color:#1a1a2e; }

  /* Items */
  .items-title { font-size:14px; font-weight:700; color:#1b4b8a; margin-bottom:14px; padding-bottom:6px; border-bottom:1px solid #e2e8f0; }
  .item-row { padding:14px 16px; border:1px solid #e2e8f0; border-radius:8px; margin-bottom:10px; }
  .item-row:nth-child(even) { background:#fafbff; }
  .item-num { display:inline-block; width:22px; height:22px; border-radius:50%; background:#1b4b8a; color:#fff; font-size:10px; font-weight:700; text-align:center; line-height:22px; margin-right:8px; flex-shrink:0; }
  .item-question { font-weight:600; font-size:13px; color:#1a1a2e; flex:1; }
  .item-header { display:flex; align-items:center; margin-bottom:8px; }
  .item-required { font-size:10px; color:#dc2626; margin-left:4px; }
  .item-answer-type { font-size:10px; color:#6b7280; margin-left:auto; background:#f1f5f9; padding:2px 8px; border-radius:10px; }

  /* Answer displays */
  .answer-yes-no { display:flex; gap:8px; margin-top:8px; }
  .yn-btn { padding:5px 18px; border-radius:6px; font-size:12px; font-weight:600; border:2px solid #e2e8f0; color:#6b7280; }
  .yn-btn.selected-yes { background:#dcfce7; border-color:#16a34a; color:#16a34a; }
  .yn-btn.selected-no  { background:#fee2e2; border-color:#dc2626; color:#dc2626; }
  .answer-text { margin-top:8px; padding:8px 12px; border:1.5px solid #e2e8f0; border-radius:6px; background:#f9fafb; font-size:12px; color:#374151; min-height:40px; }
  .answer-blank { margin-top:8px; padding:8px 12px; border:1.5px dashed #d1d5db; border-radius:6px; background:#fafafa; min-height:40px; }
  .answer-blank-lines { margin-top:4px; }
  .answer-blank-lines div { height:1px; background:#e5e7eb; margin-bottom:16px; }
  .note-row { margin-top:8px; font-size:11px; color:#6b7280; font-style:italic; padding:6px 10px; background:#f9fafb; border-radius:6px; border-left:3px solid #d1d5db; }
  .image-box { margin-top:10px; }
  .image-box img { max-width:280px; max-height:200px; object-fit:contain; border:1px solid #e2e8f0; border-radius:6px; }
  .image-grid { display:flex; flex-wrap:wrap; gap:8px; margin-top:10px; }
  .image-grid img { width:180px; height:140px; object-fit:cover; border:1px solid #e2e8f0; border-radius:6px; }
  .image-caption { font-size:10px; color:#9ca3af; margin-top:3px; text-align:center; }
  .image-placeholder { display:inline-block; padding:8px 14px; border:1.5px dashed #d1d5db; border-radius:6px; font-size:11px; color:#9ca3af; margin-top:8px; }

  /* Summary */
  .summary-bar { display:flex; gap:16px; background:#f0f4ff; border:1px solid #dbeafe; border-radius:8px; padding:14px 18px; margin-bottom:24px; flex-wrap:wrap; }
  .summary-item { text-align:center; }
  .summary-item .num { font-size:22px; font-weight:700; color:#1b4b8a; }
  .summary-item .lbl { font-size:10px; color:#6b7280; text-transform:uppercase; }
  .divider { width:1px; background:#dbeafe; }

  /* Footer */
  .footer { margin-top:32px; padding-top:16px; border-top:1px solid #e2e8f0; display:flex; justify-content:space-between; font-size:10px; color:#9ca3af; }

  /* Print button */
  .print-btn { position:fixed; top:20px; right:20px; background:#1b4b8a; color:#fff; border:none; padding:10px 20px; border-radius:8px; cursor:pointer; font-size:13px; font-weight:600; display:flex; align-items:center; gap:8px; box-shadow:0 4px 12px rgba(27,75,138,.3); }
  .print-btn:hover { background:#15396e; }
</style>
</head>
<body>

<button class="print-btn no-print" onclick="window.print()">
  <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
  Print / Save PDF
</button>

<div class="page">

  <!-- Header -->
  <div class="header">
    <div class="header-left">
      <?php if ($logoUrl): ?>
        <img src="<?= h($logoUrl) ?>" alt="Logo">
      <?php else: ?>
        <div class="company"><?= h($companyName) ?></div>
      <?php endif; ?>
    </div>
    <div class="header-right">
      <div class="doc-title">
        <?= $isBlank ? 'Checklist Form' : 'Checklist Report' ?>
        <?php if (!$isBlank && isset($instance)): ?>
          <span class="status-badge" style="background:<?= $statusColor ?>"><?= h($statusLabel) ?></span>
        <?php endif; ?>
      </div>
      <div class="doc-sub"><?= h($template['name']) ?></div>
      <?php if (!$isBlank && isset($instance)): ?>
        <div class="doc-sub" style="margin-top:4px">Instance #<?= $instanceId ?></div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Info Grid -->
  <div class="info-grid">
    <div class="info-item">
      <label>Checklist</label>
      <span><?= h($template['name']) ?></span>
    </div>
    <?php if (!$isBlank && isset($instance)): ?>
    <div class="info-item">
      <label>Due Date</label>
      <span><?= date('d M Y', strtotime($instance['due_date'])) ?><?= $instance['due_time'] ? ' · ' . substr($instance['due_time'],0,5) : '' ?></span>
    </div>
    <div class="info-item">
      <label>Submitted</label>
      <span><?= $instance['submitted_at'] ? date('d M Y H:i', strtotime($instance['submitted_at'])) : '—' ?></span>
    </div>
    <div class="info-item">
      <label>Completed By</label>
      <span><?= h($instance['completed_by_name'] ?? '—') ?></span>
    </div>
    <div class="info-item">
      <label>Assigned To</label>
      <span><?= h($instance['assigned_to_name'] ?? '—') ?></span>
    </div>
    <?php if ($instance['vehicle_reg']): ?>
    <div class="info-item">
      <label>Vehicle</label>
      <span><?= h($instance['vehicle_reg']) ?> — <?= h($instance['vehicle_name']) ?></span>
    </div>
    <?php endif; ?>
    <?php else: ?>
    <div class="info-item">
      <label>Type</label>
      <span><?= h(ucfirst($template['linked_type'])) ?></span>
    </div>
    <div class="info-item">
      <label>Frequency</label>
      <span><?= h(ucfirst($template['frequency'])) ?></span>
    </div>
    <div class="info-item">
      <label>Total Questions</label>
      <span><?= count($allItems) ?></span>
    </div>
    <div class="info-item">
      <label>Date</label>
      <span><?= date('d M Y') ?></span>
    </div>
    <?php endif; ?>
  </div>

  <?php if (!$isBlank && isset($instance)):
    $totalQ   = count($allItems);
    $answered = 0; $yesCount = 0; $noCount = 0; $imgCount = 0;
    foreach ($allItems as $it) {
        if ($it['answer_bool'] !== null || $it['answer_text']) $answered++;
        if ($it['answer_bool'] === '1' || $it['answer_bool'] === 1) $yesCount++;
        if ($it['answer_bool'] === '0' || $it['answer_bool'] === 0) $noCount++;
        $imgCount += count($imagesByItem[$it['id']] ?? []);
    }
  ?>
  <!-- Summary bar -->
  <div class="summary-bar">
    <div class="summary-item"><div class="num"><?= $totalQ ?></div><div class="lbl">Total Questions</div></div>
    <div class="divider"></div>
    <div class="summary-item"><div class="num" style="color:#16a34a"><?= $answered ?></div><div class="lbl">Answered</div></div>
    <div class="divider"></div>
    <div class="summary-item"><div class="num" style="color:#16a34a"><?= $yesCount ?></div><div class="lbl">Yes</div></div>
    <div class="divider"></div>
    <div class="summary-item"><div class="num" style="color:#dc2626"><?= $noCount ?></div><div class="lbl">No</div></div>
    <?php if ($imgCount > 0): ?>
    <div class="divider"></div>
    <div class="summary-item"><div class="num" style="color:#0284c7"><?= $imgCount ?></div><div class="lbl">Photos</div></div>
    <?php endif; ?>
    <?php if ($instance['instance_notes']): ?>
    <div class="summary-item" style="flex:1;text-align:left;padding-left:16px">
      <div class="lbl">Notes</div>
      <div style="font-size:12px;color:#374151;margin-top:3px"><?= h($instance['instance_notes']) ?></div>
    </div>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <!-- Items -->
  <div class="items-title">Checklist Questions (<?= count($allItems) ?>)</div>

  <?php foreach ($allItems as $i => $item): ?>
  <div class="item-row">
    <div class="item-header">
      <span class="item-num"><?= $i + 1 ?></span>
      <span class="item-question"><?= h($item['item_text']) ?><?php if ($item['is_required']): ?><span class="item-required"> *</span><?php endif; ?></span>
      <span class="item-answer-type"><?= $item['answer_type'] === 'yes_no' ? 'Yes / No' : ($item['answer_type'] === 'text' ? 'Text' : 'Number') ?></span>
    </div>

    <?php if ($item['answer_type'] === 'yes_no'): ?>
      <?php if (!$isBlank): ?>
        <div class="answer-yes-no">
          <span class="yn-btn <?= $item['answer_bool'] === '1' || $item['answer_bool'] === 1 ? 'selected-yes' : '' ?>">✓ Yes</span>
          <span class="yn-btn <?= $item['answer_bool'] === '0' || $item['answer_bool'] === 0 ? 'selected-no' : '' ?>">✗ No</span>
        </div>
      <?php else: ?>
        <div class="answer-yes-no">
          <span class="yn-btn">✓ Yes</span>
          <span class="yn-btn">✗ No</span>
        </div>
      <?php endif; ?>

    <?php elseif ($item['answer_type'] === 'text' || $item['answer_type'] === 'number'): ?>
      <?php if (!$isBlank && $item['answer_text']): ?>
        <div class="answer-text"><?= h($item['answer_text']) ?></div>
      <?php else: ?>
        <div class="answer-blank"><div class="answer-blank-lines"><div></div><div></div></div></div>
      <?php endif; ?>
    <?php endif; ?>

    <?php if (!$isBlank && $item['note']): ?>
      <div class="note-row">📝 Note: <?= h($item['note']) ?></div>
    <?php endif; ?>

    <?php
      $uploadBase  = dirname($_SERVER['SCRIPT_NAME']) . '/uploads/';
      $itemImages  = $imagesByItem[$item['id']] ?? [];
    ?>
    <?php if (!$isBlank && !empty($itemImages)): ?>
      <div class="image-grid">
        <?php foreach ($itemImages as $idx => $imgFile): ?>
          <div>
            <img src="<?= h($uploadBase . $imgFile) ?>" alt="Photo <?= $idx + 1 ?>">
            <?php if (count($itemImages) > 1): ?>
              <div class="image-caption">Photo <?= $idx + 1 ?></div>
            <?php endif; ?>
          </div>
        <?php endforeach; ?>
      </div>
    <?php elseif ($item['requires_image'] !== 'never'): ?>
      <div class="image-placeholder">
        📷 Image: <?= $item['requires_image'] === 'always' ? 'Required' : ('Required on ' . ucfirst(str_replace('on_', '', $item['requires_image']))) ?>
        <?php if ($isBlank): ?> — attach photo here<?php endif; ?>
      </div>
    <?php endif; ?>
  </div>
  <?php endforeach; ?>

  <!-- Signature Block (blank form only) -->
  <?php if ($isBlank): ?>
  <div style="margin-top:28px;display:grid;grid-template-columns:1fr 1fr;gap:24px;">
    <div>
      <div style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;margin-bottom:8px">Completed By</div>
      <div style="border-bottom:1.5px solid #374151;margin-bottom:6px;height:32px;"></div>
      <div style="font-size:10px;color:#9ca3af">Full Name &amp; Signature</div>
    </div>
    <div>
      <div style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;margin-bottom:8px">Date &amp; Time</div>
      <div style="border-bottom:1.5px solid #374151;margin-bottom:6px;height:32px;"></div>
      <div style="font-size:10px;color:#9ca3af">DD/MM/YYYY · HH:MM</div>
    </div>
  </div>
  <?php endif; ?>

  <!-- Footer -->
  <div class="footer">
    <span><?= h($companyName) ?> · Checklist System</span>
    <span>Generated: <?= date('d M Y H:i') ?></span>
  </div>

</div>
</body>
</html>