<?php
session_start(); // 🚀 ضروري لجلب اسم المدرسة للمدير الحالي
require_once 'db_connect.php';

// 🚀 جلب اسم المدرسة לעزل الطلاب 🚀
$school_name = isset($_SESSION['school_name']) ? $conn->real_escape_string($_SESSION['school_name']) : '';

$search = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$stage = isset($_GET['stage']) ? $conn->real_escape_string($_GET['stage']) : '';
$class = isset($_GET['class']) ? $conn->real_escape_string($_GET['class']) : '';
$section = isset($_GET['section']) ? $conn->real_escape_string($_GET['section']) : '';

// 🚀 إضافة شرط (school_name) لكي لا تظهر بيانات المدارس الأخرى 🚀
$query = "SELECT student_id, student_name, stage, department, branch FROM students WHERE school_name = '$school_name'";

if (!empty($search)) $query .= " AND student_name LIKE '%$search%'";
if (!empty($stage)) $query .= " AND stage = '$stage'";
if (!empty($class)) $query .= " AND department = '$class'";
if (!empty($section)) $query .= " AND branch = '$section'";

$query .= " ORDER BY student_id DESC LIMIT 50";
$res = $conn->query($query);

if ($res && $res->num_rows > 0) {
    while ($row = $res->fetch_assoc()) {
        $st_id = $conn->real_escape_string($row['student_id']);
        $st_name = htmlspecialchars($row['student_name']);
        $st_details = htmlspecialchars($row['stage'] . ' - ' . $row['department'] . ' - شعبة ' . $row['branch']);
        
        echo "<tr style='border-bottom: 1px solid rgba(255,255,255,0.05);'>
                <td style='padding:12px; font-weight:bold;'>$st_name</td>
                <td style='padding:12px; color:#94a3b8; font-size:13px;'>$st_details</td>
                <td style='padding:12px;'>
                    <button class='btn-action' style='background:#8b5cf6; padding:6px 12px; border-radius:6px;' 
                            onclick=\"openParentInfo('$st_id', '$st_name')\">
                        <i class='fas fa-user-tie'></i> ولي الأمر
                    </button>
                </td>
              </tr>";
    }
} else {
    echo "<tr><td colspan='3' style='padding:20px; text-align:center; color:#f87171;'>لا يوجد طلاب يطابقون خيارات البحث.</td></tr>";
}
?>