<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// Database configuration
require_once('db.php');

// Get parameters from the request
$user_id = $_GET['user_id'] ?? null;
$role = $_GET['role'] ?? null;

if (!$user_id || !$role) {
    echo json_encode([
        'status' => 'error',
        'message' => 'User ID and role are required'
    ]);
    exit;
}

try {
    // Create database connection
    $conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($role === 'teacher') {
        // For teachers, show only their own videos
        $stmt = $conn->prepare("SELECT video_id, video_url, subject, summary, lesson_name 
                              FROM tbl_videos 
                              WHERE user_id = ?");
        $stmt->execute([$user_id]);
    } else if ($role === 'student') {
        // For students, show videos from teachers in their school
        $stmt = $conn->prepare("SELECT v.video_id, v.video_url, v.subject, v.summary, v.lesson_name 
                              FROM tbl_videos v
                              INNER JOIN tbl_adhd_users teacher ON v.user_id = teacher.user_id
                              INNER JOIN tbl_adhd_users student ON student.school_id = teacher.school_id
                              WHERE student.user_id = ?
                              ORDER BY v.video_id DESC");
        $stmt->execute([$user_id]);
    } else {
        throw new Exception('Invalid role specified');
    }
    
    $videos = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($videos) {
        // Return the videos as JSON
        echo json_encode([
            'status' => 'success',
            'data' => $videos
        ]);
    } else {
        // No videos found
        echo json_encode([
            'status' => 'success',
            'data' => []
        ]);
    }

} catch(PDOException $e) {
    // Handle database errors
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
} catch(Exception $e) {
    // Handle other errors
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Server error: ' . $e->getMessage()
    ]);
}

// Close the connection
$conn = null;
$stmt = null;
?> 