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

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

if(!isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if(!isset($_POST['template_id'])) {
    echo json_encode(['success' => false, 'message' => 'Template ID is required']);
    exit();
}

$conn = new Database();

try {
    // Delete template (template_details will be deleted automatically due to CASCADE)
    $sql = "DELETE FROM timetable_templates WHERE id = :template_id";
    $conn->query($sql);
    $conn->bind(':template_id', $_POST['template_id']);

    if($conn->execute()) {
        echo json_encode([
            'success' => true,
            'message' => 'Template deleted successfully'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to delete template'
        ]);
    }

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