<?php
session_start();
require_once('../config/db.php');

// ✅ التحقق من تسجيل الدخول
if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

// ✅ جلب بيانات الطلاب
$stmt = $conn->query("SELECT * FROM students ORDER BY created_at DESC");
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ✅ تحديد اللغة والاتجاه
$current_lang = $_SESSION['lang'] ?? 'ar';
$dir = ($current_lang == 'ar') ? 'rtl' : 'ltr';

?>

<?php include('../includes/header.php'); ?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
    @keyframes fadeIn { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } }
    .animate-fadeIn { animation: fadeIn 0.3s ease-out; }
    .table-header { background-color: #4f46e5; color: white; }
    .table-body tr { transition: background-color 0.2s ease; }
    .table-body tr:hover { background-color: #eef2ff; }
    .dark .table-body tr:hover { background-color: #374151; }
    .action-group { display: flex; flex-wrap: nowrap; justify-content: center; gap: 0.5rem; }
    .toast-active { display: flex !important; opacity: 1 !important; transform: translateY(0) !important; }
    #detailsContent { max-height: 70vh; overflow-y: auto; }
</style>

<?php include('../includes/navbar.php'); ?>

<div class="min-h-screen bg-gray-100 dark:bg-gray-900 pb-16 font-[Cairo]" dir="<?= $dir ?>">
    <div class="max-w-7xl mx-auto py-10 px-4 sm:px-6 lg:px-8">

        <div class="bg-white dark:bg-gray-800 shadow-xl rounded-xl p-6 mb-8 border-b-4 border-indigo-500/10">
            <div class="flex flex-col md:flex-row md:justify-between md:items-center">
                
                <h2 class="text-3xl font-extrabold text-gray-800 dark:text-gray-100 mb-4 md:mb-0 border-b-4 border-indigo-400/50 pb-2 inline-block">
                    <i class="fas fa-user-graduate text-indigo-500 <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('student_management') ?>
                </h2>
                
                <div class="flex flex-wrap gap-3">
                    <a href="add.php" class="bg-indigo-600 text-white px-5 py-2 rounded-xl hover:bg-indigo-700 transition flex items-center shadow-lg transform hover:scale-[1.02]">
                        <i class="fas fa-user-plus <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('add_new_student') ?>
                    </a>
					<a href="student_schedule.php" class="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-2.5 rounded-xl transition shadow-md flex items-center gap-2">
    <i class="fas fa-calendar-alt"></i>
    <?= $translations['add_schedule_btn'] ?>
</a>
                    <a href="export_excel.php" class="bg-green-600 text-white px-5 py-2 rounded-xl hover:bg-green-700 transition flex items-center shadow-lg transform hover:scale-[1.02]">
                        <i class="fas fa-file-excel <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('export_excel') ?>
                    </a>
					
                </div>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 shadow-xl rounded-xl p-6 mb-8">
            <input type="search" id="searchInput"
                    placeholder="<?= __('search_placeholder_students') ?>"
                    onkeyup="searchTable()"
                    class="border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-xl px-5 py-3 w-full focus:outline-none focus:ring-4 focus:ring-indigo-500/50 transition shadow-inner <?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>">
        </div>

        <div class="overflow-x-auto rounded-xl shadow-2xl">
            <table id="studentsTable" class="min-w-full <?= $dir == 'rtl' ? 'text-right' : 'text-left' ?> bg-white dark:bg-gray-800 border-collapse">
                <thead class="table-header">
                    <tr>
                    <th class="p-4 border-b border-r border-indigo-400"><?= __('id') ?></th>
                        <th class="p-4 border-b border-r border-indigo-400"><?= __('full_name') ?></th>
                        <th class="p-4 border-b border-r border-indigo-400"><?= __('phone_number') ?></th>
                        <th class="p-4 border-b border-r border-indigo-400"><?= __('email') ?></th>
                        <th class="p-4 border-b border-r border-indigo-400"><?= __('study_system') ?></th>
                        <th class="p-4 border-b border-r border-indigo-400 hidden lg:table-cell"><?= __('registration_date') ?></th>
                        <th class="p-4 border-b border-indigo-400 text-center w-[250px] min-w-[250px]"><?= __('actions') ?></th>
                    </tr>
                </thead>
                <tbody class="table-body text-gray-700 dark:text-gray-300">
                    <?php if ($students): ?>
                        <?php foreach ($students as $student): 
                            // --- إضافة منطق الترجمة هنا لضمان ظهورها في المودال ---
                            $student['gender_translated'] = __($student['gender'] ?? 'not_specified');
                            $student['nationality_translated'] = __($student['nationality'] ?? 'not_specified');
                            $student['study_system_translated'] = __($student['study_system'] ?? 'not_specified');
                            $student['address_translated'] = __($student['address'] ?? 'not_specified');
                        ?>
                            <tr class="border-b dark:border-gray-700">
                            <td class="p-4 border-r dark:border-gray-700 font-mono text-indigo-600 dark:text-indigo-400">
    <?= htmlspecialchars($student['id'] ?? 'N/A') ?>
</td>
                                <td class="p-4 border-r dark:border-gray-700 font-semibold"><?= htmlspecialchars($student['full_name']) ?></td>
                                <td class="p-4 border-r dark:border-gray-700"><?= htmlspecialchars($student['phone']) ?></td>
                                <td class="p-4 border-r dark:border-gray-700 text-sm"><?= htmlspecialchars($student['email'] ?? '-') ?></td>
                                <td class="p-4 border-r dark:border-gray-700">
                                    <span class="inline-block px-3 py-1 text-xs font-medium rounded-full
                                        <?= ($student['study_system'] == 'full_time' || $student['study_system'] == 'دوام كامل') ? 'bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-300' : 'bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-300' ?>">
                                        <?= $student['study_system_translated'] ?>
                                    </span>
                                </td>
                                <td class="p-4 border-r dark:border-gray-700 hidden lg:table-cell text-sm text-gray-500 dark:text-gray-400">
                                    <?= date('Y-m-d', strtotime($student['created_at'])) ?>
                                </td>
                                <td class="p-4 text-center">
                                    <div class="action-group">
                                        
                                        <button onclick='showDetails(<?= json_encode($student, JSON_UNESCAPED_UNICODE) ?>)'
                                            class="action-button bg-yellow-500 hover:bg-yellow-600 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150" title="<?= __('details') ?>">
                                            <i class="fas fa-eye w-4 h-4"></i>
                                        </button>
                                        
                                        <a href="edit.php?id=<?= $student['id'] ?>"
                                            class="action-button bg-blue-600 hover:bg-blue-700 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150" title="<?= __('edit') ?>">
                                            <i class="fas fa-edit w-4 h-4"></i>
                                        </a>
                                        
                                        <button onclick="confirmDelete(<?= $student['id'] ?>)"
                                            class="action-button bg-red-600 hover:bg-red-700 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150" title="<?= __('delete') ?>">
                                            <i class="fas fa-trash-alt w-4 h-4"></i>
                                        </button>

                                        <?php
                                        $raw_phone = $student['phone'] ?? '';
                                        if (!empty($raw_phone)) {
                                            $numeric_phone = preg_replace('/\D/', '', $raw_phone); 
                                            $clean_phone = ltrim($numeric_phone, '0'); 
                                            $whatsapp_number = '962' . $clean_phone; 
                                            $general_message = __('whatsapp_general_message');
                                            $encoded_message = urlencode($general_message);
                                            $whatsapp_url = "https://wa.me/{$whatsapp_number}?text={$encoded_message}";
                                            $link_disabled_classes = '';
                                        } else {
                                            $whatsapp_url = '#';
                                            $whatsapp_number = '';
                                            $link_disabled_classes = 'opacity-50 pointer-events-none cursor-not-allowed';
                                        }
                                        ?>

                                        <a href="<?= $whatsapp_url ?>" target="_blank"
                                            class="action-button bg-green-600 hover:bg-green-700 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150 <?= $link_disabled_classes ?>" 
                                            title="WhatsApp (<?= $whatsapp_number ?: __('no_phone') ?>)">
                                            <i class="fab fa-whatsapp w-4 h-4"></i>
                                        </a>
                                        
                                        <button onclick='showCredentials("<?= htmlspecialchars($student['username'] ?? 'N/A') ?>", "123")'
                                            class="action-button bg-purple-600 hover:bg-purple-700 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150" title="<?= __('login_info') ?>">
                                            <i class="fas fa-key w-4 h-4"></i>
                                        </button>
										<a href="view_timetable.php?student_id=<?= $student['id'] ?>" 
   class="action-button bg-indigo-600 hover:bg-indigo-700 p-2 rounded-full text-white shadow-md transform hover:scale-110 transition duration-150" 
   title="<?= $translations['schedule_title'] ?? 'عرض الجدول الدراسي' ?>">
   <i class="fas fa-calendar-alt w-4 h-4 flex items-center justify-center"></i>
</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="text-center p-8 text-xl text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-700">
                                <i class="fas fa-exclamation-circle text-4xl mb-3 text-red-500"></i><br>
                                <?= __('no_students_found') ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="detailsModal" class="hidden fixed inset-0 bg-black bg-opacity-70 flex justify-center items-center z-50 p-2 md:p-4">
    <div class="bg-white dark:bg-gray-800 rounded-2xl md:rounded-3xl shadow-2xl w-full max-w-3xl p-5 md:p-8 relative animate-fadeIn border-t-8 border-blue-600 overflow-hidden">
        <button onclick="closeModal()" class="absolute top-2 <?= $dir == 'rtl' ? 'left-4' : 'right-4' ?> text-gray-400 hover:text-red-500 text-3xl transition z-10">&times;</button>
        <h3 class="text-2xl md:text-3xl font-extrabold text-center mb-6 md:mb-8 text-blue-700 dark:text-blue-400">📋 <?= __('student_file_details') ?></h3>
        
        <div id="detailsContent" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 md:gap-6 text-gray-700 dark:text-gray-300 text-md">
        </div>
        
        <div class="text-center mt-8 md:mt-10">
            <button onclick="closeModal()" class="bg-gray-400 hover:bg-gray-500 text-white px-8 py-3 rounded-xl font-bold transition shadow-lg w-full md:w-auto">
                <i class="fas fa-times <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('close_window') ?>
            </button>
        </div>
    </div>
</div>

<div id="credentialsModal" class="hidden fixed inset-0 bg-black bg-opacity-70 flex justify-center items-center z-50 p-4">
    <div class="bg-white dark:bg-gray-800 rounded-3xl shadow-2xl w-full max-w-lg p-8 relative animate-fadeIn border-t-8 border-purple-600">
        <button onclick="closeCredentialsModal()" class="absolute top-4 <?= $dir == 'rtl' ? 'left-4' : 'right-4' ?> text-gray-400 hover:text-red-500 text-3xl transition">&times;</button>
        <h3 class="text-3xl font-extrabold text-center mb-8 text-purple-700 dark:text-purple-400">🔑 <?= __('login_info') ?></h3>
        
        <div class="text-center text-gray-700 dark:text-gray-300 text-xl space-y-4 bg-gray-50 dark:bg-gray-700 p-6 rounded-xl border border-dashed border-purple-300 dark:border-purple-700">
            <p class="flex justify-between items-center">
                <span><i class="fas fa-user-circle <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?> text-purple-500"></i> <?= __('username') ?>:</span>
                <strong id="credUsername" class="text-2xl font-mono text-gray-900 dark:text-white"></strong>
            </p>
            <p class="flex justify-between items-center">
                <span><i class="fas fa-lock <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?> text-purple-500"></i> <?= __('password') ?>:</span>
                <strong id="credPassword" class="text-2xl font-mono text-gray-900 dark:text-white"></strong>
            </p>
            <p class="text-sm text-red-500 mt-4"><i class="fas fa-exclamation-triangle"></i> <?= __('temporary_password_note') ?></p>
        </div>
        
        <div class="text-center mt-10">
            <button onclick="closeCredentialsModal()" class="bg-gray-400 hover:bg-gray-500 text-white px-8 py-3 rounded-xl font-bold transition shadow-lg">
                <i class="fas fa-times <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('close') ?>
            </button>
        </div>
    </div>
</div>

<div id="toast" class="hidden fixed bottom-6 <?= $dir == 'rtl' ? 'right-6' : 'left-6' ?> bg-green-600 text-white px-6 py-4 rounded-xl shadow-2xl text-lg font-bold transition-all duration-300 transform opacity-0 translate-y-full z-[100] items-center">
    <i id="toastIcon" class="fas fa-check-circle <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?> text-2xl"></i> 
    <span id="toastMessage"></span>
</div>

<script>
    // نمرر الترجمات للجافاسكريبت
    const translations = {
        'id': "<?= __('id') ?>",
        'delete_confirm': "<?= __('delete_confirm_msg') ?>",
        'success_msg': "<?= __('operation_success') ?>",
        'error_msg': "<?= __('operation_error') ?>",
        'full_name': "<?= __('full_name') ?>",
        'phone_number': "<?= __('phone_number') ?>",
        'guardian_phone': "<?= __('guardian_phone') ?>",
        'national_id': "<?= __('national_id') ?>",
        'nationality': "<?= __('nationality') ?>", 
        'email': "<?= __('email') ?>",
        'gender': "<?= __('gender') ?>",
        'birth_date': "<?= __('birth_date') ?>",
        'branch': "<?= __('branch') ?>",
        'address_details': "<?= __('address_details') ?>",
        'study_system': "<?= __('study_system') ?>",
        'marketer_name': "<?= __('marketer_name') ?>",
        'registration_date': "<?= __('registration_date') ?>",
        'no_specified': "<?= __('not_specified') ?>",
    };

    function showNotification(message, isError = false) {
        const toast = document.getElementById('toast');
        const toastMsg = document.getElementById('toastMessage');
        const toastIcon = document.getElementById('toastIcon');
        
        toastMsg.innerText = message;
        if(isError) {
            toast.classList.remove('bg-green-600');
            toast.classList.add('bg-red-600');
            toastIcon.className = "fas fa-exclamation-triangle <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?> text-2xl";
        } else {
            toast.classList.remove('bg-red-600');
            toast.classList.add('bg-green-600');
            toastIcon.className = "fas fa-check-circle <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?> text-2xl";
        }

        toast.classList.remove('hidden');
        setTimeout(() => toast.classList.add('toast-active'), 10);
        setTimeout(() => { location.reload(); }, isError ? 2500 : 1500);
    }

    function searchTable() {
        const input = document.getElementById('searchInput').value.toLowerCase();
        document.querySelectorAll('#studentsTable tbody tr').forEach(row => {
            const rowContent = row.textContent.toLowerCase();
            row.style.display = rowContent.includes(input) ? '' : 'none';
        });
    }

    function showDetails(student) {
        const modal = document.getElementById('detailsModal');
        const content = document.getElementById('detailsContent');

        const fields = [
            { label: translations.id, value: student.id || '-' },
            { label: translations.full_name, value: student.full_name },
            { label: translations.phone_number, value: student.phone },
            { label: translations.guardian_phone, value: student.guardian_phone || '-' },
            { label: translations.national_id, value: student.national_id || '-' },
            { label: translations.nationality, value: student.nationality_translated || '-' }, 
            { label: translations.email, value: student.email || '-' },
            { label: translations.gender, value: student.gender_translated || '-' }, 
            { label: translations.birth_date, value: student.birth_date || '-' },
            { label: translations.branch, value: student.address_translated || '-' },
            { label: translations.address_details, value: student.address_details || '-' },
            { label: translations.study_system, value: student.study_system_translated || '-' },
            { label: translations.marketer_name, value: student.marketing_source || '-' },
            { 
                label: translations.registration_date, 
                value: student.created_at 
                    ? `<span class="date-display">${student.created_at.split(' ')[0]}</span>` 
                    : '-' 
            }
        ];

        content.innerHTML = fields.map(field => `
                <div class="p-3 md:p-4 rounded-xl bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 shadow-sm">
                    <strong class="text-blue-700 dark:text-blue-400 font-bold block mb-1 text-sm md:text-base">${field.label}</strong>
                    <div class="text-gray-900 dark:text-white font-medium text-base md:text-lg break-words">${field.value}</div>
                </div>
            `).join('');

        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    function closeModal() {
        document.getElementById('detailsModal').classList.add('hidden');
        document.body.style.overflow = 'auto';
    }

    function showCredentials(username, password) {
        document.getElementById('credUsername').textContent = username;
        document.getElementById('credPassword').textContent = password;
        document.getElementById('credentialsModal').classList.remove('hidden');
    }

    function closeCredentialsModal() {
        document.getElementById('credentialsModal').classList.add('hidden');
    }

    function confirmDelete(id) {
        if (confirm(translations.delete_confirm)) {
            fetch(`delete.php?id=${id}`) 
                .then(response => response.json())
                .then(data => {
                    showNotification(data.message, !data.success);
                })
                .catch(error => {
                    showNotification(translations.error_msg, true);
                });
        }
    }
</script>

<?php include('../includes/footer.php'); ?>