<?php
session_start();
include '../includes/database.php';
include '../includes/functions.php';

//header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$conn = new Functions();

try {
    $template_id = (int)$_POST['id'];

    if ($template_id <= 0) {
        throw new Exception("Invalid template ID");
    }

    // Check if template is being used
    $sql = "SELECT COUNT(*) FROM student_results WHERE template_id = :template_id";
    $conn->query($sql);
    $conn->bind(':template_id', $template_id);
    $usage_count = $conn->fetchColumn();

    if ($usage_count > 0) {
        throw new Exception("Cannot delete template. It is currently being used by $usage_count student records.");
    }

    // Delete template (components will be deleted automatically due to foreign key cascade)
    $sql = "DELETE FROM assessment_templates WHERE id = :id";
    $conn->query($sql);
    $conn->bind(':id', $template_id);
    $conn->execute();

    echo json_encode(['success' => true, 'message' => 'Template deleted successfully']);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}