<?php
// fee_receipt_view.php
$receipt_no = $_GET['receipt_no'] ?? '';
require_once('libs/classes/DbPathsArray.php');
require_once('libs/classes/App_DB.php');
$db = new App_DB(DBU::$dba_user);
$config = $db->getRecordFilled("SELECT M_Name, M_Address FROM config LIMIT 1");
$m_name = $config ? $config['M_Name'] : 'مدرسہ کا نام';
$m_address = $config ? $config['M_Address'] : 'پتہ یہاں آئے گا';
?>
<!DOCTYPE html>
<html lang="ur" dir="rtl">

<head>
    <meta charset="UTF-8">
    <title>Fee Receipt -
        <?php echo $receipt_no; ?>
    </title>
    <!-- Include the base site styles/Bootstrap if needed -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="assets/css/accounts.css">
    <style>
        .urdu-regular {
            font-family: 'Jameel Noori Nastaleeq', 'Noto Nastaliq Urdu', serif;
        }

        .urdu-bold {
            font-family: 'Jameel Noori Nastaleeq', 'Noto Nastaliq Urdu', serif;
            font-weight: bold;
        }

        .receipt-container {
            max-width: 800px;
            margin: 0 auto;
            background: #fff;
        }

        .receipt-header h1 {
            font-size: 2.5rem;
            color: #000;
        }

        .receipt-header p {
            font-size: 1.25rem;
            color: #555;
        }

        .receipt-title {
            font-size: 1.5rem;
            color: #000;
        }

        .info-card {
            background-color: #f8f9fa !important;
            border-radius: 12px;
            padding: 20px 30px;
        }

        .custom-table th,
        .custom-table td {
            padding: 1rem 1.25rem;
            vertical-align: middle;
            border-color: #dee2e6;
        }

        .custom-table th {
            font-size: 1.1rem;
            background-color: #fdfdfd !important;
        }

        @media print {
            body {
                background-color: #ffffff !important;
                margin: 0;
                padding: 0;
            }

            .d-print-none {
                display: none !important;
            }

            .receipt-container {
                width: 100% !important;
                max-width: 100% !important;
                border: none !important;
                box-shadow: none !important;
                padding: 0 20px !important;
            }

            .info-card {
                background-color: #f8f9fa !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }

            /* Table borders for print */
            .table-bordered th,
            .table-bordered td {
                border: 1px solid #dee2e6 !important;
            }
        }
    </style>
</head>

<body class="bg-light">

    <div class="container py-5">
        <div class="receipt-container card shadow-sm p-5 rounded-4" id="receipt-print-area">

            <!-- Header -->
            <div class="text-center receipt-header">
                <h1 class="urdu-bold mb-3">
                    <?php echo $m_name; ?>
                </h1>
                <p class="urdu-regular mb-4 text-dark">
                    <?php echo $m_address; ?>
                </p>
                <div class="receipt-title urdu-bold mb-4" id="r_title_full">رسید برائے فیس (Fee Receipt)</div>
                <hr style="border-top: 2px solid #ddd; opacity: 1; margin: 0;">
            </div>

            <!-- Date & Receipt No -->
            <div class="d-flex justify-content-between urdu-regular fs-5 mt-4 mb-4">
                <div><strong>رسید نمبر:</strong> <span id="r_no" dir="ltr" class="d-inline-block text-end">
                        <?php echo $receipt_no; ?>
                    </span></div>
                <div><strong>تاریخ:</strong> <span id="r_date" dir="ltr" class="d-inline-block text-start">--</span>
                </div>
            </div>

            <!-- Student Info & QR Card -->
            <div class="info-card mb-4 urdu-regular fs-5">
                <div class="row align-items-center">
                    <!-- Info (Right side in RTL) -->
                    <div class="col-8 text-start">
                        <div class="mb-3"><strong>طالب علم:</strong> <span id="r_std_name">--</span></div>
                        <div class="mb-3"><strong>ولدیت:</strong> <span id="r_std_father">--</span></div>
                        <div><strong>رجسٹریشن نمبر:</strong> <span id="r_std_reg" dir="ltr"
                                class="d-inline-block">--</span></div>
                    </div>
                    <!-- QR (Left side in RTL) -->
                    <div class="col-4 text-center">
                        <div class="bg-white p-1 rounded-3 d-inline-block border">
                            <canvas id="receiptQR" style="height: 120px; width: 120px;"></canvas>
                        </div>
                        <p class="text-muted mt-2 mb-0" style="font-size: 0.9rem;">تصدیق کے لیے سکین کریں</p>
                    </div>
                </div>
            </div>

            <!-- Details Table -->
            <table class="table table-bordered custom-table urdu-regular fs-5 mb-5 mt-3">
                <thead>
                    <tr>
                        <th class="text-end text-dark" style="width: 60%;">تفصیل (DESCRIPTION)</th>
                        <th class="text-start text-dark" style="width: 40%;">رقم (AMOUNT)</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td class="text-end"><span id="r_fee_name" dir="ltr">--</span> (<span id="r_month"
                                dir="ltr">--</span>)</td>
                        <td class="text-start font-weight-bold">Rs. <span id="r_amount">0.00</span></td>
                    </tr>
                    <tr>
                        <td class="text-end fw-bold">کل رقم (Total):</td>
                        <td class="text-start fw-bold">Rs. <span id="r_total">0.00</span></td>
                    </tr>
                </tbody>
            </table>

            <!-- Signature -->
            <div class="d-flex justify-content-end mt-5 pt-3">
                <div class="text-center" style="width: 180px; border-top: 1px solid #000; padding-top: 10px;">
                    <p class="urdu-bold mb-0 fs-5">دستخط منتظم</p>
                </div>
            </div>
        </div>

        <!-- Actions -->
        <div class="text-center mt-4 d-print-none">
            <button class="btn btn-primary btn-lg px-5 urdu-regular shadow-sm rounded-pill" onclick="window.print()">
                <i class="bi bi-printer me-2"></i> پرنٹ کریں (Print)
            </button>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"></script>
    <script>
        // Inline the minimum required QR initialization
        function generateReceiptQR(url) {
            if (document.getElementById('receiptQR')) {
                new QRious({
                    element: document.getElementById('receiptQR'),
                    value: url,
                    size: 150,
                    level: 'H'
                });
            }
        }

        $(document).ready(function () {
            const rNo = "<?php echo $receipt_no; ?>";
            if (rNo) {
                $.getJSON(`APIs/fee_api.php?action=get_receipt&receipt_no=${rNo}`, function (res) {
                    if (res.success) {
                        const d = res.data;
                        // Reformat date if needed (API returns YYYY-MM-DD, snapshot uses DD-MM-YYYY)
                        let formattedDate = d.payment_date;
                        if (formattedDate && formattedDate.includes('-')) {
                            const parts = formattedDate.split('-');
                            if (parts.length === 3) formattedDate = `${parts[2]}-${parts[1]}-${parts[0]}`;
                        }

                        $('#r_date').text(formattedDate);
                        $('#r_std_name').text(d.stdName);
                        $('#r_std_father').text(d.fatherName);
                        $('#r_std_reg').text(d.registrationNo || 'N/A');
                        const monthNamesUrdu = {
                            "01": "جنوری", "02": "فروری", "03": "مارچ", "04": "اپریل",
                            "05": "مئی", "06": "جون", "07": "جولائی", "08": "اگست",
                            "09": "ستمبر", "10": "اکتوبر", "11": "نومبر", "12": "دسمبر"
                        };

                        const parts = d.month_year.split('-');
                        const monthNum = parts[0];
                        const year = parts[1];
                        const monthName = monthNamesUrdu[monthNum] || monthNum;

                        $('#r_title_full').text(`رسید برائے فیس ۔ماہ  ${monthName} (${year})`);

                        $('#r_fee_name').text(d.fee_name);
                        $('#r_month').text(d.month_year);

                        // Format amount
                        const amount = parseFloat(d.collection_amount).toFixed(2);
                        $('#r_amount').text(amount);

                        const total = parseFloat(d.total_amount).toFixed(2);
                        $('#r_total').text(total);

                        // Construct absolute URL for QR Code
                        const protocol = window.location.protocol;
                        const host = window.location.host;
                        let path = window.location.pathname;
                        const absoluteUrl = `${protocol}//${host}${path}?receipt_no=${rNo}`;

                        generateReceiptQR(absoluteUrl);
                    } else {
                        alert(res.message);
                    }
                });
            }
        });
    </script>
</body>

</html>