<?php
if (session_status() == PHP_SESSION_NONE) { session_start(); }
header('Content-Type: application/json; charset=utf-8');
require_once 'db_connect.php';

// 1. استقبال اسم المدرس بذكاء مع فك تشفير اللغة العربية (urldecode)
$teacher_name = isset($_GET['teacher']) ? urldecode($_GET['teacher']) : '';

if (empty($teacher_name) || $teacher_name == 'مجهول') {
    $teacher_name = $_SESSION['teacher_name'] ?? $_SESSION['admin_user'] ?? 'admin_ammar';
}

$teacher_name = $conn->real_escape_string($teacher_name);

// 🚀 استخراج المعرف الرقمي الطويل (مثال: 1778675284) لضمان دقة البحث الفولاذي والعزل التام
preg_match('/\d{8,}/', $teacher_name, $matches);
$tid_only = !empty($matches[0]) ? $matches[0] : '';

// 🚀 2. جلب مدرسة المدرس (المؤسسة) لضمان العزل المؤسساتي باستخدام المعرف الرقمي أو الاسم
if (!empty($tid_only)) {
    $school_q = $conn->query("SELECT school_name FROM teachers WHERE teacher_name LIKE '%$tid_only%' LIMIT 1");
} else {
    $school_q = $conn->query("SELECT school_name FROM teachers WHERE teacher_name = '$teacher_name' LIMIT 1");
}
$school_data = $school_q->fetch_assoc();
$my_school = $school_data['school_name'] ?? '';

// 🚀 3. جلب كل التفاصيل مع شرط تصفية رقم المدرس المرن (LIKE) لمنع تداخل البيانات أو اختفاء الدروس
if (!empty($tid_only)) {
    $sql = "SELECT id, title, class_name as stage, department as dept, branch, date_added as date, lesson_content as content, pdf_file, video_file, video_url 
            FROM archived_lessons 
            WHERE teacher_name LIKE ? 
            AND school_name = ?
            ORDER BY date_added DESC";
            
    $stmt = $conn->prepare($sql);
    $search_term = "%" . $tid_only . "%";
    $stmt->bind_param("ss", $search_term, $my_school);
} else {
    // خط دفاع احتياطي للحسابات الإدارية مثل admin_ammar
    $sql = "SELECT id, title, class_name as stage, department as dept, branch, date_added as date, lesson_content as content, pdf_file, video_file, video_url 
            FROM archived_lessons 
            WHERE teacher_name = ? 
            AND school_name = ?
            ORDER BY date_added DESC";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $teacher_name, $my_school);
}

$stmt->execute();
$result = $stmt->get_result();

$archive = [];
while($row = $result->fetch_assoc()) {
    $archive[] = [
        'id' => $row['id'],
        'title' => $row['title'] ?? 'بدون عنوان',
        'stage' => (!empty($row['stage']) && $row['stage'] !== 'null') ? $row['stage'] : 'عام',
        'dept' => (!empty($row['dept']) && $row['dept'] !== 'null') ? $row['dept'] : 'عام',
        'branch' => (!empty($row['branch']) && $row['branch'] !== 'null') ? $row['branch'] : 'الكل',
        'date' => date("Y-m-d", strtotime($row['date'])),
        'content' => $row['content'] ?? '',
        'pdf_file' => $row['pdf_file'] ?? '',
        'video_file' => $row['video_file'] ?? '',
        'video_url' => $row['video_url'] ?? '#'
    ];
}

// 4. إرسال النتيجة للجافاسكريبت مع دعم اللغة العربية (JSON_UNESCAPED_UNICODE)
echo json_encode(['status' => 'success', 'data' => $archive], JSON_UNESCAPED_UNICODE);

$stmt->close();
$conn->close();
?>