<link rel="stylesheet" href="assets/css/accounts.css">
<div id="feeModule" dir="rtl" class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold text-success urdu-bold mb-1">فیس رپورٹس (Fee Reports)</h2>
            <p class="text-muted urdu-regular fs-5">تعلیمی سال کے دوران وصول شدہ فیسوں کا خلاصہ</p>
        </div>
        <a href="fee_dashboard" class="btn btn-outline-dark px-4 py-2 rounded-3 urdu-regular fs-5">
            <i class="bi bi-arrow-right me-2"></i> واپس
        </a>
    </div>

    <!-- Filter Card -->
    <div class="card border-0 shadow-sm rounded-4 mb-4">
        <div class="card-body p-4">
            <div class="row g-3 align-items-end">
                <div class="col-md-4">
                    <label class="form-label urdu-bold text-dark">فیس کا مہینہ (Fee Month)</label>
                    <select class="form-select border-2 shadow-sm" id="reportMonth">
                        <option value="">تمام مہینے (All Months)</option>
                        <?php
                        $months = [
                            "01" => "جنوری (January)",
                            "02" => "فروری (February)",
                            "03" => "مارچ (March)",
                            "04" => "اپریل (April)",
                            "05" => "مئی (May)",
                            "06" => "جون (June)",
                            "07" => "جولائی (July)",
                            "08" => "اگست (August)",
                            "09" => "ستمبر (September)",
                            "10" => "اکتوبر (October)",
                            "11" => "نومبر (November)",
                            "12" => "دسمبر (December)"
                        ];
                        foreach ($months as $num => $name) {
                            $selected = ($num == date('m')) ? 'selected' : '';
                            echo "<option value='$num' $selected>$name</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label urdu-bold text-dark">فیس کا سال (Fee Year)</label>
                    <input type="number" class="form-control border-2 shadow-sm" id="reportYear"
                        value="<?php echo date('Y'); ?>" min="2000" max="2100">
                </div>
                <div class="col-md-4">
                    <button class="btn btn-success w-100 py-3 urdu-bold shadow-sm rounded-3" id="btnRunReport">
                        <i class="bi bi-search me-2"></i> رپورٹ تلاش کریں
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Report Table -->
    <div class="card border-0 shadow-sm rounded-4 overflow-hidden">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light urdu-bold">
                        <tr>
                            <th class="px-4 py-3 fs-4">#</th>
                            <th class="py-3 fs-4">تاریخ</th>
                            <th class="py-3 fs-4">مہینہ</th>
                            <th class="py-3 fs-4">سال</th>
                            <th class="py-3 fs-4">طالب علم</th>
                            <th class="py-3 fs-4">فیس کی قسم</th>
                            <th class="py-3 fs-4">رقم</th>
                            <th class="py-3 fs-4">طریقہ</th>
                            <th class="px-4 py-3 text-center fs-4">رسید</th>
                            <th class="text-center px-4 py-3 fs-4">ایڈٹ / ڈیلیٹ</th>
                        </tr>
                    </thead>
                    <tbody id="reportTableBody">
                        <tr>
                            <td colspan="10" class="text-center py-5 text-muted">ڈیٹا دیکھنے کے لیے فلٹر کا استعمال کریں
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Edit Fee Collection Modal (Same as Dashboard) -->
<div class="modal fade" id="editCollectionModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered" dir="rtl">
        <div class="modal-content rounded-4 border-0 shadow">
            <div class="modal-header bg-light border-bottom-0">
                <h5 class="modal-title urdu-bold">فیس میں ترمیم کریں (Edit Fee)</h5>
                <button type="button" class="btn-close m-0 ms-auto" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <form id="formEditCollection">
                    <input type="hidden" id="edit_col_id">

                    <div class="mb-3">
                        <label class="form-label urdu-regular">طالب علم (Student)</label>
                        <input type="text" class="form-control bg-light" id="edit_std_name" readonly>
                    </div>

                    <div class="row mb-3">
                        <div class="col-6">
                            <label class="form-label urdu-regular">فیس کی قسم (Fee Type)</label>
                            <input type="text" class="form-control bg-light" id="edit_fee_name" readonly>
                        </div>
                        <div class="col-6">
                            <label class="form-label urdu-regular">مہینہ (Month)</label>
                            <input type="text" class="form-control bg-light" id="edit_month_year" readonly>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label urdu-bold">رقم (Amount) <span class="text-danger">*</span></label>
                        <input type="number" class="form-control font-monospace fs-5" id="edit_amount" required min="0">
                    </div>

                    <div class="row mb-4">
                        <div class="col-6">
                            <label class="form-label urdu-regular">ادائیگی کی تاریخ (Date)</label>
                            <input type="text" class="form-control hijri-picker" id="edit_payment_date" readonly
                                required>
                        </div>
                        <div class="col-6">
                            <label class="form-label urdu-regular">طریقہ (Method)</label>
                            <select class="form-select" id="edit_payment_method" required>
                                <option value="Cash">Cash (نقد)</option>
                                <option value="Bank">Bank (بینک)</option>
                                <option value="EasyPaisa">EasyPaisa</option>
                                <option value="JazzCash">JazzCash</option>
                            </select>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary w-100 py-2 urdu-bold rounded-3"
                        id="btnUpdateCollection">محفوظ کریں (Save Changes)</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="assets/js/student_fee.js"></script>
<script>
    $(document).ready(function () {
        // Run Report API Call
        $('#btnRunReport').off('click').on('click', runReport);

        function runReport() {
            const month = $('#reportMonth').val();
            const year = $('#reportYear').val();
            const $body = $('#reportTableBody');

            $body.html('<tr><td colspan="10" class="text-center py-4"><div class="spinner-border text-primary"></div></td></tr>');

            const monthNamesUrdu = {
                "1": "جنوری", "2": "فروری", "3": "مارچ", "4": "اپریل",
                "5": "مئی", "6": "جون", "7": "جولائی", "8": "اگست",
                "9": "ستمبر", "10": "اکتوبر", "11": "نومبر", "12": "دسمبر",
                "01": "جنوری", "02": "فروری", "03": "مارچ", "04": "اپریل",
                "05": "مئی", "06": "جون", "07": "جولائی", "08": "اگست",
                "09": "ستمبر"
            };

            $.getJSON(`APIs/fee_api.php?action=get_ledger_global&fee_month=${month}&fee_year=${year}`, function (res) {
                if (res.success) {
                    let rows = '';
                    res.data.forEach((c, i) => {
                        const dateStr = c.created_at ? c.created_at.split(' ')[0].replace(/-/g, '') : '';
                        const receiptNo = `RCP-${dateStr}-${String(c.id).padStart(4, '0')}`;

                        rows += `
                        <tr class="urdu-regular">
                            <td class="px-4">${i + 1}</td>
                            <td>${c.payment_date}</td>
                            <td class="fw-bold text-primary">${monthNamesUrdu[c.fee_month] || c.fee_month}</td>
                            <td class="fw-bold text-primary">${c.fee_year}</td>
                            <td>${c.stdName} بن ${c.fatherName}</td>
                            <td>${c.fee_name}</td>
                            <td class="fw-bold">Rs. ${c.amount}</td>
                            <td>${c.payment_method}</td>
                            <td class="text-center">
                                <a href="fee_receipt_view?receipt_no=${receiptNo}" target="_blank" class="btn btn-sm btn-outline-info"><i class="bi bi-printer"></i></a>
                            </td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-outline-primary btn-edit-col me-1" data-id="${c.id}" title="Edit"><i class="bi bi-pencil"></i></button>
                                <button class="btn btn-sm btn-outline-danger btn-del-col" data-id="${c.id}" title="Delete"><i class="bi bi-trash"></i></button>
                            </td>
                        </tr>
                    `;
                    });
                    $body.html(rows || '<tr><td colspan="10" class="text-center py-4">کوئی ریکارڈ نہیں ملا</td></tr>');
                } else {
                    $body.html('<tr><td colspan="10" class="text-center py-4 text-danger">ڈیٹا لوڈ نہیں ہوسکا (Data could not be loaded)</td></tr>');
                }
            }).fail(function () {
                $body.html('<tr><td colspan="10" class="text-center py-4 text-danger">API سے رابطہ منقطع ہوگیا (Failed to connect to API)</td></tr>');
            });
        }

        // Edit Button Logic
        $(document).on('click', '.btn-edit-col', function () {
            const id = $(this).data('id');
            $.getJSON(`APIs/fee_api.php?action=get_collection_by_id&id=${id}`, function (res) {
                if (res.success) {
                    const d = res.data;
                    $('#edit_col_id').val(d.id);
                    $('#edit_std_name').val(d.stdName + ' بن ' + d.fatherName);
                    $('#edit_fee_name').val(d.fee_name);
                    $('#edit_month_year').val(d.month_year);
                    $('#edit_amount').val(d.amount);
                    $('#edit_payment_date').val(d.payment_date);
                    $('#edit_payment_method').val(d.payment_method);

                    let editModal = new bootstrap.Modal(document.getElementById('editCollectionModal'));
                    editModal.show();
                } else {
                    Swal.fire('Error', res.message, 'error');
                }
            });
        });

        // Delete Button Logic
        $(document).on('click', '.btn-del-col', function () {
            const id = $(this).data('id');
            Swal.fire({
                title: 'کیا آپ واقعی ڈیلیٹ کرنا چاہتے ہیں؟',
                text: "یہ عمل واپس نہیں ہو سکتا (This action cannot be undone)!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'ہاں، ڈیلیٹ کریں',
                cancelButtonText: 'کینسل'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'APIs/fee_api.php',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({ action: 'delete_collection', id: id }),
                        success: function (res) {
                            if (res.success) {
                                Swal.fire('Deleted!', 'ریکارڈ ڈیلیٹ ہو گیا۔', 'success');
                                runReport(); // Reload the report table
                            } else {
                                Swal.fire('Error', res.message, 'error');
                            }
                        }
                    });
                }
            });
        });

        // Update Form Submission Logic
        $('#formEditCollection').on('submit', function (e) {
            e.preventDefault();
            const data = {
                action: 'update_collection',
                id: $('#edit_col_id').val(),
                amount: $('#edit_amount').val(),
                payment_date: $('#edit_payment_date').val(),
                payment_method: $('#edit_payment_method').val(),
                month_year: $('#edit_month_year').val()
            };

            const $btn = $('#btnUpdateCollection');
            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

            $.ajax({
                url: 'APIs/fee_api.php',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (res) {
                    $btn.prop('disabled', false).text('محفوظ کریں (Save Changes)');
                    if (res.success) {
                        $('#editCollectionModal').modal('hide');
                        Swal.fire('Success', 'ریکارڈ اپڈیٹ ہو گیا۔', 'success');
                        runReport(); // Reload the report table
                    } else {
                        Swal.fire('Error', res.message, 'error');
                    }
                }
            });
        });
    });
</script>