<?php
declare(strict_types=1);

session_start();
require_once '../../../config.php';
require_once dirname(__DIR__) . '/helpers.php';

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

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

$conn = getDBConnection();
if (!$conn) {
    echo json_encode(['conflict' => false, 'details' => 'Database unavailable']);
    exit;
}

$teacherId = isset($_POST['teacher_id']) ? (int) $_POST['teacher_id'] : 0;
$periodId = isset($_POST['period_id']) ? (int) $_POST['period_id'] : 0;
$excludeSlotId = isset($_POST['exclude_slot_id']) ? (int) $_POST['exclude_slot_id'] : 0;
$dayOfWeek = trim((string) ($_POST['day_of_week'] ?? ''));
$academicYear = trim((string) ($_POST['academic_year'] ?? ''));
$term = trim((string) ($_POST['term'] ?? ''));

if ($teacherId <= 0 || $periodId <= 0 || $dayOfWeek === '' || $academicYear === '' || $term === '') {
    echo json_encode(['conflict' => false, 'details' => '']);
    exit;
}

$conflict = timetableFindTeacherConflict($conn, $teacherId, $dayOfWeek, $periodId, $academicYear, $term, $excludeSlotId);
if (!$conflict) {
    echo json_encode(['conflict' => false, 'details' => '']);
    exit;
}

$details = 'Teacher ' . ($conflict['teacher_name'] ?? 'Unknown') .
    ' already has ' . ($conflict['subject_name'] ?? 'a subject') .
    ' in ' . ($conflict['class_name'] ?? 'another class') . ' at this time';
echo json_encode(['conflict' => true, 'details' => $details]);

