<?php
session_start();
require_once 'includes/database.php';
require_once 'Classes/Timetable.php';

header('Content-Type: application/json');

if(!isset($_SESSION['username']) || !isset($_POST['period_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit();
}

$timetable = new Timetable();
$periodId = $_POST['period_id'];

$data = [
    'period_name' => $_POST['period_name'],
    'start_time' => $_POST['start_time'],
    'end_time' => $_POST['end_time'],
    'duration' => $_POST['duration'],
    'is_break' => isset($_POST['is_break']) ? 1 : 0
];

try {
    if($timetable->updatePeriod($periodId, $data)) {
        echo json_encode(['success' => true, 'message' => 'Period updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update period']);
    }
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}