<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json; charset=utf-8');

error_reporting(0);
ini_set('display_errors', 0);

require_once 'db_connect.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }

if (!isset($conn)) {
    echo json_encode(['status' => 'error', 'message' => 'تعذر الاتصال بقاعدة البيانات']);
    exit;
}

$site_title = 'واصل نجاحك يا بطل 🚀'; 
$logo_url = '';

$config_sql = "SELECT site_title, logo_path FROM site_config LIMIT 1";
$config_result = $conn->query($config_sql);
if ($config_result && $config_result->num_rows > 0) {
    $config_row = $config_result->fetch_assoc();
    if (!empty($config_row['site_title'])) $site_title = $config_row['site_title'];
    if (!empty($config_row['logo_path'])) $logo_url = '/academy/' . $config_row['logo_path']; 
}

$student_id = $_GET['sid'] ?? $_SESSION['student_id'] ?? '';
$my_teacher = ''; $my_teacher_clean = ''; $flexible_search = '';
$my_school  = ''; $student_stage = ''; $student_dept = ''; $student_branch = '';

if (!empty($student_id)) {
    $st_info_q = $conn->query("SELECT teacher_name, school_name, stage, department, branch FROM students WHERE student_id = '$student_id' LIMIT 1");
    if($st_info_row = $st_info_q->fetch_assoc()) {
        $raw_teacher = trim($st_info_row['teacher_name']);
        
        // تنظيف الاسم
        $clean = str_ireplace('teacher', '', $raw_teacher); 
        $clean = preg_replace('/[0-9]+/', '', $clean); 
        $clean = str_replace('_', ' ', $clean); 
        $clean = preg_replace('/\s+/', ' ', $clean); 
        $clean = trim($clean); 

        $my_teacher = $conn->real_escape_string($raw_teacher);
        $my_teacher_clean = $conn->real_escape_string($clean);
        
        // 🔥 الخدعة السحرية الأقوى: تحويل "عمار مصلح ناجي" إلى "%عمار%مصلح%ناجي%"
        $flex = '%' . str_replace(' ', '%', $clean) . '%';
        $flexible_search = $conn->real_escape_string($flex);
        
        $my_school        = $conn->real_escape_string(trim($st_info_row['school_name']));
        $student_stage    = $conn->real_escape_string(trim($st_info_row['stage']));
        $student_dept     = $conn->real_escape_string(trim($st_info_row['department']));
        $student_branch   = $conn->real_escape_string(trim($st_info_row['branch']));
    }
}

if (empty($my_teacher)) {
    echo json_encode(['status' => 'error', 'message' => 'خطأ: لم يتم تعيين مدرس لهذا الطالب.']);
    exit;
}

// 🚀 الاستعلام مع البحث المطاطي الذي لا يمكن أن يفشل!
$sql = "SELECT s.*, t.logo AS teacher_personal_logo 
        FROM schedules_archive s
        LEFT JOIN teachers t ON t.teacher_name = s.teacher_name
        WHERE (
            s.teacher_name LIKE '$flexible_search' 
            OR TRIM(s.teacher_name) = '$my_teacher_clean' 
            OR '$my_teacher' LIKE CONCAT('%', TRIM(s.teacher_name), '%')
        )
        AND (s.school_name = '$my_school' OR s.school_name = 'المدرسة العامة' OR s.school_name IS NULL OR s.school_name = '')
        AND (TRIM(s.target_stage) = '$student_stage' OR TRIM(s.target_stage) IN ('الكل', 'all', 'عام', ''))
        AND (TRIM(s.target_dept) = '$student_dept' OR TRIM(s.target_dept) IN ('الكل', 'all', 'عام', ''))
        AND (TRIM(s.target_branch) = '$student_branch' OR TRIM(s.target_branch) IN ('الكل', 'all', 'عام', ''))
        ORDER BY s.created_at DESC";

$result = $conn->query($sql);
$schedules = [];

if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $display_teacher = $row['teacher_name'] ?? 'إدارة';
        $display_teacher = str_ireplace('teacher', '', $display_teacher); 
        $display_teacher = preg_replace('/[0-9]+/', '', $display_teacher); 
        $display_teacher = str_replace('_', ' ', $display_teacher); 
        $display_teacher = preg_replace('/\s+/', ' ', $display_teacher); 
        $display_teacher = trim($display_teacher); 
        
        $row['clean_teacher_name'] = "أ. " . $display_teacher;
        $schedules[] = $row;
    }
}

echo json_encode([
    'status' => 'success', 
    'data' => $schedules,
    'config' => [
        'site_title' => $site_title,
        'logo_url' => $logo_url
    ]
]);
$conn->close();
?>