<?php
// live_v2/fetch_media.php
header('Content-Type: application/json; charset=utf-8');
error_reporting(0);

require_once '../db_connect.php';

// بدء الجلسة لمعرفة معرف المدرس الحالي
session_start();
$current_teacher_id = isset($_SESSION['teacher_id']) ? intval($_SESSION['teacher_id']) : 0;

$subject = isset($_GET['subject']) ? trim($_GET['subject']) : '';

if (empty($subject)) {
    echo json_encode([]);
    exit;
}

try {
    // 🚀 المعادلة الذكية: جلب الـ 3D للجميع، وجلب بقية الوسائط لصاحب الحساب فقط 🚀
    $query = "SELECT id, title, media_type AS type, source_url AS url 
              FROM academy_media_library 
              WHERE subject = ? 
              AND (media_type = '3D' OR teacher_id = ?) 
              ORDER BY id DESC";
              
    $stmt = $conn->prepare($query);
    $stmt->bind_param("si", $subject, $current_teacher_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    
    echo json_encode($data);
} catch (Exception $e) {
    echo json_encode(["error" => "خطأ في السيرفر"]);
}
?>