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

$timetable = new Timetable();
$entryId = $_POST['entry_id'];

$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,
    'notes' => $_POST['notes'] ?? null
];

try {
    $result = $timetable->updateTimetableEntry($entryId, $data);

    if($result === true) {
        echo json_encode(['success' => true, 'message' => 'Entry updated successfully']);
    } else if(is_array($result)) {
        echo json_encode($result);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update entry']);
    }
} catch(Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}