<?php
session_start();
require_once('../config/db.php');

// جلب لغة المستخدم أو الافتراضية
$current_lang = $_SESSION['lang'] ?? 'ar';
$lang = include("../languages/{$current_lang}.php");

if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

$from_date = $_GET['from'] ?? '';
$to_date = $_GET['to'] ?? '';

// جلب الطلاب
$students = $conn->query("SELECT id, full_name, phone FROM students ORDER BY full_name")->fetchAll();

// دوال المساعدة (بقيت كما هي لضمان دقة الحسابات)
function getTotalCoursePrice($conn, $student_id, $from = '', $to = '') {
    $sql = "SELECT SUM(c.price) FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = ?";
    $params = [$student_id];
    if ($from && $to) {
        $sql .= " AND DATE(e.enrollment_date) BETWEEN ? AND ?";
        $params[] = $from; $params[] = $to;
    }
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchColumn() ?? 0;
}

function getTotalPayments($conn, $student_id) {
    $stmt = $conn->prepare("SELECT SUM(amount_paid) FROM payments WHERE student_id = ?");
    $stmt->execute([$student_id]);
    return $stmt->fetchColumn() ?? 0;
}

function getTotalDiscount($conn, $student_id) {
    $stmt = $conn->prepare("SELECT SUM(discount) FROM payments WHERE student_id = ?");
    $stmt->execute([$student_id]);
    return $stmt->fetchColumn() ?? 0;
}

function getStudentCourses($conn, $student_id, $from = '', $to = '') {
    $sql = "SELECT c.course_name, c.price, e.enrollment_date FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = ?";
    $params = [$student_id];
    if ($from && $to) {
        $sql .= " AND DATE(e.enrollment_date) BETWEEN ? AND ?";
        $params[] = $from; $params[] = $to;
    }
    $sql .= " ORDER BY e.enrollment_date DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
}

$students_with_remaining = [];
$total_remaining_all = 0;

foreach ($students as $student) {
    $totalPrice = getTotalCoursePrice($conn, $student['id'], $from_date, $to_date);
    $totalPaid = getTotalPayments($conn, $student['id']);
    $totalDiscount = getTotalDiscount($conn, $student['id']);
    $remaining = $totalPrice - ($totalPaid + $totalDiscount);

    if ($remaining > 0.05) { // تصفية الديون الحقيقية فقط
        $student['total_price'] = $totalPrice;
        $student['total_paid'] = $totalPaid;
        $student['total_discount'] = $totalDiscount;
        $student['remaining'] = $remaining;
        $student['courses'] = getStudentCourses($conn, $student['id'], $from_date, $to_date);
        $students_with_remaining[] = $student;
        $total_remaining_all += $remaining;
    }
}
?>

<?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" />
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">

<style>
    body { font-family: 'Cairo', sans-serif; background-color: #f8fafc; overflow-x: hidden; }
    
    /* متجاوب مع الجوال */
    .table-responsive { 
        width: 100%; 
        overflow-x: auto; 
        -webkit-overflow-scrolling: touch; 
        background: white; 
        border-radius: 15px; 
    }

    #studentsTable { min-width: 1000px; width: 100% !important; border-collapse: collapse !important; }
    #studentsTable th, #studentsTable td { text-align: <?= $current_lang == 'ar' ? 'right' : 'left' ?> !important; padding: 15px !important; white-space: nowrap; }

    .table-header { background-color: #4f46e5; color: white; }
    
    /* ستايل الترقيم */
    .dataTables_wrapper .dataTables_paginate { display: flex !important; justify-content: center; gap: 8px; margin-top: 25px; }
    .dataTables_wrapper .dataTables_paginate .paginate_button { 
        background: #fff !important; border: 1px solid #e2e8f0 !important; border-radius: 10px !important; 
        padding: 6px 14px !important; color: #4f46e5 !important; font-weight: 700 !important; cursor: pointer; 
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button.current { background: #4f46e5 !important; color: white !important; }
    .dataTables_filter { display: none; }

    .course-badge { display: flex; items-center; font-size: 11px; background: #f3f4f6; border: 1px solid #e5e7eb; border-radius: 8px; overflow: hidden; }
    
    @media print {
        nav, aside, header, footer, .no-print, .dataTables_paginate, .dataTables_info { display: none !important; }
        body { background: white !important; }
        .max-w-7xl { max-width: 100% !important; width: 100% !important; }
        .table-responsive { overflow: visible !important; }
        #studentsTable { min-width: 100% !important; table-layout: auto; }
    }
</style>

<?php include('../includes/navbar.php'); ?>

<div class="min-h-screen pb-16" dir="<?= $current_lang == 'ar' ? 'rtl' : 'ltr' ?>">
    <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-2xl p-6 mb-8 border-b-8 border-indigo-600/50">
            <div class="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
                <div>
                    <h2 class="text-3xl font-extrabold text-gray-800 dark:text-gray-100">
                        <i class="fas fa-wallet text-indigo-500 <?= $current_lang == 'ar' ? 'ml-3' : 'mr-3' ?>"></i> <?= $lang['student_remaining_report'] ?? 'تقرير ذمم الطلاب' ?>
                    </h2>
                    <p class="mt-1 text-xs text-gray-500 font-bold">
                        <?= $lang['report_date'] ?? 'تاريخ التقرير' ?>: <?php echo date('Y-m-d'); ?> | <?= $lang['total_debtors'] ?? 'إجمالي المدينين' ?>: <?= count($students_with_remaining) ?>
                    </p>
                </div>
                <div class="bg-indigo-50 px-8 py-3 rounded-2xl border border-indigo-100 text-center">
                    <p class="text-xs text-indigo-500 font-bold mb-1"><?= $lang['total_remaining_dues'] ?? 'إجمالي الذمم المستحقة' ?></p>
                    <p class="text-2xl font-black text-indigo-700"><?= number_format($total_remaining_all, 2) ?> <span class="text-sm"><?= $lang['currency'] ?? 'د.أ' ?></span></p>
                </div>
            </div>
        </div>

        <div class="bg-white dark:bg-gray-800 shadow-xl rounded-xl p-6 mb-8 border-t-4 border-indigo-400 no-print">
            <div class="flex items-center mb-6">
                <div class="w-1.5 h-6 bg-indigo-500 rounded-full <?= $current_lang == 'ar' ? 'ml-3' : 'mr-3' ?>"></div>
                <h3 class="text-xl font-bold text-gray-800 dark:text-gray-100"><?= $lang['advanced_filter_options'] ?? 'خيارات الفلترة المتقدمة' ?></h3>
            </div>
            
            <form method="GET" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-5 gap-4">
                <div>
                    <label class="block text-xs font-bold text-gray-500 mb-2 mr-1"><?= $lang['from_date'] ?? 'من تاريخ' ?> </label>
                    <input type="date" name="from" value="<?= htmlspecialchars($from_date) ?>" class="w-full border-gray-200 dark:bg-gray-700 dark:text-white rounded-xl text-sm py-2.5 px-3 focus:ring-2 focus:ring-indigo-500 outline-none shadow-sm">
                </div>
                <div>
                    <label class="block text-xs font-bold text-gray-500 mb-2 mr-1"><?= $lang['to_date'] ?? 'إلى تاريخ' ?></label>
                    <input type="date" name="to" value="<?= htmlspecialchars($to_date) ?>" class="w-full border-gray-200 dark:bg-gray-700 dark:text-white rounded-xl text-sm py-2.5 px-3 focus:ring-2 focus:ring-indigo-500 outline-none shadow-sm">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-xs font-bold text-gray-500 mb-2 mr-1"><?= $lang['instant_search'] ?? 'بحث فوري' ?></label>
                    <input type="text" id="globalSearch" placeholder="<?= $lang['search_student_course_placeholder'] ?? 'ابحث باسم الطالب أو الكورس...' ?>" class="w-full border-gray-200 dark:bg-gray-700 dark:text-white rounded-xl text-sm py-2.5 px-3 focus:ring-2 focus:ring-indigo-500 outline-none shadow-sm">
                </div>

                <div class="flex items-end gap-2">
                    <button type="submit" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white py-2.5 rounded-xl text-sm font-bold shadow-md transition">
                        <?= $lang['apply'] ?? 'تطبيق' ?>
                    </button>
                    <a href="?" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 py-2.5 rounded-xl text-sm font-bold transition text-center">
                        <?= $lang['reset'] ?? 'إعادة' ?>
                    </a>
                </div>
            </form>
        </div>

        <div class="table-responsive shadow-xl">
            <table id="studentsTable" class="w-full">
                <thead class="table-header">
                    <tr>
                        <th><?= $lang['student_name'] ?? 'اسم الطالب' ?></th>
                        <th class="text-center"><?= $lang['total_fees'] ?? 'إجمالي الرسوم' ?></th>
                        <th class="text-center"><?= $lang['paid_amount'] ?? 'المدفوع' ?></th>
                        <th class="text-center"><?= $lang['discount'] ?? 'الخصم' ?></th>
                        <th class="text-center"><?= $lang['remaining_amount'] ?? 'المتبقي' ?></th>
                        <th><?= $lang['course_details'] ?? 'تفاصيل الكورسات' ?></th>
                        <th class="text-center no-print"><?= $lang['actions'] ?? 'إجراء' ?></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 text-sm">
                    <?php foreach ($students_with_remaining as $student): ?>
                        <tr class="hover:bg-indigo-50/50 transition">
                            <td>
                                <div class="font-bold text-gray-900"><?= htmlspecialchars($student['full_name']) ?></div>
                                <div class="text-[10px] text-gray-400">ID: #<?= $student['id'] ?></div>
                            </td>
                            <td class="text-center text-gray-600 font-bold"><?= number_format($student['total_price'], 2) ?></td>
                            <td class="text-center text-emerald-600 font-bold"><?= number_format($student['total_paid'], 2) ?></td>
                            <td class="text-center text-orange-500 font-bold"><?= number_format($student['total_discount'], 2) ?></td>
                            <td class="text-center">
                                <span class="bg-red-600 text-white px-3 py-1.5 rounded-lg font-black block text-sm shadow-sm">
                                    <?= number_format($student['remaining'], 2) ?>
                                </span>
                            </td>
                            <td>
                                <div class="flex flex-wrap gap-1 max-w-xs">
                                    <?php foreach ($student['courses'] as $course): ?>
                                        <div class="course-badge">
                                            <span class="px-2 py-0.5 text-gray-700 font-medium"><?= htmlspecialchars($course['course_name']) ?></span>
                                            <span class="bg-indigo-100 text-indigo-700 px-2 py-0.5 font-bold <?= $current_lang == 'ar' ? 'border-r' : 'border-l' ?> border-gray-200"><?= number_format($course['price'], 0) ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </td>
                            <td class="text-center no-print">
                                <div class="flex justify-center gap-2">
                                    <a href="../payments/add_payment.php?student_id=<?= $student['id'] ?>" title="<?= $lang['add_payment'] ?? 'إضافة دفعة' ?>" class="bg-emerald-500 text-white w-9 h-9 flex items-center justify-center rounded-xl hover:bg-emerald-600 transition shadow-sm">
                                        <i class="fas fa-plus text-xs"></i>
                                    </a>
                                    <a href="../payments/view_payments.php?student_id=<?= $student['id'] ?>" title="<?= $lang['view_history'] ?? 'عرض السجل' ?>" class="bg-indigo-500 text-white w-9 h-9 flex items-center justify-center rounded-xl hover:bg-indigo-600 transition shadow-sm">
                                        <i class="fas fa-eye text-xs"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <p class="md:hidden text-center text-[10px] text-gray-400 mt-4"><?= $lang['swipe_table_note'] ?? 'اسحب الجدول يميناً ويساراً لعرض كافة البيانات ↔' ?></p>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<script>
$(document).ready(function() {
    var table = $('#studentsTable').DataTable({
        autoWidth: false,
        language: {
            "sInfo": "<?= $lang['dt_info'] ?? 'عرض _START_ إلى _END_ من أصل _TOTAL_ طالب مدين' ?>",
            "sZeroRecords": "<?= $lang['dt_zero'] ?? 'لا يوجد طلاب لديهم ذمم مالية حالياً' ?>",
            "oPaginate": { 
                "sNext": "<?= $current_lang == 'ar' ? '<i class=\"fas fa-chevron-left\"></i>' : '<i class=\"fas fa-chevron-right\"></i>' ?>", 
                "sPrevious": "<?= $current_lang == 'ar' ? '<i class=\"fas fa-chevron-right\"></i>' : '<i class=\"fas fa-chevron-left\"></i>' ?>" 
            }
        },
        pageLength: 10,
        ordering: true,
        order: [[4, "desc"]], // الترتيب حسب المتبقي تنازلياً
        dom: 'rt<"bottom-info"i><"bottom-pagination"p>'
    });
    
    $('#globalSearch').on('keyup', function() { table.search(this.value).draw(); });
});
</script>

<?php include('../includes/footer.php'); ?>