<?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(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
$className = trim((string) ($_POST['class_name'] ?? ''));
$dayOfWeek = trim((string) ($_POST['day_of_week'] ?? ''));
$periodId = isset($_POST['period_id']) ? (int) $_POST['period_id'] : 0;
$subjectId = isset($_POST['subject_id']) ? (int) $_POST['subject_id'] : 0;
$teacherId = isset($_POST['teacher_id']) ? (int) $_POST['teacher_id'] : 0;
$room = trim((string) ($_POST['room'] ?? ''));
$academicYear = trim((string) ($_POST['academic_year'] ?? ''));
$term = trim((string) ($_POST['term'] ?? ''));
$forceSave = !empty($_POST['force_save']) ? 1 : 0;

if ($className === '' || $dayOfWeek === '' || $periodId <= 0 || $subjectId <= 0 || $teacherId <= 0 || $academicYear === '' || $term === '') {
    echo json_encode(['success' => false, 'message' => 'All required fields must be provided.']);
    exit;
}

$conflict = timetableFindTeacherConflict($conn, $teacherId, $dayOfWeek, $periodId, $academicYear, $term, $id);
if ($conflict && $forceSave === 0) {
    $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(['success' => false, 'message' => $details, 'conflict' => true]);
    exit;
}

if ($id > 0) {
    $stmt = $conn->prepare(
        "UPDATE timetable_slots
         SET class_name = ?, day_of_week = ?, period_id = ?, subject_id = ?, teacher_id = ?, room = ?, academic_year = ?, term = ?
         WHERE id = ?"
    );
    $stmt->bind_param('ssiiisssi', $className, $dayOfWeek, $periodId, $subjectId, $teacherId, $room, $academicYear, $term, $id);
    $stmt->execute();
    $stmt->close();
} else {
    $stmt = $conn->prepare(
        "INSERT INTO timetable_slots (class_name, day_of_week, period_id, subject_id, teacher_id, room, academic_year, term)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)
         ON DUPLICATE KEY UPDATE
           subject_id = VALUES(subject_id),
           teacher_id = VALUES(teacher_id),
           room = VALUES(room),
           updated_at = CURRENT_TIMESTAMP"
    );
    $stmt->bind_param('ssiiisss', $className, $dayOfWeek, $periodId, $subjectId, $teacherId, $room, $academicYear, $term);
    $stmt->execute();
    if ($stmt->insert_id > 0) {
        $id = (int) $stmt->insert_id;
    } else {
        $findStmt = $conn->prepare(
            "SELECT id FROM timetable_slots
             WHERE class_name = ? AND day_of_week = ? AND period_id = ? AND academic_year = ? AND term = ?
             LIMIT 1"
        );
        $findStmt->bind_param('ssiss', $className, $dayOfWeek, $periodId, $academicYear, $term);
        $findStmt->execute();
        $slotRow = $findStmt->get_result()->fetch_assoc();
        $id = (int) ($slotRow['id'] ?? 0);
        $findStmt->close();
    }
    $stmt->close();
}

$fetchStmt = $conn->prepare(
    "SELECT ts.*, s.subject_name, st.full_name AS teacher_name, p.period_name, p.start_time, p.end_time, p.is_break, p.order_no
     FROM timetable_slots ts
     LEFT JOIN subjects s ON ts.subject_id = s.id
     LEFT JOIN staff st ON ts.teacher_id = st.id
     LEFT JOIN timetable_periods p ON ts.period_id = p.id
     WHERE ts.id = ?
     LIMIT 1"
);
$fetchStmt->bind_param('i', $id);
$fetchStmt->execute();
$slot = $fetchStmt->get_result()->fetch_assoc();
$fetchStmt->close();

echo json_encode(['success' => true, 'message' => 'Timetable slot saved successfully.', 'slot' => $slot]);

