<?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']) || !isset($_POST['template_name'])) {
    echo json_encode(['success' => false, 'message' => 'Template ID and name are required']);
    exit();
}

$conn = new Database();

try {
    $sql = "UPDATE timetable_templates SET
            template_name = :template_name,
            description = :description,
            is_active = :is_active
            WHERE id = :template_id";

    $conn->query($sql);
    $conn->bind(':template_id', $_POST['template_id']);
    $conn->bind(':template_name', $_POST['template_name']);
    $conn->bind(':description', $_POST['description'] ?? '');
    $conn->bind(':is_active', $_POST['is_active'] ?? 1);

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

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