<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();

$id = (int)post('id', 0);
if (!$id) apiError('Template ID required.', 422);

$stmt = $db->prepare("
    SELECT t.*,
           u.full_name AS created_by_name,
           ua.full_name AS assigned_to_name,
           v.registration AS vehicle_reg, v.make AS vehicle_make, v.model AS vehicle_model
    FROM checklist_templates t
    LEFT JOIN users u  ON u.id = t.created_by
    LEFT JOIN users ua ON ua.id = t.assigned_to
    LEFT JOIN fleet_vehicles v ON v.id = t.fleet_vehicle_id
    WHERE t.id = ?
");
$stmt->execute([$id]);
$template = $stmt->fetch();
if (!$template) apiError('Template not found.', 404);

$items = $db->prepare("
    SELECT * FROM checklist_template_items
    WHERE template_id = ?
    ORDER BY sort_order ASC, id ASC
");
$items->execute([$id]);
$template['items'] = $items->fetchAll();

apiSuccess(['template' => $template]);
