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

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

$templateId = (int)post('template_id', 0);
$dueDate    = post('due_date', date('Y-m-d'));
$dueTime    = post('due_time') ?: null;
$assignedTo = post('assigned_to') ? (int)post('assigned_to') : (int)$user['id'];

if (!$templateId) apiError('Template ID required.', 422);

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

// Check for existing PENDING/IN_PROGRESS instance — warn but allow override
$exists = $db->prepare("
    SELECT id, status FROM checklist_instances
    WHERE template_id = ? AND due_date = ? AND user_id = ?
    LIMIT 1
");
$exists->execute([$templateId, $dueDate, $assignedTo]);
$ex = $exists->fetch();

if ($ex && in_array($ex['status'], ['pending', 'in_progress'])) {
    // Return existing pending instance (not a completed one)
    apiSuccess(['id' => $ex['id'], 'existing' => true], 'Instance already exists for this date.');
}
// If completed/missed — create a fresh instance

$db->prepare("
    INSERT INTO checklist_instances (template_id, user_id, due_date, due_time, status)
    VALUES (?, ?, ?, ?, 'pending')
")->execute([$templateId, $assignedTo, $dueDate, $dueTime]);

$instanceId = (int)$db->lastInsertId();

apiSuccess(['id' => $instanceId, 'existing' => false], 'Checklist instance created.');