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

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

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

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

try {
    $db->beginTransaction();

    // ── Find future pending instances (safe to delete) ────────
    $futureStmt = $db->prepare("
        SELECT id FROM checklist_instances
        WHERE template_id = ?
          AND status IN ('pending', 'in_progress')
          AND due_date >= CURDATE()
    ");
    $futureStmt->execute([$id]);
    $futureIds = $futureStmt->fetchAll(PDO::FETCH_COLUMN);

    if (!empty($futureIds)) {
        $placeholders = implode(',', array_fill(0, count($futureIds), '?'));

        // Delete answers for those instances
        $db->prepare("
            DELETE FROM checklist_instance_items
            WHERE instance_id IN ($placeholders)
        ")->execute($futureIds);

        // Delete the instances
        $db->prepare("
            DELETE FROM checklist_instances
            WHERE id IN ($placeholders)
        ")->execute($futureIds);

        // Delete matching calendar events for those dates
        $datesStmt = $db->prepare("
            SELECT DISTINCT due_date FROM checklist_instances
            WHERE id IN ($placeholders)
        ");
        // (already deleted above — grab dates from futureIds via a different approach)
    }

    // Also delete future calendar events by title + date
    // We stored them as "✅ Checklist: {name}" so match on title
    $db->prepare("
        DELETE FROM calendar_events
        WHERE title = ?
          AND event_date >= CURDATE()
    ")->execute(['✅ Checklist: ' . $t['name']]);

    // ── Check if any historical records remain ────────────────
    $historyStmt = $db->prepare("
        SELECT COUNT(*) FROM checklist_instances
        WHERE template_id = ?
          AND status IN ('completed', 'missed')
    ");
    $historyStmt->execute([$id]);
    $hasHistory = (int)$historyStmt->fetchColumn() > 0;

    if ($hasHistory) {
        // Soft delete — keep template for historical reference, just deactivate
        $db->prepare("
            UPDATE checklist_templates SET is_active = 0 WHERE id = ?
        ")->execute([$id]);

        $db->commit();
        apiSuccess([
            'deleted'    => false,
            'deactivated' => true,
            'future_removed' => count($futureIds),
        ], 'Template deactivated and ' . count($futureIds) . ' future instance(s) removed. Historical records kept.');

    } else {
        // Full delete — no history to preserve
        $db->prepare("DELETE FROM checklist_template_items WHERE template_id = ?")->execute([$id]);
        $db->prepare("DELETE FROM checklist_instances WHERE template_id = ?")->execute([$id]);
        $db->prepare("DELETE FROM checklist_templates WHERE id = ?")->execute([$id]);

        $db->commit();
        apiSuccess([
            'deleted' => true,
            'future_removed' => count($futureIds),
        ], 'Template fully deleted.');
    }

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