<?php
declare(strict_types=1);

session_start();
require_once '../../config.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

header('Content-Type: application/json');
$conn = getDBConnection();
if (!$conn instanceof mysqli) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

$id = (int) ($_POST['id'] ?? 0);
$paperId = (int) ($_POST['paper_id'] ?? 0);
$className = trim((string) ($_POST['class_name'] ?? ''));
$examDate = trim((string) ($_POST['exam_date'] ?? ''));
$startTime = trim((string) ($_POST['start_time'] ?? ''));
$endTime = trim((string) ($_POST['end_time'] ?? ''));
$venue = trim((string) ($_POST['venue'] ?? ''));
$invigilatorId = (int) ($_POST['invigilator_id'] ?? 0);
$status = trim((string) ($_POST['status'] ?? 'scheduled'));

if ($paperId <= 0 || $className === '' || $examDate === '' || $startTime === '' || $endTime === '') {
    echo json_encode(['success' => false, 'message' => 'Required fields missing']);
    exit;
}
if (strtotime($endTime) <= strtotime($startTime)) {
    echo json_encode(['success' => false, 'message' => 'End time must be after start time']);
    exit;
}

$check = $conn->prepare(
    "SELECT id
     FROM exam_schedules
     WHERE class_name = ? AND exam_date = ? AND id != ?
       AND NOT (end_time <= ? OR start_time >= ?)
     LIMIT 1"
);
$check->bind_param('ssiss', $className, $examDate, $id, $startTime, $endTime);
$check->execute();
$checkResult = $check->get_result();
if ($checkResult->num_rows > 0) {
    $check->close();
    echo json_encode(['success' => false, 'message' => 'Exam clash detected for this class']);
    exit;
}
$check->close();

if ($id > 0) {
    $stmt = $conn->prepare(
        "UPDATE exam_schedules
         SET paper_id = ?, class_name = ?, exam_date = ?, start_time = ?, end_time = ?, venue = ?, invigilator_id = ?, status = ?
         WHERE id = ?"
    );
    $stmt->bind_param('isssssisi', $paperId, $className, $examDate, $startTime, $endTime, $venue, $invigilatorId, $status, $id);
    $stmt->execute();
    $stmt->close();
} else {
    $stmt = $conn->prepare(
        "INSERT INTO exam_schedules
         (paper_id, class_name, exam_date, start_time, end_time, venue, invigilator_id, status)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->bind_param('isssssis', $paperId, $className, $examDate, $startTime, $endTime, $venue, $invigilatorId, $status);
    $stmt->execute();
    $id = $conn->insert_id;
    $stmt->close();
}

echo json_encode(['success' => true, 'message' => 'Schedule saved successfully', 'schedule' => ['id' => $id]]);
