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

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

$instanceId = (int)post('instance_id', 0);
$answers    = post('answers', []);   // array of {item_id, answer_bool, answer_text, note}
$notes      = post('notes', '');
$action     = post('action', 'save'); // save | submit

if (!$instanceId) apiError('Instance ID required.', 422);
if (!is_array($answers)) $answers = [];

$stmt = $db->prepare("SELECT * FROM checklist_instances WHERE id = ?");
$stmt->execute([$instanceId]);
$instance = $stmt->fetch();
if (!$instance) apiError('Instance not found.', 404);

if ($instance['status'] === 'completed') apiError('This checklist has already been submitted.', 409);

try {
    $db->beginTransaction();

    // Mark as in_progress when first saving
    if ($instance['status'] === 'pending') {
        $db->prepare("UPDATE checklist_instances SET status = 'in_progress', started_at = NOW() WHERE id = ?")->execute([$instanceId]);
    }

    // Upsert each answer
    foreach ($answers as $ans) {
        $itemId     = (int)($ans['item_id'] ?? 0);
        if (!$itemId) continue;

        $answerBool = isset($ans['answer_bool']) && $ans['answer_bool'] !== '' ? ($ans['answer_bool'] ? 1 : 0) : null;
        $answerText = isset($ans['answer_text']) ? trim($ans['answer_text']) : null;
        $note       = isset($ans['note']) ? trim($ans['note']) : null;
        $isChecked  = ($answerBool !== null) ? $answerBool : ($answerText ? 1 : 0);

        // Check if exists
        $ex = $db->prepare("SELECT id FROM checklist_instance_items WHERE instance_id = ? AND template_item_id = ?");
        $ex->execute([$instanceId, $itemId]);
        $existing = $ex->fetch();

        if ($existing) {
            $db->prepare("
                UPDATE checklist_instance_items SET
                    is_checked   = ?,
                    answer_bool  = ?,
                    answer_text  = ?,
                    note         = ?,
                    completed_at = NOW()
                WHERE id = ?
            ")->execute([$isChecked, $answerBool, $answerText ?: null, $note ?: null, $existing['id']]);
        } else {
            $db->prepare("
                INSERT INTO checklist_instance_items
                    (instance_id, template_item_id, is_checked, answer_bool, answer_text, note, completed_at)
                VALUES (?, ?, ?, ?, ?, ?, NOW())
            ")->execute([$instanceId, $itemId, $isChecked, $answerBool, $answerText ?: null, $note ?: null]);
        }
    }

    if ($notes !== '') {
        $db->prepare("UPDATE checklist_instances SET instance_notes = ? WHERE id = ?")->execute([$notes, $instanceId]);
    }

    if ($action === 'submit') {
        // Validate required items are answered
        $requiredItems = $db->prepare("
            SELECT ti.id, ti.item_text
            FROM checklist_template_items ti
            WHERE ti.template_id = (SELECT template_id FROM checklist_instances WHERE id = ?)
              AND ti.is_required = 1
        ");
        $requiredItems->execute([$instanceId]);
        $required = $requiredItems->fetchAll();

        foreach ($required as $req) {
            $answered = $db->prepare("SELECT id FROM checklist_instance_items WHERE instance_id = ? AND template_item_id = ?");
            $answered->execute([$instanceId, $req['id']]);
            if (!$answered->fetch()) {
                $db->rollBack();
                apiError('Required item not answered: "' . $req['item_text'] . '"', 422);
            }
        }

        $db->prepare("
            UPDATE checklist_instances SET
                status       = 'completed',
                completed_by = ?,
                submitted_at = NOW()
            WHERE id = ?
        ")->execute([$user['id'], $instanceId]);
    }

    $db->commit();

    // ── Email notification: checklist_completed ───────────
    if ($action === 'submit') {
        try {
            require_once __DIR__ . '/../config/mailer.php';
            require_once __DIR__ . '/../emails/templates.php';
            $rule = getNotifRule($db, 'checklist_completed');
            if ($rule && $rule['is_enabled']) {
                $instFull = $db->prepare("
                    SELECT ci.*, ct.name AS template_name,
                           v.registration AS vehicle_reg, CONCAT(v.make,' ',v.model) AS vehicle_make,
                           (SELECT COUNT(*) FROM checklist_instance_items WHERE instance_id=ci.id) AS total_items,
                           (SELECT COUNT(*) FROM checklist_instance_items WHERE instance_id=ci.id AND (is_checked=1 OR answer_text IS NOT NULL)) AS answered_items
                    FROM checklist_instances ci
                    JOIN checklist_templates ct ON ct.id=ci.template_id
                    LEFT JOIN fleet_vehicles v ON v.id=ci.vehicle_id
                    WHERE ci.id=? LIMIT 1
                ");
                $instFull->execute([$instanceId]);
                $inst = $instFull->fetch();
                if ($inst) {
                    $completedBy = $user['full_name'];
                    $cfg         = getMailerConfig($db);
                    $appUrl      = $cfg['email_app_url'] ?? '';
                    $adminEmail  = getAdminEmail($db);
                    $subject     = "✅ Checklist Completed: " . $inst['template_name'];
                    if ($rule['notify_admin'] && $adminEmail) {
                        $html = tplChecklistCompleted($inst, 'Admin', $completedBy, $appUrl);
                        queueEmail($db, 'checklist_completed', $adminEmail, 'Admin', $subject, $html, 'checklist', $instanceId);
                    }
                }
            }
        } catch (Exception $ignored) {}
    }

    apiSuccess(['instance_id' => $instanceId], $action === 'submit' ? 'Checklist submitted.' : 'Progress saved.');

} catch (Exception $e) {
    $db->rollBack();
    apiError('Failed to save: ' . $e->getMessage(), 500);
}