<?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();
}

// Validate required fields
if(!isset($_POST['template_name']) || !isset($_POST['class_id']) || !isset($_POST['section_id'])) {
    echo json_encode(['success' => false, 'message' => 'Template name, class and section are required']);
    exit();
}

$conn = new Database();

try {
    $sql = "INSERT INTO timetable_templates 
            (template_name, description, class_id, section_id, academic_year, created_by, is_active)
            VALUES 
            (:template_name, :description, :class_id, :section_id, :academic_year, :created_by, 1)";

    $conn->query($sql);
    $conn->bind(':template_name', $_POST['template_name']);
    $conn->bind(':description', $_POST['description'] ?? '');
    $conn->bind(':class_id', $_POST['class_id']);
    $conn->bind(':section_id', $_POST['section_id']);
    $conn->bind(':academic_year', $_POST['academic_year'] ?? null);
    $conn->bind(':created_by', $_POST['created_by'] ?? $_SESSION['username']);

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

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