<?php
// إخفاء الأخطاء لضمان استجابة JSON نظيفة
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

session_start();
require_once 'db_connect.php';

if (!$conn) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// جلب اسم المدرسة من الجلسة (اختياري، للفلترة إذا كنت تستخدم نفس القاعدة لعدة مدارس)
$current_school = isset($_SESSION['school_name']) ? $conn->real_escape_string($_SESSION['school_name']) : '';

// 1. جلب فلاتر الواجهة
$stage_filter = isset($_POST['stage']) ? $conn->real_escape_string($_POST['stage']) : '';
$dept_filter  = isset($_POST['dept'])  ? $conn->real_escape_string($_POST['dept'])  : '';
$branch_filter= isset($_POST['branch'])? $conn->real_escape_string($_POST['branch']): '';

// 2. بناء الاستعلام الأساسي (ربط جدول الطلاب مع جدول الحسابات)
$query = "
    SELECT 
        s.student_id as id, 
        s.student_name as name, 
        COALESCE(s.stage, 'عام') as stage, 
        COALESCE(s.department, 'عام') as dept, 
        COALESCE(s.branch, 'عام') as section,
        s.enrollment_status,
        s.is_suspended as is_blocked,
        COALESCE(f.financial_id, 0) as financial_id,
        COALESCE(f.net_total, 0) as total,
        COALESCE(f.discount_percentage, 0) as discount,
        COALESCE(f.total_paid, 0) as paid
    FROM students s
    LEFT JOIN acc_student_financials f ON s.student_id = f.student_id
    WHERE s.school_name = '$current_school'
";

// إضافة الفلاتر إذا وجدت
if (!empty($current_school) && $current_school !== 'مستقل') {
    $query .= " AND s.school_name = '$current_school'";
}
if (!empty($stage_filter))  $query .= " AND s.stage = '$stage_filter'";
if (!empty($dept_filter))   $query .= " AND s.department = '$dept_filter'";
if (!empty($branch_filter)) $query .= " AND s.branch = '$branch_filter'";

$query .= " ORDER BY s.student_name ASC";

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

// 3. ترتيب البيانات وجلب الأقساط الفرعية
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $student = [
            'id' => $row['id'],
            'name' => $row['name'],
            'stage' => $row['stage'],
            'dept' => $row['dept'],
            'section' => $row['section'],
            'enrollment_status' => $row['enrollment_status'], /* 🚀 تم إضافة هذا السطر الهام جداً 🚀 */
            'is_blocked' => $row['is_blocked'],
            'total' => floatval($row['total']),
            'discount' => floatval($row['discount']),
            'paid' => floatval($row['paid']),
            'installments' => []
        ];

        // إذا كان لديه حساب مالي، نجلب تواريخ أقساطه من جدول acc_installments
        if ($row['financial_id'] > 0) {
            $fin_id = $row['financial_id'];
            $inst_q = $conn->query("SELECT due_date, amount_due, is_paid FROM acc_installments WHERE financial_id = $fin_id ORDER BY due_date ASC");
            
            if ($inst_q && $inst_q->num_rows > 0) {
                while ($i = $inst_q->fetch_assoc()) {
                    $student['installments'][] = [
                        'date' => $i['due_date'],
                        'amount' => floatval($i['amount_due']),
                        'stat' => $i['is_paid'] == 1 ? 'مدفوع' : 'غير مدفوع'
                    ];
                }
            }
        }
        
        $students_data[] = $student;
    }
}

// 4. إرسال البيانات كـ JSON نظيف للجافاسكريبت
echo json_encode([
    'status' => 'success',
    'data' => $students_data
], JSON_UNESCAPED_UNICODE);

exit;
?>
