<?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['teacher_id'])) {
    echo json_encode(['success' => false, 'message' => 'Teacher ID required']);
    exit();
}

$timetable = new Timetable();
$teacherId = $_POST['teacher_id'];
$academicYear = $_POST['academic_year'] ?? null;
$term = $_POST['term'] ?? null;

try {
    // Get teacher info
    $sql = "SELECT id, name, email, phone, photo FROM teachers WHERE id = :teacher_id";
    $timetable->query($sql);
    $timetable->bind(':teacher_id', $teacherId);
    $teacher = $timetable->fetchSingle();

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

    // Get teacher timetable
    $entries = $timetable->getTeacherTimetable($teacherId, $academicYear, $term);

    // Get workload statistics
    $workload = $timetable->getTeacherWorkload($teacherId, $academicYear, $term);

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

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

    // Format timetable entries
    $formattedEntries = [];
    if($entries) {
        foreach($entries as $entry) {
            $formattedEntries[] = [
                'id' => $entry->id,
                'class_name' => $entry->class_name,
                'section_name' => $entry->section_name,
                'subject_name' => $entry->subject_name,
                'day_id' => $entry->day_id,
                'period_id' => $entry->period_id,
                'room_number' => $entry->room_number
            ];
        }
    }

    // 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,
        'teacher' => [
            'name' => $teacher->name,
            'email' => $teacher->email,
            'phone' => $teacher->phone,
            'photo' => !empty($teacher->photo) ? './upload/' . $teacher->photo : './upload/default.png'
        ],
        'workload' => [
            'total_periods' => $workload->total_periods ?? 0,
            'teaching_days' => $workload->teaching_days ?? 0,
            'classes_taught' => $workload->classes_taught ?? 0
        ],
        'timetable' => $formattedEntries,
        'days' => $formattedDays,
        'periods' => $formattedPeriods
    ]);

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