<?php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: ../auth/login.php');
    exit;
}

require_once('../config/db.php');

// تعيين قيم التاريخ الافتراضية (الشهر الحالي)
$start_date = date('Y-m-01');
$end_date = date('Y-m-d');

// قراءة مدخلات الفلترة
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!empty($_GET['start_date'])) {
        $start_date = $_GET['start_date'];
    }
    if (!empty($_GET['end_date'])) {
        $end_date = $_GET['end_date'];
    }
}

$expense_search = $_GET['expense_search'] ?? '';

// جلب المدفوعات مع اسم الطالب ضمن النطاق الزمني
$stmtPayments = $conn->prepare("
    SELECT payments.*, students.full_name 
    FROM payments 
    JOIN students ON payments.student_id = students.id 
    WHERE payment_date BETWEEN ? AND ? 
    ORDER BY payment_date DESC
");
$stmtPayments->execute([$start_date, $end_date]);
$payments = $stmtPayments->fetchAll();

// جلب المصروفات ضمن النطاق الزمني مع شرط البحث في نوع المصروف أو الوصف إذا تم الإدخال
if ($expense_search !== '') {
    $searchTerm = "%$expense_search%";
    $stmtExpenses = $conn->prepare("SELECT * FROM expenses WHERE expense_date BETWEEN ? AND ? AND (expense_type LIKE ? OR description LIKE ?) ORDER BY expense_date DESC");
    $stmtExpenses->execute([$start_date, $end_date, $searchTerm, $searchTerm]);
} else {
    $stmtExpenses = $conn->prepare("SELECT * FROM expenses WHERE expense_date BETWEEN ? AND ? ORDER BY expense_date DESC");
    $stmtExpenses->execute([$start_date, $end_date]);
}
$expenses = $stmtExpenses->fetchAll();

// حساب المجموعات
$totalPayments = 0;
foreach ($payments as $payment) {
    $totalPayments += $payment['amount_paid'];
}

$totalExpenses = 0;
foreach ($expenses as $expense) {
    $totalExpenses += $expense['amount'];
}

$netBalance = $totalPayments - $totalExpenses;

?>

<?php include('../includes/header.php'); ?>

<nav class="bg-white shadow" dir="rtl">
    <div class="max-w-7xl mx-auto px-4 py-4 flex justify-between items-center">
        <div class="text-2xl font-bold text-blue-700">نظام إدارة الكورسات</div>
        <div class="space-x-4 rtl:space-x-reverse">
            <a href="../dashboard.php" class="text-gray-700 hover:text-blue-600 font-medium">الرئيسية</a>
            <a href="../auth/logout.php" class="text-red-600 hover:underline font-medium">تسجيل الخروج</a>
        </div>
    </div>
</nav>

<div class="max-w-7xl mx-auto p-6" dir="rtl">

    <h2 class="text-2xl font-bold mb-6">تقرير المالية</h2>

    <form method="GET" class="mb-6 flex flex-wrap gap-4 items-end">
        <div>
            <label for="start_date" class="block mb-1 font-semibold">من تاريخ:</label>
            <input type="date" name="start_date" id="start_date" value="<?= htmlspecialchars($start_date) ?>" class="border rounded px-3 py-2" required>
        </div>
        <div>
            <label for="end_date" class="block mb-1 font-semibold">إلى تاريخ:</label>
            <input type="date" name="end_date" id="end_date" value="<?= htmlspecialchars($end_date) ?>" class="border rounded px-3 py-2" required>
        </div>
        <div>
            <label for="expense_search" class="block mb-1 font-semibold">بحث في نوع المصروف أو الوصف:</label>
            <input type="text" name="expense_search" id="expense_search" value="<?= htmlspecialchars($expense_search) ?>" class="border rounded px-3 py-2" placeholder="أدخل نص للبحث">
        </div>
        <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-5 py-2 rounded shadow font-medium transition">بحث</button>
    </form>

    <div class="bg-white rounded-2xl shadow p-6">

        <div class="mb-6 grid grid-cols-1 sm:grid-cols-3 gap-6 text-center">
            <div class="p-4 bg-green-100 rounded-lg">
                <h3 class="text-lg font-semibold text-green-700 mb-2">إجمالي المدفوعات</h3>
                <p class="text-2xl font-bold text-green-700"><?= number_format($totalPayments, 2) ?> د.أ</p>
            </div>
            <div class="p-4 bg-red-100 rounded-lg">
                <h3 class="text-lg font-semibold text-red-700 mb-2">إجمالي المصروفات</h3>
                <p class="text-2xl font-bold text-red-700"><?= number_format($totalExpenses, 2) ?> د.أ</p>
            </div>
            <div class="p-4 bg-blue-100 rounded-lg">
                <h3 class="text-lg font-semibold text-blue-700 mb-2">صافي الرصيد</h3>
                <p class="text-2xl font-bold text-blue-700"><?= number_format($netBalance, 2) ?> د.أ</p>
            </div>
        </div>

        <!-- جدول المدفوعات -->
        <div class="overflow-x-auto mb-2">
            <h3 class="text-xl font-semibold mb-3">المدفوعات</h3>
            <table id="payments-table" class="min-w-full border border-gray-300 rounded-xl text-right" dir="rtl">
                <thead class="bg-green-100 text-green-700 font-semibold">
                    <tr>
                        <th class="border border-green-300 px-4 py-2">التاريخ</th>
                        <th class="border border-green-300 px-4 py-2">اسم الطالب</th>
                        <th class="border border-green-300 px-4 py-2">المبلغ</th>
                        <th class="border border-green-300 px-4 py-2">الوصف</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($payments) > 0): ?>
                        <?php foreach ($payments as $payment): ?>
                            <tr class="hover:bg-green-50 transition">
                                <td class="border border-green-200 px-4 py-2"><?= htmlspecialchars($payment['payment_date']) ?></td>
                                <td class="border border-green-200 px-4 py-2"><?= htmlspecialchars($payment['full_name']) ?></td>
                                <td class="border border-green-200 px-4 py-2"><?= number_format($payment['amount_paid'], 2) ?> د.أ</td>
                                <td class="border border-green-200 px-4 py-2"><?= htmlspecialchars($payment['notes'] ?? '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="4" class="text-center p-4 text-gray-500">لا توجد مدفوعات في هذا النطاق الزمني</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <!-- أزرار المدفوعات -->
        <div class="my-4 flex gap-4 justify-center">
            <button onclick="printSection('payments-table')" class="bg-green-700 text-white px-4 py-2 rounded hover:bg-green-800">
                🖨 طباعة المدفوعات
            </button>
            <button onclick="exportTableToExcel('payments-table', 'تقرير_المدفوعات')" class="bg-yellow-600 text-white px-4 py-2 rounded hover:bg-yellow-700">
                📁 تصدير المدفوعات إلى Excel
            </button>
        </div>

        <!-- جدول المصروفات -->
        <div class="overflow-x-auto mt-10">
            <h3 class="text-xl font-semibold mb-3">المصروفات</h3>
            <table id="expenses-table" class="min-w-full border border-gray-300 rounded-xl text-right" dir="rtl">
                <thead class="bg-red-100 text-red-700 font-semibold">
                    <tr>
                        <th class="border border-red-300 px-4 py-2">التاريخ</th>
                        <th class="border border-red-300 px-4 py-2">نوع المصروف</th>
                        <th class="border border-red-300 px-4 py-2">المبلغ</th>
                        <th class="border border-red-300 px-4 py-2">الوصف</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($expenses) > 0): ?>
                        <?php foreach ($expenses as $expense): ?>
                            <tr class="hover:bg-red-50 transition">
                                <td class="border border-red-200 px-4 py-2"><?= htmlspecialchars($expense['expense_date']) ?></td>
                                <td class="border border-red-200 px-4 py-2"><?= htmlspecialchars($expense['expense_type']) ?></td>
                                <td class="border border-red-200 px-4 py-2"><?= number_format($expense['amount'], 2) ?> د.أ</td>
                                <td class="border border-red-200 px-4 py-2"><?= htmlspecialchars($expense['description'] ?? '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="4" class="text-center p-4 text-gray-500">لا توجد مصروفات في هذا النطاق الزمني</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <!-- أزرار المصروفات -->
        <div class="my-4 flex gap-4 justify-center">
            <button onclick="printSection('expenses-table')" class="bg-red-700 text-white px-4 py-2 rounded hover:bg-red-800">
                🖨 طباعة المصروفات
            </button>
            <button onclick="exportTableToExcel('expenses-table', 'تقرير_المصروفات')" class="bg-yellow-600 text-white px-4 py-2 rounded hover:bg-yellow-700">
                📁 تصدير المصروفات إلى Excel
            </button>
        </div>

    </div>
</div>

<script>
function printSection(tableId) {
    const table = document.getElementById(tableId);
    if (!table) return alert('لا يوجد جدول للطباعة');

    const originalTitle = document.title;
    const schoolName = 'نظام إدارة الكورسات';
    const reportName = tableId === 'payments-table' ? 'تقرير المدفوعات' : 'تقرير المصروفات';
    const today = new Date().toLocaleDateString('ar-EG');

    // رابط اللوغو (ضع رابط صورة اللوغو هنا)
    const logoUrl = '../assets/logo.jpg'; // عدّل المسار حسب موقع الصورة عندك

    let printContent = `
        <html dir="rtl" lang="ar">
        <head>
            <title>${originalTitle}</title>
            <style>
                body { font-family: "Cairo", sans-serif; padding: 20px; }
                header { text-align: center; margin-bottom: 20px; }
                header img { max-height: 80px; margin-bottom: 10px; }
                h1, h2, h3 { margin: 5px 0; }
                table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                th, td { border: 1px solid #999; padding: 8px; text-align: right; }
                th { background-color: #f0f0f0; }
                tr:nth-child(even) { background: #f9f9f9; }
            </style>
        </head>
        <body>
            <header>
                <img src="${logoUrl}" alt="لوغو" />

                <h1>${schoolName}</h1>
                <h2>${reportName}</h2>
                <h3>تاريخ الطباعة: ${today}</h3>
            </header>
            ${table.outerHTML}
        </body>
        </html>
    `;

    const printWindow = window.open('', '_blank', 'width=900,height=700');
    printWindow.document.write(printContent);
    printWindow.document.close();
    printWindow.focus();
    printWindow.print();
    printWindow.close();
}


// تصدير جدول إلى ملف Excel بصيغة XLS
function exportTableToExcel(tableId, filename = '') {
    const table = document.getElementById(tableId);
    if (!table) return alert('لا يوجد جدول للتصدير');

    const schoolName = 'نظام إدارة الكورسات';
    const today = new Date().toLocaleDateString('ar-EG');

    let tableHTML = `
        <table dir="rtl" border="1" style="border-collapse: collapse; width: 100%;">
            <thead>
                <tr>
                    <th colspan="${table.rows[0].cells.length}" style="background:#f0f0f0; font-size:20px; text-align:center;">${schoolName}</th>
                </tr>
                <tr>
                    <th colspan="${table.rows[0].cells.length}" style="text-align:center;">تاريخ التصدير: ${today}</th>
                </tr>
            </thead>
            <tbody>
                ${table.innerHTML}
            </tbody>
        </table>
    `;

    const blob = new Blob(['\ufeff' + tableHTML], {
        type: 'application/vnd.ms-excel'
    });

    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename ? filename + '.xls' : 'financial_report.xls';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
</script>

<?php include('../includes/footer.php'); ?>
