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

$user = requireRole([1, 2, 5]);
$db   = getDB();

$id          = (int)post('id', 0);
$name        = trim(post('name', ''));
$description = trim(post('description', ''));
$frequency   = post('frequency', 'once');
$startsAt    = post('starts_at') ?: null;
$endsAt      = post('ends_at') ?: null;
$isActive    = post('is_active', 1) ? 1 : 0;
$linkedType  = post('linked_type', 'general');
$vehicleId   = post('fleet_vehicle_id') ? (int)post('fleet_vehicle_id') : null;
$assignedTo  = post('assigned_to') ? (int)post('assigned_to') : null;
$items       = post('items', []);

if (!$name)  apiError('Checklist name is required.', 422);
if (!is_array($items)) $items = [];

try {
    $db->beginTransaction();

    if ($id) {
        $db->prepare("
            UPDATE checklist_templates SET
                name             = ?,
                description      = ?,
                frequency        = ?,
                starts_at        = ?,
                ends_at          = ?,
                is_active        = ?,
                linked_type      = ?,
                fleet_vehicle_id = ?,
                assigned_to      = ?
            WHERE id = ?
        ")->execute([
            $name, $description, $frequency,
            $startsAt, $endsAt, $isActive,
            $linkedType, $vehicleId, $assignedTo,
            $id
        ]);
        $id_was_edit = true;
    } else {
        $db->prepare("
            INSERT INTO checklist_templates
                (name, description, frequency, starts_at, ends_at, is_active, linked_type, fleet_vehicle_id, assigned_to, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ")->execute([
            $name, $description, $frequency,
            $startsAt, $endsAt, $isActive,
            $linkedType, $vehicleId, $assignedTo,
            $user['id']
        ]);
        $id = (int)$db->lastInsertId();
        $id_was_edit = false;
    }

    // Rebuild items
    $db->prepare("DELETE FROM checklist_template_items WHERE template_id = ?")->execute([$id]);
    $sort = 0;
    foreach ($items as $item) {
        $text = trim($item['item_text'] ?? '');
        if (!$text) continue;
        $answerType    = in_array($item['answer_type'] ?? '', ['yes_no', 'text', 'number']) ? $item['answer_type'] : 'yes_no';
        $requiresImage = in_array($item['requires_image'] ?? '', ['never', 'always', 'on_yes', 'on_no']) ? $item['requires_image'] : 'never';
        $isRequired    = isset($item['is_required']) ? ($item['is_required'] ? 1 : 0) : 1;
        $requiresPhoto = in_array($requiresImage, ['always', 'on_yes', 'on_no']) ? 1 : 0;
        $requiresNote  = ($answerType === 'text') ? 1 : 0;

        $db->prepare("
            INSERT INTO checklist_template_items
                (template_id, item_text, answer_type, requires_image, is_required, requires_photo, requires_note, sort_order)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ")->execute([$id, $text, $answerType, $requiresImage, $isRequired, $requiresPhoto, $requiresNote, $sort++]);
    }

    // ── Seed initial instances immediately (cron handles ongoing generation) ─
    if ($isActive && !$id_was_edit) {
        $today = date('Y-m-d');
        $seedDates = [];

        if ($frequency === 'once' && $startsAt && $startsAt >= $today) {
            $seedDates = [$startsAt];

        } elseif ($frequency === 'daily') {
            // Seed today through end of current month
            $end = date('Y-m-t');
            $d = new DateTime($startsAt && $startsAt >= $today ? $startsAt : $today);
            $endDt = new DateTime($end);
            while ($d <= $endDt) { $seedDates[] = $d->format('Y-m-d'); $d->modify('+1 day'); }

        } elseif ($frequency === 'weekly') {
            // Seed all weekly occurrences this month
            $anchor = new DateTime($startsAt ?: $today);
            $dow    = (int)$anchor->format('N');
            $cursor = new DateTime($startsAt && $startsAt >= $today ? $startsAt : $today);
            $curDow = (int)$cursor->format('N');
            $diff   = ($dow - $curDow + 7) % 7;
            if ($diff) $cursor->modify("+{$diff} days");
            $endOfMonth = new DateTime(date('Y-m-t'));
            while ($cursor <= $endOfMonth) {
                $seedDates[] = $cursor->format('Y-m-d');
                $cursor->modify('+1 week');
            }

        } elseif ($frequency === 'monthly') {
            // Seed this month's instance
            $anchor = new DateTime($startsAt ?: $today);
            $targetDay = (int)$anchor->format('j');
            $thisMonthDate = date('Y-m-') . str_pad($targetDay, 2, '0', STR_PAD_LEFT);
            if ($thisMonthDate >= $today) $seedDates = [$thisMonthDate];
        }

        foreach ($seedDates as $seedDate) {
            $exists = $db->prepare("SELECT id FROM checklist_instances WHERE template_id = ? AND due_date = ? LIMIT 1");
            $exists->execute([$id, $seedDate]);
            if (!$exists->fetch()) {
                $db->prepare("
                    INSERT INTO checklist_instances (template_id, user_id, vehicle_id, due_date, status)
                    VALUES (?, ?, ?, ?, 'pending')
                ")->execute([$id, $assignedTo ?? 0, $vehicleId, $seedDate]);
            }
        }
    }

    $db->commit();

    $freqNote = match($frequency) {
        'daily'   => ' The cron will generate instances 14 days ahead daily.',
        'weekly'  => ' The cron will generate instances 8 weeks ahead daily.',
        'monthly' => ' The cron will generate instances 3 months ahead daily.',
        default   => ''
    };

    apiSuccess(['id' => $id], ($id ? 'Template saved.' : 'Template created.') . $freqNote);

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