<?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 {
    $sql = "DELETE FROM timetable 
            WHERE class_id = :class_id AND section_id = :section_id";

    if($academicYear) {
        $sql .= " AND academic_year = :academic_year";
    }
    if($term) {
        $sql .= " AND term = :term";
    }

    $timetable->query($sql);
    $timetable->bind(':class_id', $classId);
    $timetable->bind(':section_id', $sectionId);
    if($academicYear) $timetable->bind(':academic_year', $academicYear);
    if($term) $timetable->bind(':term', $term);

    if($timetable->execute()) {
        echo json_encode(['success' => true, 'message' => 'Timetable cleared successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to clear timetable']);
    }
} catch(Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}