<?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;

}



if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    echo json_encode(['success' => false, 'message' => 'Invalid request']);

    exit;

}



$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;

$periodName = trim((string) ($_POST['period_name'] ?? ''));

$startTime = trim((string) ($_POST['start_time'] ?? ''));

$endTime = trim((string) ($_POST['end_time'] ?? ''));

$orderNo = isset($_POST['order_no']) ? (int) $_POST['order_no'] : 0;

$className = trim((string) ($_POST['class_name'] ?? ''));



// Period type: either one of the known types, or a school-defined one typed

// into the "Other" box. Custom types are remembered for this school so the

// editor offers them again next time.

$knownTypes = timetablePeriodTypes($conn);

$periodType = trim((string) ($_POST['period_type'] ?? 'teaching'));

$customLabel = trim((string) ($_POST['period_type_custom'] ?? ''));



if ($periodType === '__other__' || ($customLabel !== '' && !isset($knownTypes[$periodType]))) {

    $slug = timetableSlugifyPeriodType($customLabel);

    if ($slug === '') {

        echo json_encode(['success' => false, 'message' => 'Enter a name for the custom period type.']);

        exit;

    }

    $periodType = $slug;

    timetableRegisterCustomPeriodType($conn, $slug, $customLabel);

} elseif (!isset($knownTypes[$periodType])) {

    $periodType = 'teaching';

}



// Lesson-capable periods occupy a normal row; everything else reads as a break.

$isBreak = in_array($periodType, timetableLessonCapableTypes(), true) ? 0 : 1;



if ($periodName === '' || $startTime === '' || $endTime === '' || $className === '') {

    echo json_encode(['success' => false, 'message' => 'Class, period name, start time, and end time are required.']);

    exit;

}



if ($startTime >= $endTime) {

    echo json_encode(['success' => false, 'message' => 'End time must be after start time.']);

    exit;

}



// Overlap check scoped to the same class

$overlapStmt = $conn->prepare(

    "SELECT id, period_name FROM timetable_periods

     WHERE class_name = ? AND id != ? AND start_time < ? AND end_time > ?

     LIMIT 1"

);

$overlapStmt->bind_param('siss', $className, $id, $endTime, $startTime);

$overlapStmt->execute();

$overlap = $overlapStmt->get_result()->fetch_assoc();

$overlapStmt->close();



if ($overlap) {

    echo json_encode(['success' => false, 'message' => 'Time overlaps with ' . $overlap['period_name'] . '.']);

    exit;

}



if ($id > 0) {

    $stmt = $conn->prepare(

        "UPDATE timetable_periods

         SET period_name = ?, start_time = ?, end_time = ?, is_break = ?, order_no = ?, period_type = ?, class_name = ?

         WHERE id = ?"

    );

    $stmt->bind_param('sssiissi', $periodName, $startTime, $endTime, $isBreak, $orderNo, $periodType, $className, $id);

    $stmt->execute();

    $stmt->close();

} else {

    $stmt = $conn->prepare(

        "INSERT INTO timetable_periods (period_name, start_time, end_time, is_break, order_no, period_type, class_name)

         VALUES (?, ?, ?, ?, ?, ?, ?)"

    );

    $stmt->bind_param('sssiiss', $periodName, $startTime, $endTime, $isBreak, $orderNo, $periodType, $className);

    $stmt->execute();

    $id = (int) $stmt->insert_id;

    $stmt->close();

}



$fetchStmt = $conn->prepare("SELECT * FROM timetable_periods WHERE id = ? LIMIT 1");

$fetchStmt->bind_param('i', $id);

$fetchStmt->execute();

$period = $fetchStmt->get_result()->fetch_assoc();

$fetchStmt->close();



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



