<?php
// api/save_schedule.php
// This API endpoint handles the creation of new class schedule entries.

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')) {
    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);

$course_id = filter_var($input['course_id'] ?? null, FILTER_VALIDATE_INT);
$schedule_date = trim($input['schedule_date'] ?? '');
$start_time = trim($input['start_time'] ?? '');
$end_time = trim($input['end_time'] ?? '');
$topic = trim($input['topic'] ?? '');
$zoom_link = filter_var($input['zoom_link'] ?? '', FILTER_VALIDATE_URL);

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

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

// --- 1. Basic Input Validation ---
if (!$course_id || empty($schedule_date) || empty($start_time) || empty($end_time) || !$zoom_link) {
    $response['message'] = "Missing required schedule details: Course, Date, Times, or Zoom Link.";
    echo json_encode($response);
    exit();
}

// Additional validation for date/time formats if needed
if (!strtotime($schedule_date) || !strtotime($start_time) || !strtotime($end_time)) {
    $response['message'] = "Invalid date or time format.";
    echo json_encode($response);
    exit();
}

// Ensure end time is after start time
if (strtotime($start_time) >= strtotime($end_time)) {
    $response['message'] = "End time must be after start time.";
    echo json_encode($response);
    exit();
}

try {
    // --- 2. Authorization Check: Ensure instructor can only add schedules to their own courses ---
    if ($current_user_role === 'instructor') {
        $stmt_course_owner = $pdo->prepare("SELECT id FROM courses WHERE id = ? AND instructor_id = ? LIMIT 1");
        $stmt_course_owner->execute([$course_id, $current_user_id]);
        if (!$stmt_course_owner->fetch()) {
            $response['message'] = "You are not authorized to create schedules for this course.";
            echo json_encode($response);
            exit();
        }
    }

    // --- 3. Insert into `course_schedules` table ---
    $stmt = $pdo->prepare("
        INSERT INTO course_schedules (course_id, schedule_date, start_time, end_time, topic, zoom_link)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    if ($stmt->execute([$course_id, $schedule_date, $start_time, $end_time, $topic, $zoom_link])) {
        $response['success'] = true;
        $response['message'] = "Class schedule added successfully!";
    } else {
        $response['message'] = "Failed to add class schedule. Please try again.";
        error_log("Save Schedule Error: " . print_r($stmt->errorInfo(), true));
    }

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

echo json_encode($response);
exit();
