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

$timetable = new Timetable();
$classId = $_POST['class_id'];
$sectionId = $_POST['section_id'];
$academicYear = $_POST['academic_year'] ?? null;
$term = $_POST['term'] ?? null;

try {
    // Get class and section names
    $sql = "SELECT c.name as class_name, s.name as section_name
            FROM classes c, sections s
            WHERE c.id = :class_id AND s.id = :section_id";
    $timetable->query($sql);
    $timetable->bind(':class_id', $classId);
    $timetable->bind(':section_id', $sectionId);
    $classInfo = $timetable->fetchSingle();

    // Get timetable entries
    $entries = $timetable->getClassTimetable($classId, $sectionId, $academicYear, $term);

    // Get active days
    $days = $timetable->getActiveDays();

    // Get all periods
    $periods = $timetable->getAllPeriods();

    // Format entries
    $formattedEntries = [];
    if($entries) {
        foreach($entries as $entry) {
            $formattedEntries[] = [
                'id' => $entry->id,
                'subject_id' => $entry->subject_id,
                'subject_name' => $entry->subject_name,
                'teacher_id' => $entry->teacher_id,
                'teacher_name' => $entry->teacher_name,
                'day_id' => $entry->day_id,
                'period_id' => $entry->period_id,
                'room_number' => $entry->room_number,
                'notes' => $entry->notes
            ];
        }
    }

    // Format days
    $formattedDays = [];
    foreach($days as $day) {
        $formattedDays[] = [
            'id' => $day->id,
            'day_name' => $day->day_name,
            'day_number' => $day->day_number
        ];
    }

    // Format periods
    $formattedPeriods = [];
    foreach($periods as $period) {
        $formattedPeriods[] = [
            'id' => $period->id,
            'period_name' => $period->period_name,
            'period_number' => $period->period_number,
            'start_time' => date('h:i A', strtotime($period->start_time)),
            'end_time' => date('h:i A', strtotime($period->end_time)),
            'is_break' => $period->is_break
        ];
    }

    echo json_encode([
        'success' => true,
        'data' => [
            'class_name' => $classInfo->class_name,
            'section_name' => $classInfo->section_name,
            'entries' => $formattedEntries
        ],
        'days' => $formattedDays,
        'periods' => $formattedPeriods
    ]);

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