<?php
// api/upload_video_link.php
// This API endpoint handles updating the video_link for a specific class schedule.

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

$schedule_id = filter_var($input['id'] ?? null, FILTER_VALIDATE_INT);
$video_link = filter_var($input['video_link'] ?? '', FILTER_VALIDATE_URL); // Can be empty if clearing link

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

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

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

// Allow video_link to be empty (if they want to clear it) but if provided, it must be a URL
if (!empty($input['video_link']) && $video_link === false) { // input['video_link'] is raw, video_link is filtered
    $response['message'] = "Invalid video link format. Please provide a valid URL.";
    echo json_encode($response);
    exit();
}


try {
    // --- 2. Authorization Check: Ensure instructor can only update schedules for their own courses ---
    $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.";
        echo json_encode($response);
        exit();
    }

    if ($current_user_role === 'instructor' && $schedule_info['instructor_id'] != $current_user_id) {
        $response['message'] = "You are not authorized to update this schedule.";
        echo json_encode($response);
        exit();
    }

    // --- 3. Update the video_link ---
    $stmt = $pdo->prepare("UPDATE course_schedules SET video_link = ? WHERE id = ?");

    if ($stmt->execute([$video_link, $schedule_id])) {
        $response['success'] = true;
        $response['message'] = "Video link updated successfully!";
    } else {
        $response['message'] = "Failed to update video link. Please try again.";
        error_log("Upload Video Link Error: " . print_r($stmt->errorInfo(), true));
    }

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

echo json_encode($response);
exit();
