<?php
declare(strict_types=1);

session_start();
require_once '../../../config.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;
}

$slotId = isset($_POST['slot_id']) ? (int) $_POST['slot_id'] : 0;
$originalTeacherId = isset($_POST['original_teacher_id']) && $_POST['original_teacher_id'] !== '' ? (int) $_POST['original_teacher_id'] : null;
$substituteTeacherId = isset($_POST['substitute_teacher_id']) ? (int) $_POST['substitute_teacher_id'] : 0;
$substitutionDate = trim((string) ($_POST['substitution_date'] ?? ''));
$reason = trim((string) ($_POST['reason'] ?? ''));
$recordedBy = (int) $_SESSION['user_id'];

if ($slotId <= 0 || $substituteTeacherId <= 0 || $substitutionDate === '') {
    echo json_encode(['success' => false, 'message' => 'All required substitution fields must be completed.']);
    exit;
}

$stmt = $conn->prepare(
    "INSERT INTO timetable_substitutions
     (slot_id, original_teacher_id, substitute_teacher_id, substitution_date, reason, recorded_by)
     VALUES (?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param('iiissi', $slotId, $originalTeacherId, $substituteTeacherId, $substitutionDate, $reason, $recordedBy);
$stmt->execute();
$stmt->close();

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