<?php
// fee_dashboard.php
?>
<link rel="stylesheet" href="assets/css/accounts.css">

<div id="feeDashboard" dir="rtl" class="container-fluid py-4">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold text-success urdu-bold mb-1">طلباء فیس مینجمنٹ (Student Fee Dashboard)</h2>
            <p class="text-muted urdu-regular fs-5">فیس کی وصولی اور بقایا جات کا انتظام</p>
        </div>
        <div class="d-flex gap-2">
            <a href="fee_collection" class="btn btn-success px-4 py-2 rounded-3 urdu-regular fs-5">
                <i class="bi bi-cash-coin me-2"></i> فیس وصول کریں
            </a>
            <a href="dashboard" class="btn btn-outline-dark px-4 py-2 rounded-3 urdu-regular fs-5">
                <i class="bi bi-house me-2"></i> مین ڈیش بورڈ
            </a>
        </div>
    </div>

    <!-- Stats Row -->
    <div class="row g-4 mb-4">
        <div class="col-md-3">
            <div class="card stats-card border-0 shadow-sm bg-primary text-white text-center p-3">
                <h6 class="urdu-regular fs-6 opacity-75">آج کی کل وصولی</h6>
                <h2 class="fw-bold mb-0" id="statToday">Rs. 0</h2>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card stats-card border-0 shadow-sm bg-warning text-dark text-center p-3">
                <h6 class="urdu-regular fs-6 opacity-75">اس ماہ کی کل وصولی</h6>
                <h2 class="fw-bold mb-0" id="statMonth">Rs. 0</h2>
            </div>
        </div>
        <div class="col-md-3">
            <a href="defaulters_list" class="text-decoration-none">
                <div class="card stats-card border-0 shadow-sm bg-danger text-white text-center p-3"
                    style="cursor: pointer;">
                    <h6 class="urdu-regular fs-6 opacity-75">بقایا جات (Defaulters)</h6>
                    <h2 class="fw-bold mb-0" id="statDefaulters">0</h2>
                </div>
            </a>
        </div>
        <div class="col-md-3">
            <div class="card stats-card border-0 shadow-sm bg-info text-white text-center p-3">
                <h6 class="urdu-regular fs-6 opacity-75">کل رجسٹرڈ طلباء</h6>
                <h2 class="fw-bold mb-0" id="statStudents">0</h2>
            </div>
        </div>
    </div>

    <!-- Quick Links & Recent Collections -->
    <div class="row g-4">
        <div class="col-md-4">
            <div class="card border-0 shadow-sm rounded-4 h-100 text-end">
                <div class="card-body p-4">
                    <h5 class="urdu-bold mb-4 border-bottom pb-2">کوئیک ایکشنز (Quick Actions)</h5>
                    <div class="list-group list-group-flush urdu-regular">
                        <a href="fee_assignments" class="list-group-item list-group-item-action border-0 py-3 fs-5">
                            <i class="bi bi-person-gear text-primary me-3"></i> فیس تفویض کریں (Step 1: Assign Fees)
                        </a>
                        <a href="fee_collection" class="list-group-item list-group-item-action border-0 py-3 fs-5">
                            <i class="bi bi-plus-circle-fill text-success me-3"></i> نئی فیس وصولی (Step 2: New Fee
                            Collection)
                        </a>
                        <a href="fee_reports" class="list-group-item list-group-item-action border-0 py-3 fs-5">
                            <i class="bi bi-file-earmark-bar-graph text-info me-3"></i> فیس رپورٹس (Fee Reports)
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-8">
            <div class="card border-0 shadow-sm rounded-4 h-100 text-end">
                <div class="card-body p-4">
                    <h5 class="urdu-bold mb-4 border-bottom pb-2">حالیہ وصولیاں (Recent Collections)</h5>
                    <div class="table-responsive">
                        <table class="table table-sm urdu-regular align-middle">
                            <thead class="bg-light">
                                <tr>
                                    <th>طالب علم</th>
                                    <th>ادائیگی کی قسم</th>
                                    <th>مہینہ</th>
                                    <th>سال</th>
                                    <th>رقم</th>
                                    <th>تاریخ</th>
                                    <th class="text-center">ایڈٹ / ڈیلیٹ</th>
                                </tr>
                            </thead>
                            <tbody id="recentList">
                                <tr>
                                    <td colspan="4" class="text-center py-4 text-muted">ڈیٹا لوڈ ہو رہا ہے...</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Fee Collection Modal -->
<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>
    $(document).ready(function () {
        loadDashboardSummary();

        // Edit Button Click
        $(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 Click
        $(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');
                                loadDashboardSummary();
                            } else {
                                Swal.fire('Error', res.message, 'error');
                            }
                        }
                    });
                }
            });
        });

        // Update Form Submit
        $('#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');
                        loadDashboardSummary();
                    } else {
                        Swal.fire('Error', res.message, 'error');
                    }
                }
            });
        });
    });

    function loadDashboardSummary() {
        $.getJSON('APIs/fee_api.php?action=dashboard_summary', function (res) {
            if (res.success) {
                const d = res.data;
                $('#statToday').text('Rs. ' + Number(d.today_collection).toLocaleString());
                $('#statMonth').text('Rs. ' + Number(d.month_collection).toLocaleString());
                $('#statStudents').text(d.total_students);
                $('#statDefaulters').text(d.defaulters_count);

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

                let tbody = $('#recentList');
                tbody.empty();
                let totalRecent = 0;
                if (d.recent_collections && d.recent_collections.length > 0) {
                    d.recent_collections.forEach(c => {
                        const dateStr = c.created_at ? c.created_at.split(' ')[0].replace(/-/g, '') : '';
                        const receiptNo = `RCP-${dateStr}-${String(c.id).padStart(4, '0')}`;
                        totalRecent += parseFloat(c.amount);

                        tbody.append(`
                        <tr>
                            <td>${c.stdName}</td>
                            <td>${c.fee_name}</td>
                            <td>${monthNamesUrdu[c.fee_month] || c.fee_month}</td>
                            <td>${c.fee_year}</td>
                            <td class="text-success fw-bold">Rs. ${Number(c.amount).toLocaleString()}</td>
                            <td><span class="badge bg-light text-dark border">${c.payment_date}</span></td>
                            <td class="text-center">
                                <a href="fee_receipt_view?receipt_no=${receiptNo}" target="_blank" class="btn btn-sm btn-outline-info me-1" title="Print Receipt"><i class="bi bi-printer"></i></a>
                                <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>
                    `);
                    });
                    // Append Total Row
                    tbody.append(`
                    <tr class="table-light urdu-bold border-top-2">
                        <td colspan="4" class="text-start fs-5">کل (Total):</td>
                        <td class="text-success fs-5">Rs. ${totalRecent.toLocaleString()}</td>
                        <td colspan="2"></td>
                    </tr>
                `);
                } else {
                    tbody.append('<tr><td colspan="7" class="text-center py-4 text-muted">کوئی ریکارڈ نہیں ملا</td></tr>');
                }
            } else {
                Swal.fire('Error', res.message || 'Failed to load dashboard data', 'error');
            }
        }).fail(function () {
            Swal.fire('Error', 'Network error occurred while fetching dashboard data', 'error');
        });
    }
</script>