<?php
// إجبار السيرفر على إظهار الأخطاء إن وجدت لضمان المتابعة الدقيقة
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

require_once 'db_connect.php';

// التحقق من سلامة الاتصال
if (!isset($conn)) {
    echo '<tr><td colspan="7" style="color:#e74c3c; text-align:center; padding:20px; font-weight:bold;">خطأ: ملف الاتصال بقاعدة البيانات به مشكلة.</td></tr>';
    exit;
}

// ==========================================
// 🚀 1. رادار الديون (قوي جداً ومستقل عن أخطاء الكتابة) 🚀
// ==========================================
$defaulters = [];

// أ. جلب الطلاب الذين لديهم أقساط تجاوزت تاريخ الاستحقاق ولم تُدفع
$q1 = $conn->query("SELECT f.student_id FROM acc_installments i JOIN acc_student_financials f ON i.financial_id = f.financial_id WHERE i.is_paid = 0 AND i.due_date < CURDATE()");
if($q1) { 
    while($r = $q1->fetch_assoc()) { 
        $defaulters[] = strtoupper(str_replace([' ', '-', '_'], '', $r['student_id'])); 
    } 
}

// ب. جلب الطلاب الذين مطلوب منهم مبلغ ولم يدفعوا أي شيء (الواصل = 0)
$q2 = $conn->query("SELECT student_id FROM acc_student_financials WHERE net_total > 0 AND total_paid = 0");
if($q2) { 
    while($r = $q2->fetch_assoc()) { 
        $defaulters[] = strtoupper(str_replace([' ', '-', '_'], '', $r['student_id'])); 
    } 
}
$defaulters = array_unique($defaulters);
// ==========================================


// جلب اسم المدرسة من الجلسة
$current_school = isset($_SESSION['school_name']) ? $_SESSION['school_name'] : 'أكاديمية روزماري';
$school_name = mysqli_real_escape_string($conn, $current_school);

// ==========================================
// 🚀 2. قاموس المدرسين (يعمل بنجاح تام) 🚀
// ==========================================
$teachers_map = [];
$t_query = mysqli_query($conn, "SELECT * FROM teachers WHERE school_name = '$school_name'");
if ($t_query) {
    while ($t = mysqli_fetch_assoc($t_query)) {
        $arabic_name = !empty($t['display_name']) ? trim($t['display_name']) : (!empty($t['full_name']) ? trim($t['full_name']) : '');
        
        if (!empty($arabic_name)) {
            if(!empty($t['teacher_name'])) $teachers_map[strtoupper(str_replace([' ', '-', '_'], '', $t['teacher_name']))] = $arabic_name;
            if(!empty($t['username'])) $teachers_map[strtoupper(str_replace([' ', '-', '_'], '', $t['username']))] = $arabic_name;
            if(!empty($t['teacher_id'])) $teachers_map[strtoupper(str_replace([' ', '-', '_'], '', $t['teacher_id']))] = $arabic_name;
        }
    }
}
// ==========================================

// جلب لوجو المدرسة الحالي من قاعدة البيانات
$school_logo = 'images/icon.png'; 
$logo_query = mysqli_query($conn, "SELECT school_logo FROM schools WHERE school_name = '$school_name' LIMIT 1");
if ($logo_query && mysqli_num_rows($logo_query) > 0) {
    $row = mysqli_fetch_assoc($logo_query);
    if (!empty($row['school_logo'])) { $school_logo = htmlspecialchars($row['school_logo']); }
}

// تحديد التبويب الحالي المرسل من الواجهة لفرز طريقة عرض الجدول
$current_tab = isset($_POST['tab']) ? $_POST['tab'] : 'tab-general';

// بناء استعلام البحث الأساسي لطلاب هذه المؤسسة فقط
$sql = "SELECT * FROM students WHERE school_name = '$school_name'";

if (!empty($_POST['stage'])) {
    $stage = mysqli_real_escape_string($conn, $_POST['stage']);
    $sql .= " AND stage = '$stage'";
}
if (!empty($_POST['dept'])) {
    $dept = mysqli_real_escape_string($conn, $_POST['dept']);
    $sql .= " AND department = '$dept'";
}
if (!empty($_POST['branch'])) {
    $branch = mysqli_real_escape_string($conn, $_POST['branch']);
    $sql .= " AND branch = '$branch'";
}

$sort_order = isset($_POST['sort']) ? $_POST['sort'] : 'ASC'; 
if ($sort_order === 'ASC') {
    $sql .= " ORDER BY student_name ASC"; 
} else {
    $sql .= " ORDER BY student_id DESC"; 
}

$result = mysqli_query($conn, $sql);

if (!$result) {
    echo '<tr><td colspan="7" style="color:#e74c3c; text-align:center; padding:20px; font-weight:bold;">خطأ في قاعدة البيانات: ' . mysqli_error($conn) . '</td></tr>';
    exit;
}

// ستايل النبض للمثلث
echo '<style>@keyframes alert-pulse { 0% { transform: scale(1); } 50% { transform: scale(1.2); filter: drop-shadow(0 0 5px rgba(239,68,68,0.8)); } 100% { transform: scale(1); } }</style>';

if (mysqli_num_rows($result) > 0) {
    while ($std = mysqli_fetch_assoc($result)) {
        
        $db_id = isset($std['id']) ? htmlspecialchars($std['id']) : (isset($std['student_id']) ? htmlspecialchars($std['student_id']) : '');
        $student_id = isset($std['student_id']) ? htmlspecialchars($std['student_id']) : '';
        $raw_name = !empty($std['student_name']) ? htmlspecialchars($std['student_name']) : '<span style="color:#e74c3c;">بدون اسم!</span>';
        
        // =========================================================
        // 🚀 الفحص الذكي للديون وإضافة المثلث 🚀
        // =========================================================
        $clean_current_id = strtoupper(str_replace([' ', '-', '_'], '', $student_id));
        
        $financial_alert_html = '';
        if (in_array($clean_current_id, $defaulters)) {
            $financial_alert_html = '<i class="fas fa-exclamation-triangle" style="color:#ef4444; margin-left:8px; font-size:16px; animation: alert-pulse 1.5s infinite;" title="تنبيه: الطالب لديه متعلقات مالية متأخرة الدفع ⚠️"></i> ';
        }
        $display_name = $financial_alert_html . $raw_name;
        // =========================================================

        $phone = !empty($std['phone']) ? htmlspecialchars($std['phone']) : '';
        $email = !empty($std['email']) ? htmlspecialchars($std['email']) : '';
        $parent_phone = !empty($std['parent_phone']) ? htmlspecialchars($std['parent_phone']) : '';
        $address = !empty($std['address']) ? htmlspecialchars($std['address']) : '';
        $id_document = !empty($std['id_document']) ? htmlspecialchars($std['id_document']) : '';
        
        $stage_val = isset($std['stage']) ? htmlspecialchars($std['stage']) : '';
        $dept_val = isset($std['department']) ? htmlspecialchars($std['department']) : '';
        $branch_val = isset($std['branch']) ? htmlspecialchars($std['branch']) : '';
        $full_academic = $stage_val . ' - ' . $dept_val . ' (' . $branch_val . ')';
        
        // =========================================================
        // 🚀 ترجمة معرف المدرس لاسم عربي 🚀
        // =========================================================
        $teacher_db_val = trim(isset($std['teacher_name']) ? $std['teacher_name'] : '');
        if (!empty($teacher_db_val) && $teacher_db_val !== 'NULL' && $teacher_db_val !== 'بانتظار التخصيص') {
            $lookup_key = strtoupper(str_replace([' ', '-', '_'], '', $teacher_db_val));
            $teacher = isset($teachers_map[$lookup_key]) ? htmlspecialchars($teachers_map[$lookup_key]) : htmlspecialchars($teacher_db_val);
        } else {
            $teacher = 'بانتظار التخصيص';
        }
        // =========================================================

        $unexcused_count = 0;
        $excused_count = 0;
        $absence_history = [];

        $safe_std_id = mysqli_real_escape_string($conn, $student_id);
        $att_query = mysqli_query($conn, "SELECT attendance_date, status FROM attendance WHERE student_id = '$safe_std_id' AND status IN ('absent', 'excused') ORDER BY attendance_date DESC");

        if ($att_query) {
            while ($att_row = mysqli_fetch_assoc($att_query)) {
                if ($att_row['status'] === 'excused') {
                    $excused_count++;
                    $excuse_title = 'عذر رسمي';
                } else {
                    $unexcused_count++;
                    $excuse_title = 'بدون عذر';
                }
                $absence_history[] = [
                    'date' => $att_row['attendance_date'],
                    'status' => $att_row['status'],
                    'excuse' => $excuse_title
                ];
            }
        }
        
        $total_absences = $excused_count + $unexcused_count;
        $history_json = htmlspecialchars(json_encode($absence_history), ENT_QUOTES, 'UTF-8');
        
        $absence_color = $total_absences > 3 ? '#e74c3c' : ($total_absences > 0 ? '#f39c12' : '#2ecc71');

        switch ($current_tab) {
            case 'tab-general':
                echo '<tr style="border-bottom: 1px solid rgba(255,255,255,0.05); transition: 0.3s;">';
                echo '<td style="padding:15px;"><input type="checkbox" class="student-chk" style="width:18px; height:18px; cursor:pointer;" value="' . $student_id . '" data-name="' . $raw_name . '" data-stage="' . $full_academic . '"></td>';
                echo '<td style="padding:15px; font-family: monospace; color:#8b5cf6; font-weight:bold;">' . $student_id . '</td>';
                echo '<td style="padding:15px; font-weight:bold;">' . $display_name . '</td>';
                echo '<td style="padding:15px; color:#94a3b8;">' . $full_academic . '</td>';
                echo '<td style="padding:15px; color:' . $absence_color . '; font-weight:bold;">' . $total_absences . ' أيام</td>';
                echo '<td style="padding:15px; color:#f39c12; font-size: 0.9rem; font-weight:bold;">' . $teacher . '</td>';
                
                $photo_path = (!empty($std['personal_photo']) && $std['personal_photo'] !== 'NULL') ? htmlspecialchars($std['personal_photo']) : '';

                echo '<td style="padding:15px; display:flex; gap:5px; justify-content: center;">
                        <button class="btn-action" style="background:#8b5cf6; padding:6px 10px; border-radius:4px; border:none; color:#fff; cursor:pointer;" title="هوية QR" onclick="generateStudentCard(\'' . $student_id . '\', \'' . addslashes($raw_name) . '\', \'' . addslashes($full_academic) . '\', \'' . addslashes($photo_path) . '\', \'' . addslashes($school_logo) . '\')"><i class="fas fa-qrcode"></i></button>
                        <button class="btn-action" style="background:#3b82f6; padding:6px 10px; border-radius:4px; border:none; color:#fff; cursor:pointer;" title="تعديل بيانات الطالب" onclick="openEditStudentModal(\'' . $db_id . '\', \'' . $student_id . '\', \'' . addslashes($raw_name) . '\', \'' . addslashes($phone) . '\', \'' . addslashes($email) . '\', \'' . addslashes($parent_phone) . '\', \'' . addslashes($address) . '\', \'' . addslashes($stage_val) . '\', \'' . addslashes($dept_val) . '\', \'' . addslashes($branch_val) . '\')"><i class="fas fa-edit"></i></button>
                        <button class="btn-action" style="background:#f59e0b; padding:6px 10px; border-radius:4px; border:none; color:#fff; cursor:pointer;" title="إضافة ملاحظة" onclick="addStudentNote(\'' . $student_id . '\', \'' . addslashes($raw_name) . '\')"><i class="fas fa-sticky-note"></i></button>
                        <button class="btn-action" style="background:#ef4444; padding:6px 10px; border-radius:4px; border:none; color:#fff; cursor:pointer;" title="أرشفة / نقل الطالب" onclick="archiveStudent(\'' . $student_id . '\', \'' . addslashes($raw_name) . '\')"><i class="fas fa-user-minus"></i></button>
                     <!-- 🚀 زر تصفير الأجهزة الجديد باللون السماوي 🚀 -->
                        <button type="button" class="btn-action" style="background:#0ea5e9; padding:6px 10px; border-radius:4px; border:none; color:#fff; cursor:pointer;" title="تصفير أجهزة الطالب لفك الحظر" onclick="resetStudentDevices(\'' . $student_id . '\')"><i class="fas fa-mobile-alt"></i></button>
                      </td>';
                echo '</tr>';
                break;

            case 'tab-attendance':
                echo '<tr style="border-bottom: 1px solid rgba(255,255,255,0.05);">';
                echo '<td style="padding:15px;"><input type="checkbox" class="student-checkbox student-chk" style="width:18px; height:18px; cursor:pointer;" value="' . $student_id . '" data-name="' . $raw_name . '" data-stage="' . $full_academic . '"></td>';  
                echo '<td style="padding:15px; color:#94a3b8;">' . $student_id . '</td>';
                echo '<td style="padding:15px; font-weight:bold;">' . $display_name . '</td>';
                echo '<td style="padding:15px; color:#94a3b8;">' . $full_academic . '</td>';
                echo '<td style="padding:15px; color:#ff4d79; font-weight:bold;">' . $total_absences . ' أيام</td>';
                echo '<td style="padding:15px; color:#3498db;">' . $excused_count . ' أيام</td>';
                echo '<td style="padding:15px; color:#e74c3c;">' . $unexcused_count . ' أيام</td>';
                echo '<td style="padding:15px; text-align:center;"><button class="btn-action" style="padding:6px 12px; font-size:0.8rem; background:rgba(52, 152, 219, 0.15); border:1px solid #3498db; color:#fff;" onclick="openAbsenceModal(\'' . addslashes($raw_name) . '\', \'' . $history_json . '\')"><i class="fas fa-search"></i> التفاصيل</button></td>';
                echo '</tr>';
                break;

            case 'tab-grades':
                $success_rate = isset($std['success_rate']) ? htmlspecialchars($std['success_rate']) : 0;
                $month_grade = isset($std['month_grade']) ? htmlspecialchars($std['month_grade']) : 0;
                echo '<tr style="border-bottom: 1px solid rgba(255,255,255,0.05);">';
                echo '<td style="padding:15px;"><input type="checkbox" class="student-chk" style="width:18px; height:18px; cursor:pointer;" value="' . $student_id . '"></td>';
                echo '<td style="padding:15px; font-family: monospace; color:#94a3b8;">' . $student_id . '</td>';
                echo '<td style="padding:15px; font-weight:bold;">' . $display_name . '</td>';
                echo '<td style="padding:15px; color:#94a3b8;">' . $full_academic . '</td>';
                echo '<td style="padding:15px; color:#f39c12; font-weight:bold;">' . $month_grade . ' %</td>';
                echo '<td style="padding:15px; color:#2ecc71; font-weight:bold;">' . $success_rate . ' %</td>';
                echo '<td style="padding:15px; text-align:center;"><span style="color:var(--text-muted); font-size:0.85rem;">' . htmlspecialchars($std['teacher_note'] ?? 'لا توجد ملاحظات') . '</span></td>';
                echo '</tr>';
                break;

            // ==========================================
            // 🚀 التبويب الجديد: سجل المدرسين (السجلات) 🚀
            // ==========================================
            case 'tab-control':
                echo '<tr style="border-bottom: 1px solid rgba(255,255,255,0.05); transition: 0.3s;" onmouseover="this.style.background=\'rgba(245, 158, 11, 0.05)\'" onmouseout="this.style.background=\'transparent\'">';
                echo '<td style="padding:15px;"><input type="checkbox" class="student-chk" style="width:18px; height:18px; cursor:pointer;" value="' . $student_id . '" data-name="' . $raw_name . '"></td>';
                
                // المعرف
                echo '<td style="padding:15px; font-family: monospace; color:#f59e0b;">' . $student_id . '</td>';
                
                // اسم الطالب (مع المثلث إذا كان مديوناً)
                echo '<td style="padding:15px; font-weight:bold;">' . $display_name . '</td>';
                
                // المرحلة
                echo '<td style="padding:15px; color:#94a3b8;">' . $full_academic . '</td>';
                
                // المدرس المسؤول (بشكل بارز)
                echo '<td style="padding:15px; color:#f59e0b; font-weight:bold;"><i class="fas fa-chalkboard-teacher"></i> ' . $teacher . '</td>';
                
                // عرض الملاحظات الإدارية والسلوكية
                $admin_note = (!empty($std['teacher_note']) && $std['teacher_note'] !== 'NULL') ? htmlspecialchars($std['teacher_note']) : '<span style="color:#64748b; font-style:italic;">لا توجد سجلات او ملاحظات حالياً</span>';
                echo '<td style="padding:15px; text-align:center; max-width: 250px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="'.(!empty($std['teacher_note']) && $std['teacher_note'] !== 'NULL' ? htmlspecialchars($std['teacher_note']) : '').'">' . $admin_note . '</td>';
                
                // زر إضافة ملاحظة للسجل مخصص لهذا التبويب
                echo '<td style="padding:15px; text-align:center;">
                        <button class="btn-action" style="background:#f59e0b; padding:6px 12px; border-radius:4px; border:none; color:#fff; cursor:pointer; font-size:0.85rem;" onclick="addStudentNote(\'' . $student_id . '\', \'' . addslashes($raw_name) . '\')"><i class="fas fa-plus"></i> تحديث السجل</button>
                      </td>';
                echo '</tr>';
                break;

            case 'tab-docs':
                echo '<tr style="border-bottom: 1px solid rgba(255,255,255,0.05);">';
                echo '<td style="padding:15px;"><input type="checkbox" class="student-chk" style="width:18px; height:18px; cursor:pointer;" value="' . $student_id . '"></td>';


            case 'tab-docs':
                echo '<tr style="border-bottom: 1px solid rgba(255,255,255,0.05);">';
                echo '<td style="padding:15px;"><input type="checkbox" class="student-chk" style="width:18px; height:18px; cursor:pointer;" value="' . $student_id . '"></td>';
                echo '<td style="padding:15px; font-family: monospace; color:#8b5cf6;">' . $student_id . '</td>';
                echo '<td style="padding:15px; font-weight:bold;"><a href="javascript:void(0);" style="color:#fff; text-decoration:underline;" onclick="openStudentProfileModal(\'' . $student_id . '\', \'' . addslashes($raw_name) . '\', \'' . addslashes($phone) . '\', \'' . addslashes($email) . '\', \'' . addslashes($parent_phone) . '\', \'' . addslashes($address) . '\')">' . $display_name . '</a></td>';
                
                $p_phone_disp = !empty($parent_phone) ? $parent_phone : '-';
                $address_disp = !empty($address) ? $address : '-';
                echo '<td style="padding:15px; color:#94a3b8;">' . $p_phone_disp . '</td>';
                echo '<td style="padding:15px; color:#94a3b8; font-size:0.9rem;">' . $address_disp . '</td>';
                
                if (!empty($id_document)) {
                    echo '<td style="padding:15px;"><button class="btn-action" style="background:#3498db; padding:4px 10px; font-size:0.8rem;" onclick="viewStudentDocument(\'' . $id_document . '\', \'' . addslashes($raw_name) . '\')"><i class="fas fa-eye"></i> استعراض المرفق</button></td>';
                } else {
                    echo '<td style="padding:15px; color:#64748b; font-style:italic; font-size:0.85rem;"><i class="fas fa-times-circle"></i> غير مرفوع</td>';
                }
                echo '<td style="padding:15px; text-align:center; color:#2ecc71; font-weight:bold;"><i class="fas fa-link"></i> مربوط باللوحة</td>';
                echo '</tr>';
                break;
        }
    }
} else {
    echo '<tr><td colspan="7" style="text-align:center; padding:40px; color:#64748b; font-size:1.1rem;"><i class="fas fa-folder-open" style="font-size:2rem; display:block; margin-bottom:10px; opacity:0.5;"></i> لا توجد بيانات مسجلة في (' . htmlspecialchars($current_school) . ') تطابق الفلترة الحالية.</td></tr>';
}
?>
