<?php
session_start();
require_once 'db_connect.php';

// إيقاف طباعة التحذيرات البرمجية لكي لا تكسر تصميم الجدول
error_reporting(0);

$school_name = isset($_SESSION['school_name']) ? $conn->real_escape_string($_SESSION['school_name']) : '';

$type = isset($_POST['type']) ? $_POST['type'] : 'all';
$stage = isset($_POST['stage']) ? $conn->real_escape_string($_POST['stage']) : '';
$search = isset($_POST['search']) ? $conn->real_escape_string($_POST['search']) : '';

$html = '';
$results = [];

// 1. جلب الطلاب
if ($type === 'all' || $type === 'student') {
    $q_std = "SELECT student_name as name, CONCAT('طالب: ', stage, ' - ', department) as classification, personal_photo, id_document FROM students WHERE school_name = '$school_name'";
    if (!empty($stage)) $q_std .= " AND stage = '$stage'";
    if (!empty($search)) $q_std .= " AND student_name LIKE '%$search%'";
    
    $res_std = $conn->query($q_std);
    if ($res_std) while ($row = $res_std->fetch_assoc()) { $results[] = $row; }
}

// 2. جلب الكادر
if ($type === 'all' || $type === 'teacher' || $type === 'admin') {
    $q_stf = "SELECT display_name as name, CONCAT('كادر: ', role, ' - ', title) as classification, personal_photo, id_document FROM teachers WHERE (school_name = '$school_name' OR '$school_name' = '')";
    
    if ($type === 'teacher') $q_stf .= " AND role = 'teacher'";
    if ($type === 'admin') $q_stf .= " AND role IN ('admin', 'accountant')";
    if (!empty($search)) $q_stf .= " AND display_name LIKE '%$search%'";
    
    $res_stf = $conn->query($q_stf);
    if ($res_stf) while ($row = $res_stf->fetch_assoc()) { $results[] = $row; }
}

// 3. طباعة الجدول
if (empty($results)) {
    echo '<tr><td colspan="5" style="text-align:center; padding:30px; color:#94a3b8;">لا توجد ملفات مطابقة للبحث.</td></tr>';
} else {
    foreach ($results as $r) {
        
        // الحل الجذري لمشكلة الـ NULL في PHP 8+
        $db_photo = isset($r['personal_photo']) ? (string)$r['personal_photo'] : '';
        $db_doc = isset($r['id_document']) ? (string)$r['id_document'] : '';

        $photo_url = trim(str_replace("'", "", $db_photo));
        $doc_url = trim(str_replace("'", "", $db_doc));

        $photo = (!empty($photo_url) && $photo_url != 'NULL') ? $photo_url : 'images/default_avatar.png';
        $has_doc = (!empty($doc_url) && $doc_url != 'NULL');

        $doc_icon = $has_doc ? '<i class="fas fa-file-pdf" style="color:#10b981; font-size:1.5rem;"></i>' : '<i class="fas fa-times-circle" style="color:#ef4444; font-size:1.5rem;"></i>';

        $html .= '<tr style="border-bottom: 1px solid rgba(255,255,255,0.05);">';
        $html .= '<td style="padding:15px; font-weight:bold;">' . htmlspecialchars($r['name']) . '</td>';
        $html .= '<td style="padding:15px; color:#cbd5e1; font-size:13px;">' . htmlspecialchars($r['classification']) . '</td>';
        
        // عرض الصورة مع fallback في حال كسر الرابط
        $html .= '<td style="padding:15px; text-align:center;"><img src="'.htmlspecialchars($photo).'" style="width:40px; height:40px; border-radius:50%; object-fit:cover; border:2px solid #3b82f6;" onerror="this.src=\'images/default_avatar.png\'"></td>';
        
        $html .= '<td style="padding:15px; text-align:center;">' . $doc_icon . '</td>';
        
        $html .= '<td style="padding:15px; text-align:center; white-space:nowrap;">';
        
        // 🌟 التغيير هنا: استخدام viewDocument بدلاً من printDocument 🌟
        if ($has_doc) {
            $html .= '<button onclick="viewDocument(\''.htmlspecialchars($doc_url).'\', \'doc\')" class="btn-action" style="background:#3b82f6; padding:5px 10px; margin-left:5px; font-size:12px; display:inline-block;"><i class="fas fa-eye"></i> الهوية</button>';
        } else {
            $html .= '<button disabled class="btn-action" style="background:#3b82f6; padding:5px 10px; margin-left:5px; font-size:12px; opacity:0.5; cursor:not-allowed; display:inline-block;"><i class="fas fa-eye"></i> الهوية</button>';
        }
        
        $html .= '<button onclick="viewDocument(\''.htmlspecialchars($photo).'\', \'photo\')" class="btn-action" style="background:#8b5cf6; padding:5px 10px; font-size:12px; display:inline-block;"><i class="fas fa-eye"></i> الصورة</button>';
        
        $html .= '</td>';
        $html .= '</tr>';
    }
    echo $html;
}
?>