<?php
session_start();

// ✅ استدعاء الهيدر لتعريف نظام الترجمة والاتجاهات
include('../includes/header.php');

if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    header('Location: ../auth/login.php');
    exit;
}

require_once('../config/db.php');

// جلب الفروع للفلترة
$branches = $conn->query("SELECT DISTINCT address FROM students WHERE address IS NOT NULL AND address != ''")->fetchAll(PDO::FETCH_COLUMN);

// الاستعلام لجلب أرصدة الطلاب
$query = "
    SELECT 
        s.id as student_id,
        s.full_name, 
        s.address as branch_name,
        s.phone, 
        COALESCE(SUM(p.amount_paid), 0) as total_paid,
        COALESCE(SUM(p.discount), 0) as total_payment_discounts,
        (SELECT SUM(c.price) FROM enrollments e JOIN courses c ON e.course_id = c.id WHERE e.student_id = s.id) as original_price,
        (SELECT SUM(e.discount) FROM enrollments e WHERE e.student_id = s.id) as enroll_discounts,
        MAX(p.payment_date) as last_payment_date
    FROM students s
    LEFT JOIN payments p ON s.id = p.student_id
    GROUP BY s.id
    ORDER BY s.full_name ASC
";

$stmt = $conn->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

$grand_total = array_sum(array_column($results, 'total_paid'));
?>

<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">

<style>
    body { font-family: 'Cairo', sans-serif; background-color: #f3f4f6; overflow-x: hidden; }
    .header-card { background: white; border-radius: 15px; padding: 24px; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); border-bottom: 8px solid #4f46e5; }
    
    .table-responsive { 
        width: 100%;
        overflow-x: auto; 
        -webkit-overflow-scrolling: touch;
        background: white;
        border-radius: 15px;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    
    #paymentsTable { min-width: 900px; }
    .table-header { background-color: #4f46e5; color: white; }
    th, td { white-space: nowrap; padding: 15px 20px; }

    @media print {
        nav, aside, header, footer, .no-print, #sidebar, .sidebar-wrapper, .navbar, #menu-toggle { 
            display: none !important; 
        }
        body { background: white !important; margin: 0 !important; padding: 0 !important; }
        .max-w-7xl { max-width: 100% !important; width: 100% !important; margin: 0 !important; }
        .print-only-header { display: flex !important; justify-content: space-between; align-items: center; border-bottom: 3px solid #4f46e5; padding-bottom: 20px; margin-bottom: 30px; }
        .table-responsive { overflow: visible !important; box-shadow: none !important; border: 1px solid #eee !important; }
        #paymentsTable { min-width: 100% !important; }
        th { background-color: #f3f4f6 !important; color: black !important; border: 1px solid #ddd !important; -webkit-print-color-adjust: exact; }
    }
    .print-only-header { display: none; }
</style>

<div class="no-print">
    <?php include('../includes/navbar.php'); ?>
</div>

<div class="min-h-screen pb-20" dir="<?= $dir ?>">
    <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">

        <div class="print-only-header">
            <div class="<?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>">
                <h1 class="text-3xl font-black text-indigo-700"><?= __('institute_name') ?></h1>
                <p class="text-lg text-gray-600"><?= __('financial_report_subtitle') ?></p>
                <p class="text-sm text-gray-500 mt-2" id="printDateRangeDisplay"><?= __('all_periods_report') ?></p>
            </div>
            <div class="inline-flex items-center justify-center w-32 h-32 rounded-full bg-white shadow-xl border-4 border-[#c5a059]/20 p-2 transform hover:scale-105 transition-transform duration-300">
                <img src="../assets/logo.png" alt="Logo" class="w-full h-full object-contain rounded-full">
            </div>
        </div>

        <div class="header-card mb-8 no-print">
            <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">
                        <i class="fas fa-wallet text-indigo-500 <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('financial_report_title') ?>
                    </h2>
                    <p class="mt-1 text-xs text-gray-500 font-bold">
                        <?= __('version') ?>: 1.0 | <?= __('today_date') ?>: <?php echo date('Y-m-d'); ?>
                    </p>
                </div>
                <div class="flex flex-wrap gap-2">
                    <button onclick="window.print()" class="bg-gray-800 text-white px-5 py-2.5 rounded-xl font-bold shadow-lg hover:bg-black transition flex items-center text-sm">
                        <i class="fas fa-print <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('print') ?>
                    </button>
                    <button onclick="exportToExcel()" class="bg-emerald-600 text-white px-5 py-2.5 rounded-xl font-bold shadow-lg hover:bg-emerald-700 transition flex items-center text-sm">
                        <i class="fas fa-file-excel <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('export_excel') ?>
                    </button>
                </div>
            </div>
        </div>

        <div class="bg-white shadow-xl rounded-2xl p-6 mb-8 border-t-4 border-indigo-500 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"><?= __('advanced_filtering') ?></h3>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-12 gap-4 items-end">
                <div class="md:col-span-2">
                    <label class="block text-xs font-bold text-gray-500 mb-2 <?= $dir == 'rtl' ? 'mr-1' : 'ml-1' ?>"><?= __('branch') ?></label>
                    <select id="branchFilter" class="w-full border-gray-200 rounded-xl text-sm py-2.5 px-3 focus:ring-2 focus:ring-indigo-500 outline-none">
                        <option value=""><?= __('all_branches') ?></option>
                        <?php foreach ($branches as $b): ?>
                            <option value="<?= htmlspecialchars($b) ?>"><?= htmlspecialchars($b) ?></option>
                        <?php endforeach; ?>
                    </select>
                </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' ?>"><?= __('from_date') ?></label>
                    <input type="date" id="dateFrom" class="w-full border-gray-200 rounded-xl text-sm py-2.5 px-3 focus:ring-2 focus:ring-indigo-500 outline-none">
                </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' ?>"><?= __('to_date') ?></label>
                    <input type="date" id="dateTo" class="w-full border-gray-200 rounded-xl text-sm py-2.5 px-3 focus:ring-2 focus:ring-indigo-500 outline-none">
                </div>

                <div class="md:col-span-3">
                    <label class="block text-xs font-bold text-gray-500 mb-2 <?= $dir == 'rtl' ? 'mr-1' : 'ml-1' ?>"><?= __('instant_search') ?></label>
                    <div class="relative">
                        <span class="absolute inset-y-0 <?= $dir == 'rtl' ? 'right-0 pr-3' : 'left-0 pl-3' ?> flex items-center text-gray-400">
                            <i class="fas fa-search text-xs"></i>
                        </span>
                        <input type="text" id="globalSearch" placeholder="<?= __('search_name_phone_placeholder') ?>" 
                               class="<?= $dir == 'rtl' ? 'pr-9' : 'pl-9' ?> w-full border-gray-200 rounded-xl text-sm py-2.5 px-3 focus:ring-2 focus:ring-indigo-500 outline-none">
                    </div>
                </div>

                <div class="md:col-span-3 flex gap-2">
                    <button id="applyFilter" class="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white py-2.5 rounded-xl text-sm font-bold shadow-md transition">
                        <?= __('apply') ?>
                    </button>
                    <button id="resetFilter" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-700 py-2.5 rounded-xl text-sm font-bold transition">
                        <?= __('reset') ?>
                    </button>
                </div>
            </div>
        </div>

        <div class="table-responsive">
            <table id="paymentsTable" class="w-full <?= $dir == 'rtl' ? 'text-right' : 'text-left' ?> border-collapse">
                <thead class="table-header">
                    <tr>
                        <th class="<?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>"><?= __('student_info') ?></th>
                        <th class="text-center"><?= __('original_amount') ?></th>
                        <th class="text-center"><?= __('discounts') ?></th>
                        <th class="text-center"><?= __('net_amount') ?></th>
                        <th class="text-center"><?= __('paid_amount') ?></th>
                        <th class="text-center"><?= __('remaining_amount') ?></th>
                        <th class="text-center"><?= __('last_payment') ?></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 text-sm">
                    <?php foreach ($results as $row): 
                        $total_disc = ($row['total_payment_discounts'] ?? 0) + ($row['enroll_discounts'] ?? 0);
                        $net_req = ($row['original_price'] ?? 0) - $total_disc;
                        $remaining = $net_req - $row['total_paid'];
                        $last_date = $row['last_payment_date'] ? date('Y-m-d', strtotime($row['last_payment_date'])) : '';
                    ?>
                    <tr class="hover:bg-indigo-50 transition" 
                        data-branch="<?= htmlspecialchars($row['branch_name'] ?? '') ?>" 
                        data-date="<?= $last_date ?>">
                        <td>
                            <div class="font-bold text-gray-900"><?= htmlspecialchars($row['full_name']) ?></div>
                            <div class="text-[11px] text-gray-500"><?= $row['phone'] ?> | <?= $row['branch_name'] ?: __('main_center') ?></div>
                        </td>
                        <td class="text-center text-gray-400 line-through"><?= number_format($row['original_price'], 2) ?></td>
                        <td class="text-center text-orange-600 font-bold"><?= number_format($total_disc, 2) ?></td>
                        <td class="text-center font-bold text-gray-700"><?= number_format($net_req, 2) ?></td>
                        <td class="text-center font-black text-emerald-600" data-paid="<?= $row['total_paid'] ?>">
                            <?= number_format($row['total_paid'], 2) ?>
                        </td>
                        <td class="text-center">
                            <?php 
                            if ($net_req <= 0) {
                                echo '<span class="text-gray-400 font-bold text-xs">'.__('no_dues').'</span>';
                            } elseif ($remaining > 0.05) {
                                if ($row['total_paid'] <= 0) {
                                    echo '<span class="bg-orange-100 text-orange-700 px-3 py-1 rounded-lg font-bold text-xs">'.__('not_paid').'</span>';
                                } else {
                                    echo '<span class="bg-red-600 text-white px-3 py-1 rounded-lg font-bold text-xs shadow-sm">' . number_format($remaining, 2) . '</span>';
                                }
                            } else {
                                echo '<span class="text-emerald-500 font-bold text-xs"><i class="fas fa-check-circle '.($dir == 'rtl' ? 'ml-1' : 'mr-1').'"></i> '.__('completed').'</span>';
                            }
                            ?>
                        </td>
                        <td class="text-center text-gray-500 text-xs"><?= $last_date ?: '---' ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="bg-gray-800 text-white font-black">
                        <td colspan="4" class="p-4 <?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>"><?= __('total_collection_display') ?></td>
                        <td class="p-4 text-center text-emerald-400" id="totalDisplay">
                            <?= number_format($grand_total, 2) ?> <?= __('currency') ?>
                        </td>
                        <td colspan="2" class="p-4"></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        <p class="md:hidden text-center text-[10px] text-gray-400 mt-4"><?= __('scroll_hint') ?></p>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const tableBody = document.querySelector('#paymentsTable tbody');
    const totalDisplay = document.getElementById('totalDisplay');
    const globalSearch = document.getElementById('globalSearch');
    const branchFilter = document.getElementById('branchFilter');
    const applyFilterBtn = document.getElementById('applyFilter');
    const dateFrom = document.getElementById('dateFrom');
    const dateTo = document.getElementById('dateTo');

    function filterTable() {
        const branchVal = branchFilter.value.toLowerCase();
        const fromVal = dateFrom.value;
        const toVal = dateTo.value;
        const searchVal = globalSearch.value.toLowerCase();
        let currentTotal = 0;

        const rangeText = (fromVal || toVal) ? `<?= __('period_from') ?> ${fromVal || '...'} <?= __('period_to') ?> ${toVal || '...'}` : '<?= __('all_periods_report') ?>';
        document.getElementById('printDateRangeDisplay').innerText = rangeText;

        Array.from(tableBody.rows).forEach(row => {
            const rDate = row.getAttribute('data-date');
            const rBranch = (row.getAttribute('data-branch') || "").toLowerCase();
            const rText = row.innerText.toLowerCase();
            const rPaid = parseFloat(row.cells[4].getAttribute('data-paid')) || 0;

            const matchesDate = (!fromVal || rDate >= fromVal) && (!toVal || rDate <= toVal);
            const matchesBranch = !branchVal || rBranch.includes(branchVal);
            const matchesSearch = !searchVal || rText.includes(searchVal);

            if (matchesDate && matchesBranch && matchesSearch) {
                row.style.display = '';
                currentTotal += rPaid;
            } else {
                row.style.display = 'none';
            }
        });
        totalDisplay.innerText = currentTotal.toLocaleString(undefined, {minimumFractionDigits: 2}) + ' <?= __('currency') ?>';
    }

    globalSearch.addEventListener('input', filterTable);
    branchFilter.addEventListener('change', filterTable);
    applyFilterBtn.addEventListener('click', filterTable);

    document.getElementById('resetFilter').addEventListener('click', () => {
        branchFilter.value = '';
        dateFrom.value = '';
        dateTo.value = '';
        globalSearch.value = '';
        filterTable();
    });
});

function exportToExcel() {
    const table = document.getElementById("paymentsTable");
    const wb = XLSX.utils.table_to_book(table, {sheet: "<?= __('excel_sheet_name') ?>"});
    XLSX.writeFile(wb, "<?= __('excel_file_name') ?>.xlsx");
}
</script>

<?php include('../includes/footer.php'); ?>