<?php
session_start();
require_once('../config/db.php');


// ✅ التحقق من تسجيل الدخول
if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

// ✅ جلب بيانات الكورسات مع عد الطلاب النشطين
try {
    $sql = "SELECT c.*, 
            (SELECT COUNT(*) FROM enrollments e WHERE e.course_id = c.id AND e.status = 'نشط') as active_students_count
            FROM courses c 
            ORDER BY c.created_at DESC";
    
    $stmt = $conn->query($sql);
    $courses = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}

// ✅ ملاحظة: تم نقل تحديد اللغة إلى داخل header.php لتوحيد النظام
?>

<?php include('../includes/header.php'); ?>

<style>
    /* أنماط الـ Modal والحركة */
    @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;
    }
    .action-button {
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.15s ease-in-out;
    }
    /* إظهار التوست */
    .toast-active {
        display: flex !important;
        opacity: 1 !important;
        transform: translateY(0) !important;
    }
</style>

<?php include('../includes/navbar.php'); ?>

<div class="min-h-screen bg-gray-100 dark:bg-gray-900 pb-16" 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-book-reader text-indigo-500 <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('course_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-plus-circle <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('add_new_course') ?>
                    </a>
                    <a href="../rate/course_ratings.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-star <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('course_ratings') ?>
                    </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_courses') ?>"
                    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 font-bold <?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>">
        </div>

        <div class="overflow-x-auto rounded-xl shadow-2xl">
            <table id="coursesTable" 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"><?= __('course_name') ?></th>
                        <th class="p-4 border-b border-r border-indigo-400 text-center"><?= __('active_students') ?></th>
                        <th class="p-4 border-b border-r border-indigo-400"><?= __('price') ?></th>
                        <th class="p-4 border-b border-r border-indigo-400"><?= __('duration') ?></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 ($courses): ?>
                        <?php foreach ($courses as $course): ?>
                            <tr class="border-b dark:border-gray-700">
                                <td class="p-4 border-r dark:border-gray-700 font-bold text-indigo-600 dark:text-indigo-400">
                                    <?= htmlspecialchars($course['course_name']) ?>
                                </td>
                                <td class="p-4 border-r dark:border-gray-700 text-center">
                                    <span class="inline-block px-3 py-1 text-sm font-black rounded-lg bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-300">
                                        <?= $course['active_students_count'] ?> <?= __('student_unit') ?>
                                    </span>
                                </td>
                                <td class="p-4 border-r dark:border-gray-700 text-green-600 dark:text-green-400 font-bold">
                                   <span class="date-display"><?= number_format($course['price'], 2) ?></span>
                                </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 bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-300">
                                        <?= htmlspecialchars($course['duration_weeks'] ?? '-') ?> <?= __('weeks') ?>
                                    </span>
                                </td>
                                <td class="p-4 text-center">
                                    <div class="action-group">
                                        
                                        <button onclick="graduateStudents(<?= $course['id'] ?>, '<?= htmlspecialchars($course['course_name']) ?>')"
                                           class="action-button bg-orange-500 hover:bg-orange-600 p-2 rounded-full text-white shadow-md transform hover:scale-110" title="<?= __('graduate_all') ?>">
                                            <i class="fas fa-graduation-cap w-4 h-4"></i>
                                        </button>
                                        
                                        <button onclick='showDetails(<?= json_encode($course, 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=<?= $course['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(<?= $course['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>
                                    </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_courses_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-4">
    <div class="bg-white dark:bg-gray-800 rounded-3xl shadow-2xl w-full max-w-3xl p-8 relative animate-fadeIn border-t-8 border-blue-600">
        <button onclick="closeModal()" 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-blue-700 dark:text-blue-400">📋 <?= __('course_details') ?></h3>
        <div id="detailsContent" class="grid grid-cols-1 md:grid-cols-2 gap-6 text-gray-700 dark:text-gray-300 text-md"></div>
        <div class="text-center 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">
                <i class="fas fa-times <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('close_window') ?>
            </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 class="fas fa-check-circle <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?> text-2xl" id="toastIcon"></i> 
    <span id="toastMessage"></span>
</div>

<script>
    // نمرر مفاتيح الترجمة للجافاسكريبت لضمان تناسق اللغة في التنبيهات والمودال
    const translations = {
        'course_name': "<?= __('course_name') ?>",
        'price': "<?= __('price') ?>",
        'duration': "<?= __('duration') ?>",
        'weeks': "<?= __('weeks') ?>",
        'registration_date': "<?= __('registration_date') ?>",
        'description': "<?= __('description') ?>",
        'delete_confirm': "<?= __('delete_confirm_msg') ?>",
        'graduate_confirm': "<?= __('graduate_confirm_msg') ?>",
        'success_msg': "<?= __('operation_success') ?>",
        'error_msg': "<?= __('operation_error') ?>",
    };

    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 ? 3000 : 1500);
    }

    function searchTable() {
        const input = document.getElementById('searchInput').value.toLowerCase();
        document.querySelectorAll('#coursesTable tbody tr').forEach(row => {
            const rowContent = row.textContent.toLowerCase();
            row.style.display = rowContent.includes(input) ? '' : 'none';
        });
    }

    function graduateStudents(courseId, courseName) {
        // استخدام الترجمة الممررة من PHP
        if (confirm(translations.graduate_confirm.replace(':name', courseName))) {
            fetch(`graduate_students.php?course_id=${courseId}`)
                .then(response => {
                    if(response.ok) {
                        showNotification(translations.success_msg);
                    } else {
                        showNotification(translations.error_msg, true);
                    }
                });
        }
    }

    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);
                });
        }
    }

    function showDetails(course) {
        const modal = document.getElementById('detailsModal');
        const content = document.getElementById('detailsContent');
        
        const fields = [
            { label: translations.course_name, value: course.course_name },
            { label: translations.price, value: `<span class="date-display">${parseFloat(course.price).toFixed(2)}</span>` },
            { label: translations.duration, value: `${course.duration_weeks ?? '-'} ${translations.weeks}` },
            { 
                label: translations.registration_date, 
                value: course.created_at ? `<span class="date-display">${course.created_at.split(' ')[0]}</span>` : '-' 
            },
            { label: translations.description, value: course.description ?? '-', full: true },
        ];

        content.innerHTML = fields.map(field => `
                <div class="p-4 rounded-xl bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 shadow-sm ${field.full ? 'md:col-span-2' : ''}">
                    <strong class="text-blue-700 dark:text-blue-400 font-bold block mb-1"><?= $dir == 'rtl' ? '' : '' ?>${field.label}</strong>
                    <div class="text-gray-900 dark:text-white font-medium text-lg whitespace-pre-wrap">${field.value}</div>
                </div>
            `).join('');
        modal.classList.remove('hidden');
    }

    function closeModal() { document.getElementById('detailsModal').classList.add('hidden'); }
</script>

<?php include('../includes/footer.php'); ?>