<?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['class_id']) || !isset($_POST['section_id'])) {
    echo json_encode(['success' => false, 'message' => 'Class and section required']);
    exit();
}

$conn = new Database();

try {
    $sql = "SELECT t.*,
            (SELECT COUNT(*) FROM timetable_template_details WHERE template_id = t.id) as entry_count,
            DATE_FORMAT(t.created_at, '%M %d, %Y') as created_date
            FROM timetable_templates t
            WHERE t.class_id = :class_id 
            AND t.section_id = :section_id
            AND t.is_active = 1
            ORDER BY t.created_at DESC";

    $conn->query($sql);
    $conn->bind(':class_id', $_POST['class_id']);
    $conn->bind(':section_id', $_POST['section_id']);

    $templates = $conn->fetchMultiple();

    if($conn->rowCount() > 0) {
        echo json_encode([
            'success' => true,
            'templates' => $templates
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'No templates found',
            'templates' => []
        ]);
    }

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