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

// Validate required fields
$required = ['class_id', 'section_id', 'subject_id', 'teacher_id', 'day_id', 'period_id'];
foreach($required as $field) {
    if(!isset($_POST[$field]) || empty($_POST[$field])) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        exit();
    }
}

$timetable = new Timetable();

$data = [
    'class_id' => $_POST['class_id'],
    'section_id' => $_POST['section_id'],
    'subject_id' => $_POST['subject_id'],
    'teacher_id' => $_POST['teacher_id'],
    'day_id' => $_POST['day_id'],
    'period_id' => $_POST['period_id'],
    'room_number' => $_POST['room_number'] ?? null,
    'academic_year' => $_POST['academic_year'] ?? null,
    'term' => $_POST['term'] ?? null,
    'notes' => $_POST['notes'] ?? null,
    'created_by' => $_SESSION['username']
];

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