<?php
// api/delete_batch_schedule.php
// API endpoint to delete a schedule entry.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit();
}

require_once '../config/database.php';

$input = json_decode(file_get_contents('php://input'), true);

$id = $input['id'] ?? null;

if (!$id) {
    echo json_encode(['success' => false, 'message' => 'No schedule ID provided.']);
    exit();
}

try {
    // Check if the user has permission to delete this specific schedule entry.
    // Joins with batches to check instructor ownership.
    $stmt_check = $pdo->prepare("
        SELECT b.instructor_id
        FROM batch_schedules bs
        JOIN batches b ON bs.batch_id = b.id
        WHERE bs.id = ?
    ");
    $stmt_check->execute([$id]);
    $schedule_info = $stmt_check->fetch(PDO::FETCH_ASSOC);

    if (!$schedule_info) {
        echo json_encode(['success' => false, 'message' => 'Schedule not found.']);
        exit();
    }

    if ($_SESSION['user_role'] === 'instructor' && $schedule_info['instructor_id'] != $_SESSION['user_id']) {
        echo json_encode(['success' => false, 'message' => 'You do not have permission to delete this schedule.']);
        exit();
    }

    $stmt = $pdo->prepare("DELETE FROM batch_schedules WHERE id = ?");
    $stmt->execute([$id]);

    if ($stmt->rowCount()) {
        echo json_encode(['success' => true, 'message' => 'Schedule deleted successfully!']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Schedule not found or could not be deleted.']);
    }

} catch (PDOException $e) {
    error_log("Delete Batch Schedule Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>