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

$required = ['template_id', 'class_id', 'section_id', 'academic_year', 'term', 'load_option'];
foreach($required as $field) {
    if(!isset($_POST[$field])) {
        echo json_encode(['success' => false, 'message' => 'Missing required field: ' . $field]);
        exit();
    }
}

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

try {
    // If replace option, clear existing entries
    if($_POST['load_option'] === 'replace') {
        $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', $_POST['class_id']);
        $conn->bind(':section_id', $_POST['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 template'
        ]);
        exit();
    }

    $created = 0;
    $skipped = 0;

    foreach($entries as $entry) {
        $data = [
            'class_id' => $_POST['class_id'],
            'section_id' => $_POST['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' => $_POST['created_by'] ?? $_SESSION['username']
        ];

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

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

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

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