<?php
session_start();
require_once('../config/db.php');

// --- نظام جلب اللغة ---
$current_lang = $_SESSION['lang'] ?? 'ar';
$lang_file = "../languages/" . $current_lang . ".php";
$translations = file_exists($lang_file) ? include($lang_file) : [];

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user'])) {
    die($translations['error_unauthorized'] ?? 'Unauthorized');
}

// إعدادات ملف الإكسل
$filename = ($translations['export_filename_prefix'] ?? "students_export") . "_" . date("Y-m-d") . ".xls";

header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");

// لضمان ظهور الحروف العربية والتركية بشكل صحيح في Excel
echo "\xEF\xBB\xBF"; 

// استخراج الطلاب
$stmt = $conn->query("SELECT full_name, phone, national_id, address, study_system FROM students ORDER BY created_at DESC");
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// طباعة الجدول
echo "<table border='1'>";
echo "<tr>";
echo "<th style='background-color: #4f46e5; color: white;'>" . ($translations['label_full_name'] ?? 'الاسم الكامل') . "</th>";
echo "<th style='background-color: #4f46e5; color: white;'>" . ($translations['label_phone'] ?? 'رقم الهاتف') . "</th>";
echo "<th style='background-color: #4f46e5; color: white;'>" . ($translations['label_national_id'] ?? 'الرقم الوطني') . "</th>";
echo "<th style='background-color: #4f46e5; color: white;'>" . ($translations['label_branch'] ?? 'الفرع') . "</th>";
echo "<th style='background-color: #4f46e5; color: white;'>" . ($translations['label_study_system'] ?? 'نظام الدراسة') . "</th>";
echo "</tr>";

foreach ($students as $student) {
    echo "<tr>";
    echo "<td>" . htmlspecialchars($student['full_name']) . "</td>";
    echo "<td>" . htmlspecialchars($student['phone']) . "</td>";
    echo "<td>" . htmlspecialchars($student['national_id']) . "</td>";
    echo "<td>" . htmlspecialchars($student['address']) . "</td>";
    echo "<td>" . htmlspecialchars($student['study_system']) . "</td>";
    echo "</tr>";
}

echo "</table>";
exit;
?>