<x-admin.layout>
    <x-slot name="title">NOC for Pandol/ Mandap / मंडपासाठी ना हरकत प्रमाणपत्र</x-slot>
    <x-slot name="heading">NOC for Pandol/ Mandap / मंडपासाठी ना हरकत प्रमाणपत्र </x-slot>

    <!-- Add Form -->
    <div class="row" id="addContainer">
        <div class="col-sm-12">
            <div class="card">
                <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                    @csrf

                    {{-- <div class="card-header">
                        <h4 class="card-title">Pandal Permission Application Form / मंडप परवानगी अर्ज</h4>
                    </div> --}}

                    <div class="card-body">
                        <div class="row g-3">

                            <!-- Applicant Info -->
                            <div class="col-12">
                                <h5 class="fw-bold">1. Applicant Details / अर्जदाराचा तपशील</h5>
                                <hr>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name">
                                    Applicant / Public Mandal / Organization Of Full Name & Designation<br>
                                    अर्जदाराचे / सार्वजनिक मंडळाचे / संस्थेचे पूर्ण नाव व पद <span class="text-danger">*</span>
                                </label>
                                <textarea class="form-control" id="applicant_name" name="applicant_name" rows="3" placeholder="Enter Full Name and Designation" required></textarea>
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_mobile">Applicant/Public Mandal/
                                    Organization Mobile No / अर्जदाराचे/सार्वजनिक मंडळाचे/संस्थेचा मोबाइल क्रमांक<span class="text-danger">*</span></label>
                                <input type="text" oninput="this.value = this.value.replace(/[^0-9]/g, '')"  class="form-control" id="applicant_mobile" name="applicant_mobile" placeholder="Enter Mobile Number" maxlength="10" required>
                                <span class="text-danger is-invalid applicant_mobile_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_email">Applicant/Public Mandal/
                                    Organization Email / अर्जदाराचा / सार्वजनिक मंडळाचा / संस्थेचा ई-मेल<span class="text-danger">*</span></label>
                                <input type="email" class="form-control" id="applicant_email" name="applicant_email" placeholder="Enter Email" required>
                                <span class="text-danger is-invalid applicant_email_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_address">Applicant/Public Mandal/
                                    Organization Address / अर्जदाराचा / सार्वजनिक मंडळाचा / संस्थेचा पत्ता<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="applicant_address" name="applicant_address" placeholder="Enter Address" required>
                                <span class="text-danger is-invalid applicant_address_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="ward_area">Prabhag Area / प्रभाग क्षेत्र<span class="text-danger">*</span></label>
                                <select class="form-select" id="ward_area" name="ward_area" required>
                                    <option value="">Select Prabhag Area</option>
                                    @foreach ($wards as $ward)
                                        <option value="{{ $ward->id }}">{{ $ward->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_err"></span>
                            </div>

                            <!-- Mandap Details -->
                            <div class="col-12 pt-3">
                                <h5 class="fw-bold">2. Pandal / Stage Details / मंडप तपशील</h5>
                                <hr>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="stage_address">
                                    Mandap / Stage Erection Place / मंडप उभारण्याचे ठिकाण
                                    <span class="text-danger">*</span>
                                </label>
                                <textarea class="form-control" name="stage_address" id="stage_address" rows="2" placeholder="Enter Stage Address" required></textarea>
                                <span class="text-danger is-invalid stage_address_err"></span>
                            </div>

                            <div class="col-md-8">
                                <label class="col-form-label" for="stage_permission_date">
                                    Pandal / Stage Duration (From - To) /
                                    मंडपाचा कालावधी (पासून - पर्यंत)
                                    <span class="text-danger">*</span>
                                </label>

                                <div class="row g-2">
                                    <div class="col-md-6">
                                        <input type="date" class="form-control" id="stage_permission_date" name="stage_permission_date" required>
                                        <span class="text-danger stage_permission_date_err small"></span>
                                    </div>

                                    <div class="col-md-6">
                                        <input type="date" class="form-control" id="stage_permission_end_date" name="stage_permission_end_date" required>
                                        <span class="text-danger stage_permission_end_date_err small"></span>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="stage_dimensions">
                                    Pandol Size (Length × Width × Height) / मंडपाचा आकार (लांबी × रुंदी × उंची)
                                    <span class="text-danger">*</span>
                                </label>
                                <input type="number" class="form-control" id="stage_height" name="stage_height" placeholder="Length × Width × Height" required>
                                <span class="text-danger is-invalid stage_height_err"></span>
                            </div>

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="concerned_local_police_station">
                                    Concerned Local Police Station Office / संबंधित स्थानिक पोलीस ठाणे कार्यालयाचा तपशील
                                    <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="concerned_traffic_police_station"
                                    name="concerned_traffic_police_station" required>
                                    <option value="">Select Option</option>
                                    <option value="जिल्हा वाहतूक नियंत्रण शाखा भाईंदर">जिल्हा वाहतूक नियंत्रण शाखा
                                        भाईंदर</option>
                                </select>
                                <span class="text-danger is-invalid concerned_traffic_police_station_err"></span>
                            </div> --}}


                            <div class="col-md-4">
                                <label class="col-form-label" for="concerned_local_police_station">
                                    Concerned m Local Police Station Office / संबंधित स्थानिक पोलीस ठाणे कार्यालयाचा
                                    तपशील
                                    <span class="text-danger">*</span>
                                </label>
                                <input type="text" class="form-control" id="concerned_traffic_police_station" name="concerned_traffic_police_station" placeholder="Enter Concerned Local Police Station Office" required>
                                <span class="text-danger is-invalid concerned_traffic_police_station_err"></span>
                            </div>

                            <!-- Registration Details -->
                            <div class="col-12 pt-3">
                                <h5 class="fw-bold">3. Registration Details / नोंदणी तपशील</h5>
                                <hr>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="commissioner_name">Name registered with the
                                    Hon. Charity Commissioner / मंडळाचे मा. धर्मादाय आयुक्तांकडील नोंदवलेले नाव
                                    <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="commissioner_name" name="commissioner_name" required>
                                <span class="text-danger is-invalid commissioner_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="registration_no">Registration Number from
                                    Hon. Charity Commissioner / मंडळाचा मा. धर्मादाय आयुक्तांकडील नोंदणी क्रमांक
                                    <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="registration_no" name="registration_no" required>
                                <span class="text-danger is-invalid registration_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="registration_date">
                                    Registration Date / नोंदणीची तारीख <span class="text-danger">*</span>
                                </label>
                                <input type="date" class="form-control" id="registration_date" name="registration_date" required>
                                <span class="text-danger is-invalid registration_date_err"></span>
                            </div>

                            <!-- Additional Questions -->
                            <div class="col-md-4">
                                <label class="col-form-label" for="last_year_permission">
                                    Was Pandal Permission granted last year? / मागील वर्षी मंडप उभारण्यासाठी परवानगी
                                    दिली होती का?
                                    <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="last_year_permission" name="last_year_permission" required>
                                    <option value="">Select Option</option>
                                    <option value="Yes">Yes / होय</option>
                                    <option value="No">No / नाही</option>
                                </select>
                                <span class="text-danger is-invalid last_year_permission_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="ganesh_murti_type">
                                    Ganesh Murti Details (Shadu Mati / POP) / गणेश मूर्तीचा तपशील (शाडू माती / पी. ओ.
                                    पी)
                                    <span class="text-danger">*</span>
                                </label>
                                <select class="form-select" id="ganesh_murti_type" name="ganesh_murti_type" required>
                                    <option value="">Select Type</option>
                                    <option value="Shadu Mati">Shadu Mati / शाडू माती</option>
                                    <option value="POP">POP / पी.ओ.पी</option>
                                </select>
                                <span class="text-danger is-invalid ganesh_murti_type_err"></span>
                            </div>

                            <div class="col-md-4" id="murti_height_div" style="display: none;">
                                <label for="murti_height" class="form-label">Murti Height (Feet) / मूर्तीची उंची <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="murti_height" name="murti_height" placeholder="Enter Height" required>
                                <span class="text-danger is-invalid murti_height_err"></span>
                            </div>

                            <!-- Uploads Section -->
                            <div class="col-12 pt-3">
                                <h5 class="fw-bold">4. Document Uploads / कागदपत्र अपलोड</h5>
                                <hr>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="location_map_documents">उभारवयाच्या मंडपाच्या ठिकाणाचा नकाशा<span class="text-danger">*</span></label>
                                <input class="form-control" id="location_map_documents" name="location_map_documents" type="file" required>
                                <span class="text-danger is-invalid location_map_documents_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="board_registration_documents">संस्था नोंदणी प्रमाणपत्र <span class="text-danger">*</span></label>
                                <input class="form-control" id="board_registration_documents" name="board_registration_documents" type="file" required>
                                <span class="text-danger is-invalid board_registration_documents_err"></span>
                            </div>



                            <div class="col-md-4" id="last_year_copy_div" style="display: none;">
                                <label class="col-form-label" for="mandap_documents">
                                    मागील वर्षी मंडप उभारणेस दिलेल्या परवानगीची प्रत
                                    <span class="text-danger">*</span>
                                </label>
                                <input class="form-control" id="mandap_documents" name="mandap_documents" type="file">
                                <span class="text-danger is-invalid mandap_documents_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="local_polic_documents">स्थानिक पोलीस ठाणे यांचेकडील ना-हरकत दाखला<span class="text-danger">*</span></label>
                                <input class="form-control" id="local_polic_documents" name="local_polic_documents" type="file" required>
                                <span class="text-danger is-invalid local_polic_documents_err"></span>
                            </div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="traffic_last_year_noObjection_document">वाहतूक पोलीस ठाणे यांचेकडील ना-हरकत दाखला</label>
                                <input class="form-control" id="traffic_last_year_noObjection_document" name="traffic_last_year_noObjection_documents" type="file" required>
                                <span class="text-danger is-invalid traffic_last_year_noObjection_document_err"></span>
                            </div>



                            <div class="col-md-4">
                                <label class="col-form-label" for="fire_last_year_noObjection_documents">महापालिकेचे अग्निशमन दलाचा ना-हरकत दाखला</label>
                                <input class="form-control" id="fire_last_year_noObjection_documents" name="fire_last_year_noObjection_documents" type="file" required>
                                <span class="text-danger is-invalid fire_last_year_noObjection_documents_err"></span>
                            </div>

                            <div class="col-md-6" id="upload_section" style="display:none;">
                                <label class="col-form-label" for="prescribed_doc">Upload Application In Prescribed <span class="text-danger">*</span></label>
                                <input class="form-control" id="prescribed_doc" name="prescribed_docs" type="file" placeholder="Enter Document No. / दस्तऐवज क्रमांक भरा">
                                <span class="text-danger is-invalid prescribed_doc_err"></span>
                            </div>
                        </div>


                        <!-- Declaration -->
                        <div class="col-md-12 pt-3">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="is_correct_info" name="is_correct_info" value="yes" required>
                                <label class="form-check-label ms-2" for="is_correct_info">
                                    All information provided above is correct... / वरील सर्व माहिती अचूक आहे...
                                </label>
                                <span class="text-danger is-invalid is_correct_info_err"></span>
                            </div>
                        </div>

                    </div>

                    <div class="card-footer form-group" style="text-align: center;">
                        <button type="button" id="saveAndPrintBtn" class="btn btn-success">Save and Print</button>
                    </div>
                    <div class="card-footer" id="card-footer" style="display:none;">
                        <button type="submit" class="btn btn-primary" id="addSubmit">Submit / सबमिट करा</button>
                        <button type="reset" class="btn btn-secondary">Reset / रीसेट</button>
                    </div>
            </form>
        </div>
    </div>
    </div>
</x-admin.layout>




{{-- Add --}}
<script>
    $("#addForm").submit(function(e) {
        e.preventDefault();
        const fileField = document.getElementById('prescribed_doc');
        if (!fileField || fileField.files.length === 0) {
            // $('.prescribed_formats_err').text("Please upload application in prescribed format.");
            $('.prescribed_doc_err').text("This field is required");
            return false;
        }
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('trade-noc-mandap.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $('#preloader').css('opacity', '0.5');
                $('#preloader').css('visibility', 'visible');
            },
            success: function(data) {
                $("#addSubmit").prop('disabled', false);
                if (!data.error)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        window.location.href = '{{ route('my-application') }}';
                    });
                else
                    swal("Error!", data.error, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            },
        });

    });
    document.addEventListener('DOMContentLoaded', function() {
        const permissionSelect = document.getElementById('last_year_permission');
        const fileDiv = document.getElementById('last_year_copy_div');
        const fileInput = document.getElementById('mandap_documents');

        function toggleMandapDocuments() {
            const permission = permissionSelect.value;

            if (permission.toLowerCase() === 'yes') {
                fileDiv.style.display = 'block';
                fileInput.setAttribute('required', 'required');
            } else {
                fileDiv.style.display = 'none';
                fileInput.removeAttribute('required');
                fileInput.value = ''; // Clear the file input
            }
        }

        // Initial check (in case of edit form)
        toggleMandapDocuments();

        // On change
        permissionSelect.addEventListener('change', toggleMandapDocuments);
    });
</script>
<script>
    $('#ganesh_murti_type').on('change', function() {
        var selected = $(this).val();
        if (selected === 'Shadu Mati' || selected === 'POP') {
            $('#murti_height_div').show();
        } else {
            $('#murti_height_div').hide();
            $('#murti_height').val(''); // Optional: Clear value
        }
    });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>


<script>
    function generatePDF1() {

        document.getElementById('card-footer').style.display = 'block';
        const addContainer = document.getElementById('addContainer');
        const printContainerClone = addContainer.cloneNode(true);

        printContainerClone.style.fontSize = '16px';
        printContainerClone.style.lineHeight = '1.4';
        printContainerClone.style.padding = '20px';
        printContainerClone.style.margin = '0 auto';
        printContainerClone.style.background = '#fff';
        printContainerClone.style.width = '210mm';
        printContainerClone.style.minHeight = '297mm';
        printContainerClone.style.boxSizing = 'border-box';

        Array.from(printContainerClone.querySelectorAll('*')).forEach(el => {
            el.style.fontSize = '16px';
            el.style.margin = '4px 0';
        });

        const printTitle = document.createElement('h2');
        printTitle.style.textAlign = 'center';
        printTitle.style.marginBottom = '18px';
        printTitle.style.fontSize = '18px';
        printTitle.textContent = 'NOC for Pandol/ Mandap';
        printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);

        Array.from(printContainerClone.querySelectorAll('button')).forEach(btn => btn.remove());
        Array.from(printContainerClone.querySelectorAll('.card')).forEach(card => {
            card.style.background = 'white';
            card.style.boxShadow = 'none';
            card.style.border = '1px solid #ccc';
            card.style.marginBottom = '12px';
            card.style.padding = '12px';
        });

        Array.from(printContainerClone.querySelectorAll('input[type="checkbox"]')).forEach(checkbox => {
            const info = document.createElement('span');
            info.style.display = 'inline-block';
            info.style.width = '20px';
            info.style.height = '20px';
            info.style.marginRight = '8px';
            info.style.border = '1px solid #000';
            info.style.textAlign = 'center';
            info.style.lineHeight = '18px';
            info.style.fontSize = '16px';
            info.style.verticalAlign = 'middle';
            info.textContent = checkbox.checked ? '✔' : '';
            const label = checkbox.nextElementSibling;
            if (label) {
                label.prepend(info);
            }
            checkbox.style.display = 'none';
        });

        Array.from(printContainerClone.querySelectorAll('select')).forEach(select => {
            const originalSelect = document.getElementById(select.id);
            let selectedText = '';
            if (originalSelect) {
                if (originalSelect.multiple) {
                    selectedText = Array.from(originalSelect.selectedOptions).map(opt => opt.text).join(', ');
                } else {
                    selectedText = originalSelect.options[originalSelect.selectedIndex].text;
                }
            }
            const span = document.createElement('span');
            span.textContent = selectedText || '-';
            span.style.display = 'inline-block';
            span.style.minWidth = '150px';
            span.style.padding = '12px';
            span.style.border = '1px solid #ccc';
            span.style.borderRadius = '4px';
            span.style.backgroundColor = '#f9f9f9';
            select.parentNode.replaceChild(span, select);
        });

        let printContainer = document.getElementById('printContainer');
        if (!printContainer) {
            printContainer = document.createElement('div');
            printContainer.id = 'printContainer';
            printContainer.style.position = 'fixed';
            printContainer.style.left = '-9999px';
            document.body.appendChild(printContainer);
        }
        printContainer.innerHTML = '';
        printContainer.appendChild(printContainerClone);

        const prescribedInput = printContainerClone.querySelector('#uploaded_applications');
        if (prescribedInput) {
            prescribedInput.closest('.col-md-4').style.display = 'none';
        }

        html2canvas(printContainerClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1,
            useCORS: true,
            allowTaint: true
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            const {
                jsPDF
            } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const pageWidth = pdf.internal.pageSize.getWidth();
            const pageHeight = pdf.internal.pageSize.getHeight();
            const margin = 10;
            const pdfWidth = pageWidth - margin * 2;
            const pdfHeight = pageHeight - margin * 2;
            pdf.addImage(imgData, 'JPEG', margin, margin, pdfWidth, pdfHeight);

            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content or try again.');
            }

            pdf.save('NOC_for_Pandol_Mandap.pdf');
            document.getElementById('upload_section').style.display = 'block';
            document.getElementById('saveAndPrintBtn').style.display = 'none';
        });
    }
    // document.getElementById('saveAndPrintBtn').addEventListener('click', function() {
    //     const form = document.getElementById('addForm'); // your form ID

    //     // ✅ First, check if the form is valid
    //     if (!form.checkValidity()) {
    //         form.reportValidity();
    //         return; // stop execution if invalid
    //     }

    //     generatePDF1();
    // });

    function updateSelectedValue(selectId) {
        var select = document.getElementById(selectId);
        var selectedText = select.options[select.selectedIndex] ? select.options[select.selectedIndex].text : '';
        var selectedDiv = document.getElementById(selectId + '_selected');
        if (!selectedDiv) {
            selectedDiv = document.createElement('div');
            selectedDiv.id = selectId + '_selected';
            selectedDiv.className = 'selected-value';
            select.parentNode.appendChild(selectedDiv);
        }
        selectedDiv.textContent = 'Selected: ' + selectedText;
        selectedDiv.classList.remove('d-none');
    }

    document.getElementById('authorization').addEventListener('change', function() {
        updateSelectedValue('authorization');
    });
    updateSelectedValue('authorization');
</script>


<!--validation script-->
<!--applicant name script-->
<script></script>
<!--mobile no validation-->
<script></script>
<!--email validation-->
<script></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {

        // --- Detect field type for validation ---
        function detectFieldType(input) {
            const s = ((input.name || '') + ' ' + (input.id || '') + ' ' + (input.placeholder || '')).toLowerCase();

            if (/application_name|property_owner_name|f_name|middle_name|m_name|last_name|l_name/.test(s)) return 'name';
            if (/adhaarno|aadhaar|aadhar_no|aadhar_num|aadhar-number/.test(s)) return 'aadhar';
            if (/mobile|mobile_no|applicant_mobile|contact|contact_no|phone|telephone|tel/.test(s)) return 'phone';
            if (/email|e-mail|mail|alternate_email|email_id/.test(s)) return 'email';
            if (/pan|pancard|pan_no|pan_number/.test(s)) return 'pan';
            if (/pincode|pin_code|postal|zip|post_code|area_code/.test(s)) return 'pincode';
            if(/murti_height/.test(s)) return 'murti_height';
            return null;
        }

        // --- Get error span ---
        function getErrorSpan(input) {
            if (input.name) {
                const spanByName = document.querySelector(`.${input.name}_err`);
                if (spanByName) return spanByName;
            }
            if (input.id) {
                const spanById = document.querySelector(`.${input.id}_err`);
                if (spanById) return spanById;
            }
            return input.closest('div')?.querySelector('span.text-danger') || null;
        }

        // --- Validation rules ---
        function validateValueByType(value, type, required) {
            if (type === 'name') {
                if (required && value === '') return 'This field is required';
                if (value && !/^[A-Za-z\s]+$/.test(value)) return 'Only letters and spaces are allowed';
                return '';
            }
            if (type === 'aadhar') {
                if (required && value === '') return 'Aadhaar number is required';
                if (value && !/^\d{12}$/.test(value)) return 'Enter a valid 12-digit Aadhaar number';
                return '';
            }
           if (type === 'phone') {
                    if (required && value.trim() === '')
                        return 'Mobile number is required';

                    if (value && !/^[6-9][0-9]{9}$/.test(value))
                        return 'Enter a valid 10-digit mobile number';

                    return '';
                }
            if (type === 'email') {
                if (required && value === '') return 'Email is required';
                if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Enter a valid email address';
                return '';
            }
            if (type === 'pan') {
                if (required && value === '') return 'This field is required';
                if (value && !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(value.toUpperCase())) return 'Enter a valid PAN number';
                return '';
            }
            if (type === 'pincode') {
                if (required && value === '') return 'PIN code is required';
                if (value && !/^\d{6}$/.test(value)) return 'Enter a valid 6-digit PIN code';
                return '';
            }
            if (type === 'murti_height') {
                if (required && value === '') return 'This is required';

            }


            return '';
        }

        // --- Validate field ---
        function validateField(input) {
            // File validation
            if (input.type === "file") {
                const file = input.files[0];
                const span = getErrorSpan(input);
                if (file) {
                    if (file.size > 2 * 1024 * 1024) {
                        if (span) {
                            span.textContent = `File must be less than 2MB.`;
                            span.style.display = "block";
                        }
                        input.classList.add("is-invalid");
                        input.setAttribute("aria-invalid", "true");
                        return false;
                    } else {
                        if (span) {
                            span.textContent = "";
                            span.style.display = "none";
                        }
                        input.classList.remove("is-invalid");
                        input.removeAttribute("aria-invalid");
                        return true;
                    }
                } else if (input.hasAttribute('required')) {
                    if (span) {
                        span.textContent = "This file is required";
                        span.style.display = "block";
                    }
                    input.classList.add("is-invalid");
                    input.setAttribute("aria-invalid", "true");
                    return false;
                }
                return true;
            }

            // Checkbox validation
            if (input.type === 'checkbox' && (input.id === 'is_correct_info' || input.name === 'is_correct_info')) {
                const span = getErrorSpan(input);
                if (!input.checked) {
                    if (span) {
                        span.textContent = 'Please accept the declaration.';
                        span.style.display = 'block';
                    }
                    input.classList.add('is-invalid');
                    return false;
                } else {
                    if (span) {
                        span.textContent = '';
                        span.style.display = 'none';
                    }
                    input.classList.remove('is-invalid');
                    input.removeAttribute('aria-invalid');
                    return true;
                }
            }

            //Aadhaar live restriction (only numbers)
            const type = detectFieldType(input);
            if (type === 'adhaarno') {
                input.value = input.value.replace(/\D/g, ''); // only digits
                if (input.value.length > 12) input.value = input.value.slice(0, 12); // max 12 digits
            }

            if (input.id === 'stage_permission_end_date' || input.id === 'stage_permission_date') {
                const startDate = document.getElementById('stage_permission_date');
                const endDate = document.getElementById('stage_permission_end_date');
                const startSpan = getErrorSpan(startDate);
                const endSpan = getErrorSpan(endDate);

                if (startDate.value && endDate.value) {
                    const start = new Date(startDate.value);
                    const end = new Date(endDate.value);

                    if (end < start) {
                        if (endSpan) {
                            endSpan.textContent = "End date must be greater than or equal to start date.";
                            endSpan.style.display = "block";
                        }
                        endDate.classList.add("is-invalid");
                        endDate.setAttribute("aria-invalid", "true");
                        return false;
                    } else {
                        if (startSpan) startSpan.textContent = "";
                        if (endSpan) endSpan.textContent = "";
                        startDate.classList.remove("is-invalid");
                        endDate.classList.remove("is-invalid");
                    }
                }
            }

            // General field validation
            const value = (input.value || '').trim();
            const required = input.hasAttribute('required');

            let err = '';
            if (type) err = validateValueByType(value, type, required);
            else if (required && value === '') err = 'This field is required';

            const span = getErrorSpan(input);
            if (span) {
                span.textContent = err;
                span.style.display = err ? 'block' : 'none';
            }

            if (err) {
                input.classList.add('is-invalid');
                input.setAttribute('aria-invalid', 'true');
            } else {
                input.classList.remove('is-invalid');
                input.removeAttribute('aria-invalid');
            }

            return !err;
        }

        // --- Validate all fields ---
        function validateAllFields(form) {
            let allValid = true;
            const inputs = Array.from(form.querySelectorAll('input, textarea, select'));
            inputs.forEach(input => {
                if (input.offsetParent === null) return; // skip hidden
                if (!validateField(input)) allValid = false;
            });
            return allValid;
        }

        // --- Attach input/blur events ---
        const allInputs = Array.from(document.querySelectorAll('input, textarea, select'));
        allInputs.forEach(input => {
            input.addEventListener('input', () => validateField(input));
            input.addEventListener('blur', () => validateField(input));
        });



        window.validateAllFields = validateAllFields;

        // --- Save & Print button ---
        const btn = document.getElementById('saveAndPrintBtn');
        if (btn) {
            btn.addEventListener('click', () => {
                const form = document.getElementById('addForm');
                if (!validateAllFields(form)) return; // stop submit if invalid

                document.getElementById('card-footer').style.display = 'block';
                 generatePDF1();
            });
        }

    });
</script>
