$(function () {

    // ============================================================
    // Search Form Handler
    // ============================================================
    $('#searchForm').on('submit', function (e) {
        e.preventDefault();
        const darja = $('#darja').val();
        const fromDat = $('#fromDat').val();
        const toDate = $('#toDate').val();

        if (!darja || !fromDat || !toDate) {
            Swal.fire('توجہ', 'درجہ اور تاریخوں کا ہونا ضروری ہے', 'warning');
            return;
        }

        const btn = $('#btnSearch');
        btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>تلاش جاری ہے...');

        $.ajax({
            url: 'APIs/id_card_std.php',
            method: 'GET',
            data: { darja: darja, fromDat: fromDat, toDate: toDate },
            success: function (res) {
                btn.prop('disabled', false).html('<i class="bi bi-search me-2"></i>تلاش کریں');
                if (res.success) {
                    renderIDCards(res);
                    $('#resultsSection').removeClass('d-none');
                } else {
                    Swal.fire('ریکارڈ نہیں ملا', res.message, 'error');
                    $('#resultsSection').addClass('d-none');
                    $('#idCardResults').empty();
                }
            },
            error: function () {
                btn.prop('disabled', false).html('<i class="bi bi-search me-2"></i>تلاش کریں');
                Swal.fire('خرابی', 'ڈیٹا حاصل کرنے میں کوئی مسئلہ پیش آیا', 'error');
            }
        });
    });

    function renderIDCards(res) {
        const data = res.data;
        const container = $('#idCardResults');
        container.empty();

        data.forEach(student => {
            const cardHtml = `
                <div class="w-100 overflow-auto mb-4">
                    <div class="id-card-item avoid-break" style="width: 1086px; height: 311px; margin: 0 auto;">
                    <div class="id-card-inner d-flex h-100" style="gap: 20px;">
                        
                        <!-- Front of Card (Right side visually because of RTL) -->
                        <div class="id-card-side id-card-front position-relative border border-secondary rounded p-2" style="width: calc(50% - 10px);">
                            
                            <!-- Header Layer -->
                            <div class="d-flex justify-content-between align-items-center border-bottom border-2 border-secondary pb-1 mb-2">
                                <!-- Reg Number (Left) -->
                                <div class="text-start" style="width: 25%;">
                                    <div class="fw-bold urdu-regular" style="font-size: 1.6rem; line-height: 1.2;">رجسٹرڈ</div>
                                    <div class="ltr font-monospace fw-bold" style="font-size: 1.2rem; line-height: 1.2;">${res.reg_number}</div>
                                </div>
                                
                                <!-- Madrasa Names (Center) -->
                                <div class="text-center" style="width: 50%;">
                                    <h2 class="urdu-regular fw-bold mb-0 text-dark" style="font-size: 1.6rem; letter-spacing: 1px; line-height: 1.2;">${res.m_name}</h2>
                                    <p class="urdu-regular mb-0 text-dark" style="font-size: 1.5rem; line-height: 1.2;">${res.m_address}</p>
                                </div>
                                
                                <!-- Logo (Right) -->
                                <div class="text-end text-center" style="width: 25%;">
                                    <img src="images/card_logo.png" style="max-height: 60px; object-fit: contain;" onerror="this.style.display='none'">
                                </div>
                            </div>

                            <!-- Body Layer -->
                            <div class="d-flex h-100">
                                <!-- Details (Right side of body) -->
                                <div class="pe-2 pt-1" style="width: 65%;">
                                    <div class="d-flex mb-1">
                                        <div class="urdu-regular fw-bold fs-5 text-end pe-2" style="width: 115px; line-height: 1.2;">نام طالب علم</div>
                                        <div class="urdu-regular fs-5 flex-grow-1" style="line-height:1.2">${student.stdName}</div>
                                    </div>
                                    <div class="d-flex mb-1">
                                        <div class="urdu-regular fw-bold fs-5 text-end pe-2" style="width: 115px; line-height: 1.2;">ولدیت</div>
                                        <div class="urdu-regular fs-5 flex-grow-1" style="line-height:1.2">${student.fatherName}</div>
                                    </div>
                                    <div class="d-flex mb-1 mt-2">
                                        <div class="urdu-regular fw-bold fs-5 text-end pe-2" style="width: 115px; line-height:1.2">رجسٹریشن نمبر</div>
                                        <div class="ltr font-monospace fs-5 flex-grow-1" style="line-height:1.2">${student.registrationNoShort}</div>
                                    </div>
                                    <div class="d-flex mb-1 mt-2">
                                        <div class="urdu-regular fw-bold fs-5 text-end pe-2" style="width: 115px; line-height:1.2">تاریخ پیدائش</div>
                                        <div class="ltr font-monospace fs-5 flex-grow-1" style="line-height:1.2">${student.dobFormatted}</div>
                                    </div>
                                    <div class="d-flex mb-1 mt-4">
                                        <div class="urdu-regular small fw-bold fs-5" style="line-height:1.2">دستخط ناظم تعلیمات</div>
                                        <div class="ms-3" style="width: 80px; transform: translateY(-10px);top: 10px; position: relative;">
                                            <img src="images/Signature.png" class="img-fluid" onerror="this.style.display='none'">
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Student Large Photo (Left side of body) -->
                                <div class="ps-2 pt-1 position-relative" style="width: 35%;">
                                    <div class="border border-dark overflow-hidden mb-2" style="width: 110px; height: 140px; float: left;">
                                        <img src="uploaded/${student.stdPhoto}" class="w-100 h-100" style="object-fit: cover;">
                                    </div>
                                </div>
                            </div>

                        </div>

                        <!-- Back of Card (Left side visually because of RTL) -->
                        <div class="id-card-side id-card-back p-3 position-relative d-flex flex-column justify-content-between border border-secondary rounded" style="width: calc(50% - 10px);">
                            
                            <!-- Top Area -->
                            <div class="d-flex justify-content-between">
                                <!-- ID Label & Top Info -->
                                <div class="flex-grow-1 w-100 me-3">
                                    <div class="d-flex mb-2 text-end">
                                        <span class="fw-bold urdu-regular fs-5" style="line-height:1.2">${student.idLabel}</span>
                                        <span class="ms-3 ltr font-monospace fs-6 fw-bold px-2" style="line-height:1.2;position: relative; top: 5px;">${student.idValue}</span>
                                    </div>
                                    
                                    <div class="mb-2 text-end">
                                        <div class="urdu-regular fw-bold fs-5" style="line-height:1.2">مستقل پتہ:<span class="px-2">${student.permanentAddress}</span></div>
                                    </div>

                                    <div class="mb-3 text-end">
                                        <div class="urdu-regular fw-bold fs-5" style="line-height:1.2">موجودہ پتہ:<span class="px-2">${student.presentAddress}</span></div>
                                    </div>
                                </div>
                                
                                <!-- Small Photo Top Left -->
                                <div class="flex-shrink-0 ms-2">
                                    <div class="border border-dark shadow-sm overflow-hidden" style="width: 75px; height: 95px;">
                                        <img src="uploaded/${student.stdPhoto}" class="w-100 h-100" style="object-fit: cover;">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="w-100">
                                <!-- Darja and Roll No -->
                                <div class="d-flex justify-content-between align-items-center mb-3 px-3">
                                    <div class="d-flex align-items-center">
                                        <span class="fw-bold fs-5 urdu-regular" style="line-height:1.2">رول نمبر</span>
                                        <span class="ltr font-monospace fs-5 ms-3 fw-bold px-2" style="line-height:1.2">${student.RollNumber}</span>
                                    </div>
                                    <div class="d-flex align-items-center">
                                        <span class="fw-bold fs-5 urdu-regular" style="line-height:1.2">الدرجہ</span>
                                        <span class="urdu-regular fs-5 ms-3 fw-bold px-2" style="line-height:1.2">${student.darjaName}</span>
                                    </div>
                                </div>

                                <!-- Dates -->
                                <div class="d-flex justify-content-between align-items-center px-2 mb-3">
                                    <div class="d-flex align-items-center">
                                        <span class="fw-bold fs-5 urdu-regular px-2" style="line-height:1.2"> تاریخ تنسیخ</span>
                                        <span class="ltr font-monospace fs-5 ms-2 fw-bold" style="line-height:1.2">${student.dateEndFormatted}</span>
                                    </div>
                                    <div class="d-flex align-items-center">
                                        <span class="fw-bold fs-5 urdu-regular px-2" style="line-height:1.2"> تاریخ اجراء</span>
                                        <span class="ltr font-monospace fs-5 ms-2 fw-bold" style="line-height:1.2">${student.dateIssued}</span>
                                    </div>
                                </div>

                                <!-- English Footer Box -->
                                <div class="border border-primary bg-transparent text-center p-2 mb-1" style="border-width: 2px !important; border-color: #3b5998 !important;">
                                    <div class="fw-bold" style="color: #3b5998; font-size: 1rem; line-height: 1.3;">
                                        ${res.e_address}<br>
                                    </div>
                                </div>
                            </div>
                            
                        </div>
                    </div>
                </div>
                </div>
            `;
            container.append(cardHtml);
        });
    }

    $('#btnPrint').on('click', function () {
        window.print();
    });

});
