<?php
session_start();
require_once('../config/db.php');

// ✅ استدعاء الهيدر لتعريف نظام الترجمة والاتجاهات
include('../includes/header.php');

if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

// جلب كافة المصروفات
$query = "SELECT * FROM expenses ORDER BY expense_date DESC";
$stmt = $conn->prepare($query);
$stmt->execute();
$expenses = $stmt->fetchAll(PDO::FETCH_ASSOC);

$grand_total = array_sum(array_column($expenses, 'amount'));

// جلب أنواع المصروفات للقائمة المنسدلة
$types_stmt = $conn->query("SELECT DISTINCT expense_type FROM expenses WHERE expense_type IS NOT NULL");
$all_types = $types_stmt->fetchAll(PDO::FETCH_COLUMN);
?>

<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: #f8fafc; overflow-x: hidden; }
    .header-card { background: white; border-radius: 20px; padding: 24px; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.05); border-bottom: 8px solid #ef4444; }
    
    .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);
        border: 1px solid #e5e7eb;
    }
    
    #expensesTable { min-width: 800px; }
    .table-header { background-color: #ef4444; color: white; }
    th, td { white-space: nowrap; padding: 15px 20px; }
    
    @media print {
        nav, .no-print, #sidebar, .sidebar-wrapper, .navbar, footer { display: none !important; }
        body { background: white !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 #ef4444; padding-bottom: 15px; margin-bottom: 25px; }
        .table-responsive { overflow: visible !important; box-shadow: none !important; border: 1px solid #eee !important; }
        #expensesTable { 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-red-700"><?= __('institute_name') ?></h1>
                <p class="text-lg text-gray-600"><?= __('expenses_report_subtitle') ?></p>
                <p class="text-sm text-gray-500 mt-1" 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-file-invoice-dollar text-red-500 <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> <?= __('expenses_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-md 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-md hover:bg-emerald-700 transition flex items-center text-sm">
                        <i class="fas fa-file-excel <?= $dir == 'rtl' ? 'ml-2' : 'mr-2' ?>"></i> Excel
                    </button>
                </div>
            </div>
        </div>

        <div class="bg-white shadow-xl rounded-2xl p-6 mb-8 border-t-4 border-red-500 no-print">
            <div class="flex items-center mb-6">
                <div class="w-1.5 h-6 bg-red-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' ?>"><?= __('expense_type') ?></label>
                    <select id="typeFilter" class="w-full border-gray-200 rounded-xl text-sm py-2.5 px-3 focus:ring-2 focus:ring-red-500 outline-none shadow-sm transition">
                        <option value=""><?= __('all_types') ?></option>
                        <?php foreach($all_types as $type): ?>
                            <option value="<?= htmlspecialchars($type) ?>"><?= htmlspecialchars($type) ?></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-red-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' ?>"><?= __('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-red-500 outline-none shadow-sm transition">
                </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' ?>"><?= __('general_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_desc_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-red-500 outline-none shadow-sm transition">
                    </div>
                </div>

                <div class="md:col-span-3 flex gap-2">
                    <button id="applyFilter" class="flex-1 bg-red-600 hover:bg-red-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="expensesTable" class="w-full <?= $dir == 'rtl' ? 'text-right' : 'text-left' ?> border-collapse">
                <thead class="table-header text-sm">
                    <tr>
                        <th class="<?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>"><?= __('date') ?></th>
                        <th class="<?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>"><?= __('expense_type') ?></th>
                        <th class="text-center"><?= __('amount') ?></th>
                        <th class="<?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>"><?= __('description') ?></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 text-sm font-medium text-gray-700">
                    <?php foreach ($expenses as $e): ?>
                    <tr class="hover:bg-red-50 transition-colors" 
                        data-type="<?= htmlspecialchars($e['expense_type']) ?>" 
                        data-date="<?= $e['expense_date'] ?>">
                        <td><?= $e['expense_date'] ?></td>
                        <td>
                            <span class="bg-red-100 text-red-700 px-3 py-1 rounded-full text-xs font-bold border border-red-200">
                                <?= htmlspecialchars($e['expense_type']) ?>
                            </span>
                        </td>
                        <td class="text-center font-black text-red-600 text-lg" data-amount="<?= $e['amount'] ?>">
                            <?= number_format($e['amount'], 2) ?>
                        </td>
                        <td class="text-gray-500 whitespace-normal min-w-[200px]">
                            <?= htmlspecialchars($e['description'] ?: '---') ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="bg-gray-900 text-white font-black text-lg">
                        <td colspan="2" class="p-5 <?= $dir == 'rtl' ? 'text-right' : 'text-left' ?>"><?= __('total_expenses_display') ?></td>
                        <td class="p-5 text-center text-red-400" id="totalDisplay">
                            <?= number_format($grand_total, 2) ?> <?= __('currency') ?>
                        </td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
        <p class="md:hidden text-center text-[10px] text-gray-400 mt-4"><?= __('scroll_hint_simple') ?></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('#expensesTable tbody');
    const totalDisplay = document.getElementById('totalDisplay');
    const globalSearch = document.getElementById('globalSearch');
    const typeFilter = document.getElementById('typeFilter');
    const dateFrom = document.getElementById('dateFrom');
    const dateTo = document.getElementById('dateTo');
    const applyFilterBtn = document.getElementById('applyFilter');

    function filterTable() {
        const searchVal = globalSearch.value.toLowerCase();
        const typeVal = typeFilter.value.toLowerCase();
        const fromVal = dateFrom.value;
        const toVal = dateTo.value;
        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 rType = (row.getAttribute('data-type') || "").toLowerCase();
            const rText = row.innerText.toLowerCase();
            const rAmount = parseFloat(row.cells[2].getAttribute('data-amount')) || 0;

            const matchesDate = (!fromVal || rDate >= fromVal) && (!toVal || rDate <= toVal);
            const matchesType = !typeVal || rType.includes(typeVal);
            const matchesSearch = !searchVal || rText.includes(searchVal);

            if (matchesDate && matchesType && matchesSearch) {
                row.style.display = '';
                currentTotal += rAmount;
            } else {
                row.style.display = 'none';
            }
        });
        
        totalDisplay.innerText = currentTotal.toLocaleString(undefined, {minimumFractionDigits: 2}) + ' <?= __('currency') ?>';
    }

    globalSearch.addEventListener('input', filterTable);
    typeFilter.addEventListener('change', filterTable);
    applyFilterBtn.addEventListener('click', filterTable);

    document.getElementById('resetFilter').addEventListener('click', () => {
        globalSearch.value = '';
        typeFilter.value = '';
        dateFrom.value = '';
        dateTo.value = '';
        filterTable();
    });
});

function exportToExcel() {
    const table = document.getElementById("expensesTable");
    const wb = XLSX.utils.table_to_book(table, {sheet: "<?= __('expenses_sheet_name') ?>"});
    XLSX.writeFile(wb, "<?= __('expenses_file_name') ?>.xlsx");
}
</script>

<?php include('../includes/footer.php'); ?>