<?php
// إغلاق الجلسة لتسريع الأداء
if (session_status() === PHP_SESSION_ACTIVE) { 
    session_write_close(); 
}

header('Content-Type: application/json; charset=utf-8');

// 🌟 السر هنا: منع MySQL من إيقاف السيرفر (رمي استثناء) في حال خطأ أسماء الجداول 🌟
mysqli_report(MYSQLI_REPORT_OFF);
error_reporting(0);
ini_set('display_errors', 0);

$host = "127.0.0.1"; 
$db_name = "sql_roozmari_com";
$username = "sql_roozmari_com";
$password = "1fd588adb22d";

$response = [
    "stages" => [],
    "depts" => [],
    "sections" => [],
    "debug_status" => "success" // حقل تشخيصي لمعرفة حالة السيرفر
];

$conn = @new mysqli($host, $username, $password, $db_name);

if (!$conn->connect_error) {
    $conn->set_charset("utf8mb4");

    // استعلام المراحل
    $resStages = $conn->query("SELECT name FROM stages");
    if ($resStages) { 
        while($row = $resStages->fetch_assoc()) { $response['stages'][] = $row['name']; } 
    } else {
        $response['debug_status'] = "Error in stages table: " . $conn->error;
    }

    // استعلام الأقسام
    $resDepts = $conn->query("SELECT name FROM departments");
    if ($resDepts) { 
        while($row = $resDepts->fetch_assoc()) { $response['depts'][] = $row['name']; } 
    } else {
        $response['debug_status'] = "Error in departments table: " . $conn->error;
    }

    // استعلام الشعب
    $resSections = $conn->query("SELECT name FROM sections");
    if ($resSections) { 
        while($row = $resSections->fetch_assoc()) { $response['sections'][] = $row['name']; } 
    } else {
        $response['debug_status'] = "Error in sections table: " . $conn->error;
    }

    $conn->close();
} else {
    $response['debug_status'] = "Database Connection Failed";
}

echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>