<?php
// api/delete_schedule.php
// This API endpoint handles deleting a class schedule entry.

// --- START TEMPORARY DEBUGGING ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// --- END TEMPORARY DEBUGGING ---

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

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

// Ensure user is logged in and is either an admin or instructor
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
    error_log("DELETE_SCHEDULE_API: Unauthorized access attempt. Session: " . print_r($_SESSION, true)); // DEBUG
    echo json_encode(['success' => false, 'message' => 'Authentication required or not authorized.']);
    exit();
}

require_once '../config/database.php'; // Path to database connection

$input = json_decode(file_get_contents('php://input'), true);
$schedule_id = filter_var($input['id'] ?? null, FILTER_VALIDATE_INT);

$response = ['success' => false, 'message' => ''];

$current_user_id = $_SESSION['user_id'];
$current_user_role = $_SESSION['user_role'];

error_log("DELETE_SCHEDULE_API: Request received. Schedule ID: " . $schedule_id . ", User Role: " . $current_user_role . ", User ID: " . $current_user_id); // DEBUG

// --- 1. Basic Input Validation ---
if (!$schedule_id) {
    $response['message'] = "Missing schedule ID.";
    error_log("DELETE_SCHEDULE_API: Missing schedule ID."); // DEBUG
    echo json_encode($response);
    exit();
}

try {
    // --- 2. Authorization Check: Ensure instructor can only delete schedules for their own courses ---
    // First, get the course_id associated with this schedule_id and its instructor_id
    $stmt_check = $pdo->prepare("
        SELECT cs.id, c.instructor_id
        FROM course_schedules cs
        JOIN courses c ON cs.course_id = c.id
        WHERE cs.id = ? LIMIT 1
    ");
    $stmt_check->execute([$schedule_id]);
    $schedule_info = $stmt_check->fetch(PDO::FETCH_ASSOC);

    if (!$schedule_info) {
        $response['message'] = "Schedule entry not found.";
        error_log("DELETE_SCHEDULE_API: Schedule ID " . $schedule_id . " not found in DB."); // DEBUG
        echo json_encode($response);
        exit();
    }

    if ($current_user_role === 'instructor' && $schedule_info['instructor_id'] != $current_user_id) {
        $response['message'] = "You are not authorized to delete this schedule.";
        error_log("DELETE_SCHEDULE_API: Authorization failed. User " . $current_user_id . " (role: " . $current_user_role . ") tried to delete schedule belonging to instructor " . $schedule_info['instructor_id'] . "."); // DEBUG
        echo json_encode($response);
        exit();
    }

    // --- 3. Delete the schedule entry ---
    $stmt = $pdo->prepare("DELETE FROM course_schedules WHERE id = ?");

    if ($stmt->execute([$schedule_id])) {
        $response['success'] = true;
        $response['message'] = "Class schedule deleted successfully!";
        error_log("DELETE_SCHEDULE_API: Schedule ID " . $schedule_id . " deleted successfully."); // DEBUG
    } else {
        $error_info = $stmt->errorInfo();
        $response['message'] = "Failed to delete class schedule. DB Error: " . ($error_info[2] ?? 'Unknown error');
        error_log("DELETE_SCHEDULE_API: DB Deletion Error for ID " . $schedule_id . ": " . print_r($error_info, true)); // DEBUG
    }

} catch (PDOException $e) {
    $response['message'] = "Database error: " . $e->getMessage();
    error_log("DELETE_SCHEDULE_API PDOException: " . $e->getMessage()); // DEBUG
} catch (Exception $e) {
    $response['message'] = "Server error: " . $e->getMessage();
    error_log("DELETE_SCHEDULE_API Exception: " . $e->getMessage()); // DEBUG
}

echo json_encode($response);
exit();
