<?php
session_start();
require_once __DIR__ . '/../layouts/dbconn.php';
require_once __DIR__ . '/../layouts/session.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

$allowed = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'FRONT_OFFICE', 'NURSE'];
if (!in_array($_SESSION['role_code'], $allowed)) {
    echo json_encode(['success' => false, 'message' => 'Not allowed']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid method']);
    exit;
}

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

$admin_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $admin_roles)) {
    $row = $conn->query("SELECT doctor_id FROM doctor_rota WHERE rota_id = " . $rota_id)->fetch_assoc();
    if ($row) {
        $self = $conn->query("SELECT doctor_id FROM doctors WHERE user_id = " . (int)$_SESSION['user_id']);
        if ($self && $s = $self->fetch_assoc() && (int)$s['doctor_id'] !== (int)$row['doctor_id']) {
            echo json_encode(['success' => false, 'message' => 'You can only delete your own rota slots']);
            exit;
        }
    }
}

$stmt = $conn->prepare("DELETE FROM doctor_rota WHERE rota_id = ?");
$stmt->bind_param('i', $rota_id);
$stmt->execute();
if ($stmt->affected_rows > 0) {
    echo json_encode(['success' => true, 'message' => 'Slot removed']);
} else {
    echo json_encode(['success' => false, 'message' => 'Slot not found']);
}
