<?php
session_start();
require_once 'includes/database.php';
require_once 'Classes/Timetable.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['academic_year']) || !isset($_POST['term'])) {
    echo json_encode(['success' => false, 'message' => 'Template ID, academic year and term are required']);
    exit();
}

$conn = new Database();
$timetable = new Timetable();

try {
    // Get template details
    $sql = "SELECT * FROM timetable_templates WHERE id = :template_id";
    $conn->query($sql);
    $conn->bind(':template_id', $_POST['template_id']);
    $template = $conn->fetchSingle();

    if(!$template) {
        echo json_encode(['success' => false, 'message' => 'Template not found']);
        exit();
    }

    // Clear existing entries if requested
    if(isset($_POST['clear_existing']) && $_POST['clear_existing'] == 'on') {
        $sql = "DELETE FROM timetable 
                WHERE class_id = :class_id 
                AND section_id = :section_id 
                AND academic_year = :academic_year 
                AND term = :term";

        $conn->query($sql);
        $conn->bind(':class_id', $template->class_id);
        $conn->bind(':section_id', $template->section_id);
        $conn->bind(':academic_year', $_POST['academic_year']);
        $conn->bind(':term', $_POST['term']);
        $conn->execute();
    }

    // Get template entries
    $sql = "SELECT * FROM timetable_template_details WHERE template_id = :template_id";
    $conn->query($sql);
    $conn->bind(':template_id', $_POST['template_id']);
    $entries = $conn->fetchMultiple();

    if(empty($entries)) {
        echo json_encode(['success' => false, 'message' => 'No entries found in this template']);
        exit();
    }

    $created = 0;
    $errors = [];

    foreach($entries as $entry) {
        $data = [
            'class_id' => $template->class_id,
            'section_id' => $template->section_id,
            'subject_id' => $entry->subject_id,
            'teacher_id' => $entry->teacher_id,
            'day_id' => $entry->day_id,
            'period_id' => $entry->period_id,
            'room_number' => $entry->room_number,
            'academic_year' => $_POST['academic_year'],
            'term' => $_POST['term'],
            'created_by' => $_SESSION['username']
        ];

        $result = $timetable->createTimetableEntry($data);

        if($result['success']) {
            $created++;
        } else {
            $errors[] = $result;
        }
    }

    echo json_encode([
        'success' => true,
        'message' => 'Template applied successfully',
        'created' => $created,
        'total' => count($entries),
        'errors' => $errors
    ]);

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