<?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;
$grade = $_GET['grade'] ?? null;

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

if ($role === 'Teacher') {
    // For teachers, show only their own videos
    $stmt = $conn->prepare("SELECT v.video_id, vt.video_url, vt.summary, vt.transcript
    FROM tbl_videos v
    INNER JOIN video_transcriptions vt ON v.video_id = vt.video_id
    WHERE v.user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
} else if ($role === 'Student') {
    // For students, show videos from teachers in their school
    $stmt = $conn->prepare("SELECT v.video_id, v.grade, vt.video_url, vt.summary, vt.transcript
    FROM tbl_videos v
    JOIN video_transcriptions vt ON v.grade = vt.grade
    WHERE v.grade = ?
    ORDER BY v.video_id DESC");
    $stmt->bind_param("i", $grade);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    throw new Exception('Invalid role specified');
}

// Fetch all results
$videos = [];
while ($row = $result->fetch_assoc()) {
    $videos[] = $row;
}

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

// Close the connection
$stmt->close();
$conn->close();
?>