<?php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

require_once('../config/db.php');

// التأكد من استدعاء ملف اللغة والوظائف الأساسية
include('../includes/header.php'); 

$from_date = $_GET['from'] ?? '';
$to_date = $_GET['to'] ?? '';

// جلب الطلاب
$students = $conn->query("SELECT id, full_name 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();
}

$processed_students = [];
$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);

    $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);
    
    $processed_students[] = $student;
    $total_remaining_all += ($remaining > 0 ? $remaining : 0);
}
?>

<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: 20px;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }

    #studentsTable { min-width: 1000px; width: 100% !important; border-collapse: collapse !important; }
    #studentsTable th, #studentsTable td { text-align: <?= $dir == 'rtl' ? '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; align-items: center; font-size: 11px; background: white; border: 1px solid #e5e7eb; border-radius: 8px; overflow: hidden; }

    @media print {
        nav, .no-print, footer { display: none !important; }
        .max-w-7xl { max-width: 100% !important; width: 100% !important; }
        .table-responsive { overflow: visible !important; }
        #studentsTable { min-width: 100% !important; }
    }
</style>

<?php include('../includes/navbar.php'); ?>

<div class="min-h-screen 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-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-file-invoice-dollar text-indigo-500 <?= $dir == 'rtl' ? 'ml-3' : 'mr-3' ?>"></i> <?= __('payments_report_title') ?>
                    </h2>
                    <p class="mt-1 text-xs text-gray-500 font-bold">
                        <?= __('report_date') ?>: <?php echo date('Y-m-d'); ?> | <?= __('total_records') ?>: <?= count($processed_students) ?>
                    </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"><?= __('total_receivables') ?></p>
                    <p class="text-2xl font-black text-indigo-700"><?= number_format($total_remaining_all, 2) ?> <span class="text-sm"><?= __('currency_symbol') ?></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 <?= $dir == 'rtl' ? 'ml-3' : 'mr-3' ?>"></div>
                <h3 class="text-xl font-bold text-gray-800 dark:text-gray-100"><?= __('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 <?= $dir == 'rtl' ? 'mr-1' : 'ml-1' ?>"><?= __('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 transition">
                </div>
                <div>
                    <label class="block text-xs font-bold text-gray-500 mb-2 <?= $dir == 'rtl' ? 'mr-1' : 'ml-1' ?>"><?= __('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 transition">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-xs font-bold text-gray-500 mb-2 <?= $dir == 'rtl' ? 'mr-1' : 'ml-1' ?>"><?= __('instant_quick_search') ?></label>
                    <input type="text" id="globalSearch" placeholder="<?= __('search_placeholder_payments') ?>" 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 transition">
                </div>

                <div class="flex items-end gap-3">
                    <button id="applyFilter" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white py-2.5 px-4 rounded-lg text-sm font-semibold shadow-md transition whitespace-nowrap">
                        <i class="fas fa-filter <?= $dir == 'rtl' ? 'ml-1' : 'mr-1' ?>"></i> <?= __('apply_filter') ?>
                    </button>
                    
                    <button type="button" id="btnReset" onclick="window.location.href='report.php'" class="flex-1 bg-gray-300 hover:bg-gray-400 text-gray-800 py-2.5 px-4 rounded-lg text-sm font-semibold shadow-md transition whitespace-nowrap">
                        <i class="fas fa-undo-alt <?= $dir == 'rtl' ? 'ml-1' : 'mr-1' ?>"></i> <?= __('reset_filter') ?>
                    </button>
                </div>
            </form>
        </div>

        <div class="table-responsive">
            <table id="studentsTable" class="min-w-full">
                <thead class="table-header">
                    <tr>
                        <th class="<?= $dir == 'rtl' ? 'rounded-tr-xl' : 'rounded-tl-xl' ?>"><?= __('student_name') ?></th>
                        <th class="text-center"><?= __('total_price') ?></th>
                        <th class="text-center"><?= __('paid_amount') ?></th>
                        <th class="text-center"><?= __('discount') ?></th>
                        <th class="text-center"><?= __('remaining_amount') ?></th>
                        <th><?= __('enrolled_courses') ?></th>
                        <th class="<?= $dir == 'rtl' ? 'rounded-tl-xl' : 'rounded-tr-xl' ?> text-center no-print"><?= __('action') ?></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 text-sm">
                    <?php foreach ($processed_students as $student): ?>
                        <tr class="hover:bg-indigo-50/30 transition">
                            <td class="font-bold text-gray-900"><?= htmlspecialchars($student['full_name']) ?></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="<?= $student['remaining'] > 0 ? 'bg-red-600 text-white' : 'bg-emerald-600 text-white' ?> px-3 py-1.5 rounded-lg font-black block text-xs shadow-sm">
                                    <?= number_format($student['remaining'], 2) ?>
                                </span>
                            </td>
                            <td>
                                <div class="flex flex-wrap gap-1 max-w-xs">
                                    <?php if (empty($student['courses'])): ?>
                                        <span class="text-gray-400">---</span>
                                    <?php else: ?>
                                        <?php foreach ($student['courses'] as $course): ?>
                                            <div class="course-badge shadow-sm">
                                                <span class="px-2 py-0.5 text-gray-700 font-medium"><?= htmlspecialchars($course['course_name']) ?></span>
                                                <span class="bg-indigo-600 text-white px-2 py-0.5 font-bold"><?= number_format($course['price'], 0) ?></span>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="text-center no-print">
                                <div class="flex justify-center gap-1">
                                    <a title="<?= __('add_payment_hint') ?>" href="add_payment.php?student_id=<?= $student['id'] ?>" class="bg-emerald-500 text-white w-8 h-8 flex items-center justify-center rounded-lg hover:bg-emerald-600 transition shadow-sm"><i class="fas fa-plus text-[10px]"></i></a>
                                    <a title="<?= __('view_payments_hint') ?>" href="view_payments.php?student_id=<?= $student['id'] ?>" class="bg-indigo-500 text-white w-8 h-8 flex items-center justify-center rounded-lg hover:bg-indigo-600 transition shadow-sm"><i class="fas fa-eye text-[10px]"></i></a>
                                    <a title="<?= __('online_payment_hint') ?>" href="pay_online.php?student_id=<?= $student['id'] ?>" class="bg-purple-500 text-white w-8 h-8 flex items-center justify-center rounded-lg hover:bg-purple-600 transition shadow-sm"><i class="fas fa-credit-card text-[10px]"></i></a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <p class="md:hidden text-center text-[10px] text-gray-400 mt-4"><?= __('scroll_hint_payments') ?></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": "<?= __('dt_info') ?>",
            "sZeroRecords": "<?= __('dt_zero_records') ?>",
            "oPaginate": { 
                "sNext": "<?= $dir == 'rtl' ? "<i class='fas fa-chevron-left text-xs'></i>" : "<i class='fas fa-chevron-right text-xs'></i>" ?>", 
                "sPrevious": "<?= $dir == 'rtl' ? "<i class='fas fa-chevron-right text-xs'></i>" : "<i class='fas fa-chevron-left text-xs'></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'); ?>