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

$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid period selected.']);
    exit;
}

$checkStmt = $conn->prepare("SELECT COUNT(*) AS total FROM timetable_slots WHERE period_id = ?");
$checkStmt->bind_param('i', $id);
$checkStmt->execute();
$usage = $checkStmt->get_result()->fetch_assoc();
$checkStmt->close();

if ((int) ($usage['total'] ?? 0) > 0) {
    echo json_encode(['success' => false, 'message' => 'Period is in use. Remove slots first.']);
    exit;
}

$stmt = $conn->prepare("DELETE FROM timetable_periods WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();

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

