<?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('Instance ID required.', 422);

$stmt = $db->prepare("
    SELECT ci.*,
           t.name AS template_name, t.description AS template_description,
           t.linked_type, t.frequency,
           u.full_name AS assigned_to_name,
           cb.full_name AS completed_by_name,
           v.registration AS vehicle_reg, v.make AS vehicle_make, v.model AS vehicle_model
    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 = ?
");
$stmt->execute([$id]);
$instance = $stmt->fetch();
if (!$instance) apiError('Instance not found.', 404);

// Fetch template items with existing answers
$items = $db->prepare("
    SELECT ti.*,
           cii.id AS answer_id, cii.is_checked, cii.answer_text, cii.answer_bool,
           cii.note, cii.photo_filename, cii.image_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([$id, $instance['template_id']]);
$itemRows = $items->fetchAll();

// Fetch all images for this instance (multi-image support)
$imgStmt = $db->prepare("
    SELECT id, template_item_id, filename
    FROM checklist_item_images
    WHERE instance_id = ?
    ORDER BY uploaded_at ASC
");
$imgStmt->execute([$id]);
$allImages = $imgStmt->fetchAll();

// Group images by template_item_id
$imagesByItem = [];
foreach ($allImages as $img) {
    $imagesByItem[$img['template_item_id']][] = ['id' => $img['id'], 'filename' => $img['filename']];
}

// Attach images array to each item
foreach ($itemRows as &$item) {
    $item['images'] = $imagesByItem[$item['id']] ?? [];
    // Fallback: if no multi-image rows but legacy single image exists, wrap it
    if (empty($item['images']) && !empty($item['image_filename'])) {
        $item['images'] = [['id' => 0, 'filename' => $item['image_filename']]];
    }
}
unset($item);

$instance['items'] = $itemRows;

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