<x-admin.layout>
    <x-slot name="title">Renew Licensing Of Lodging Houses/लॉजिंग हाऊस परवान्याचे नूतनीकरण करणे</x-slot>
    <x-slot name="heading">Renew Licensing Of Lodging Houses/लॉजिंग हाऊस परवान्याचे नूतनीकरण करणे</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">Add Details</h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">
                            <div class="alert alert-warning fw-bold" role="alert">
                                प्राथमिक माहिती/Basic information
                            </div>
                            <div class="mb-3 row">
                                <div class="col-md-5" style="margin:center">
                                    <label class="col-form-label" for="license_no">
                                       License No /जुना परवाना क्र.<span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <input class="form-control" id="license_no" name="license_no" type="text" placeholder="search" required>
                                        <div class="input-group-append">
                                            <button class="btn btn-outline-secondary" type="button" id="searchShop">
                                                <i class="fas fa-search"></i> Search
                                            </button>
                                        </div>
                                    </div>                                     
                                </div>
                                  
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="shop_name">Shop Name in English/दुकानाचे नाव इंग्रजी<span class="text-danger">*</span></label>
                                <input class="form-control" id="shop_name" name="shop_name" type="text" placeholder="Enter Shop name in English" required>
                                <span class="text-danger is-invalid shop_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="marathi_shop_name">Shop Name in Marathi/दुकानाचे नाव मराठी<span class="text-danger">*</span></label>
                                <input class="form-control" id="marathi_shop_name" name="marathi_shop_name" type="text" placeholder="Enter Shop name in Marathi" required>
                                <span class="text-danger is-invalid marathi_shop_name_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="pencard_num">PAN card number/पॅन कार्ड क्रमांक<span class="text-danger">*</span></label>
                                <input class="form-control" id="pencard_num" name="pencard_num" type="text" maxlength="10" minlength="10" placeholder="Enter Pancard Number" required>
                                <span class="text-danger is-invalid pencard_num_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="mobile_num">संपर्क क्र./Contact No.<span class="text-danger">*</span></label>
                                <input class="form-control" id="mobile_num" name="mobile_num" type="text" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Mobile Number" required>
                                <span class="text-danger is-invalid mobile_num_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="e_mail">E-mail/ई-मेल</label>
                                <input class="form-control" id="e_mail" name="e_mail" type="email" placeholder="Enter Email">
                                <span class="text-danger is-invalid e_mail_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="address">Shop address/दुकानाचा पत्ता<span class="text-danger">*</span></label>
                                <textarea class="form-control" name="address" id="address" cols="30" rows="2" placeholder="Enter Shop Address" type="text" required></textarea>
                                <span class="text-danger is-invalid address_err"></span>
                            </div>


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



                            <div class="col-md-4">
                                <label class="col-form-label" for="financial_year">License Financial From Year/परवाना आर्थिक वर्षापासून</label>
                                <select class="form-control" id="financial_year" name="financial_year" required>
                                    <option value="">-- Select year --</option>
                                    @foreach (range(1980, 2060) as $year)
                                        <option value="{{ $year }}">{{ $year }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid financial_year_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="to_year"> To Year/पर्यंत वर्ष</label>
                                <select class="form-control" id="to_year" name="to_year" required>
                                    <option value="">-- Select year --</option>
                                    @foreach (range(1980, 2060) as $year)
                                        <option value="{{ $year }}">{{ $year }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid to_year_err"></span>
                            </div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="amount">Amount/रक्कम<span class="text-danger">*</span></label>
                                <input class="form-control" id="amount" name="amount" type="number" placeholder="Enter Amount" required>
                                <span class="text-danger is-invalid amount_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label">Is the item manufactured?/वस्तू निर्मित आहे का<span class="text-danger">*</span></label>
                                <div class="border rounded p-2">
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="manufactured" id="manufactured" value="होय" required>
                                        <label class="form-check-label" for="होय">होय</label>
                                    </div>

                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="manufactured" id="manufactured" value="नाही">
                                        <label class="form-check-label" for="नाही">नाही</label>
                                    </div>
                                     
                                </div>
                               <span class="text-danger is-invalid manufactured_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label">स्वतःच्या मालकीच्या जागेत व्यवसाय करीत आहे का/Are you conducting business on your own property?<span class="text-danger">*</span></label>
                                <div class="border rounded p-2">
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="business_premises" id="business_premises" value="होय" required>
                                        <label class="form-check-label" for="होय">होय</label>
                                    </div>

                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="business_premises" id="business_premises" value="नाही">
                                        <label class="form-check-label" for="नाही">नाही</label>
                                    </div>
                                   
                                </div>
                                 <span class="text-danger is-invalid business_premises_err"></span>
                            </div>

                            <div class="col-md-4">Name on the property ownership/जागा मालकीचे नाव
                                <label class="col-form-label" for="owner_place"><span class="text-danger">*</span></label>
                                <input class="form-control" id="owner_place" name="owner_place" type="text" placeholder="Enter place owner name" required>
                                <span class="text-danger is-invalid owner_place_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="address_owner_premises">Owner's address/जागा मालकाचा पत्ता<span class="text-danger">*</span></label>
                                <input class="form-control" id="address_owner_premises" name="address_owner_premises" type="text" placeholder="Enter place owner address" required>
                                <span class="text-danger is-invalid address_owner_premises_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="rental_agreement">With whom is the rental agreement made?/भाडे करार कोणासोबत केलेले आहे<span class="text-danger">*</span></label>
                                <input class="form-control" id="rental_agreement" name="rental_agreement" type="text" placeholder="Enter rental agreement" required>
                                <span class="text-danger is-invalid rental_agreement_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="area_used">Area of the space used in sq. ft./वापरात आलेले जागेचे क्षेत्र चौ. फु. मध्ये<span class="text-danger">*</span></label>
                                <input class="form-control" id="area_used" name="area_used" type="number" placeholder="Enter Area" required>
                                <span class="text-danger is-invalid area_used_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label">Have you obtained the non-objection certificate from the Municipal Corporation for business?/व्यवसायासाठी म. न. पा. चे नाहरकत प्रमाणपत्र घेतले आहे का<span class="text-danger">*</span></label>
                                <div class="border rounded p-2">
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="noc_certificate" id="noc_certificate" value="होय" required>
                                        <label class="form-check-label" for="होय">होय</label>
                                    </div>

                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="noc_certificate" id="noc_certificate" value="नाही">
                                        <label class="form-check-label" for="नाही">नाही</label>
                                    </div>

                                </div>
                                <span class="text-danger is-invalid noc_certificate_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="business_start">Year the business was started/व्यवसाय सुरु केल्याचे वर्ष<span class="text-danger">*</span></label>
                                <input class="form-control" id="business_start" name="business_start" type="number"  placeholder="Year of business start" required>
                                <span class="text-danger is-invalid business_start_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="registration_no">Shop Act Registration No./शॉप ऍक्ट नोंदणी क्र.<span class="text-danger">*</span></label>
                                <input class="form-control" id="registration_no" name="registration_no" type="number" placeholder="Enter Registration Number" required>
                                <span class="text-danger is-invalid registration_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="food_drug">Registration No. under the Food and Drug Administration Act/अन्न व औषध प्रशासन कायद्यान्वये नोंदणी क्र.<span class="text-danger">*</span></label>
                                <input class="form-control" id="food_drug" name="food_drug" type="text" placeholder="" required>
                                <span class="text-danger is-invalid food_drug_err"></span>
                            </div>
                        </div>

                        <div class="mb-3 row">

                            <div class="alert alert-warning fw-bold" role="alert">
                                संचालक माहिती/ Director information
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="aadhar_num">Director's aadhar number/संचालकांचा आधार क्रमांक<span class="">*</span></label>
                                <input class="form-control" id="aadhar_num" name="aadhar_num"type="text" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" placeholder="Enter Aadhar Card No" required>
                                <span class="text-danger is-invalid aadhar_num_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="director_name">Name of the Director/संचालकांचा नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="director_name" name="director_name" type="text" placeholder="Enter Director Name" required>
                                <span class="text-danger is-invalid director_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="contact_no">Contact No./संपर्क क्र.<span class="text-danger">*</span></label>
                                <input class="form-control" id="contact_no" name="contact_no" type="text" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter  Number" required>
                                <span class="text-danger is-invalid contact_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="alternet_email">E-mail./ई-मेल.<span class="text-danger">*</span></label>
                                <input class="form-control" id="alternet_email" name="alternet_email" type="email" placeholder="Enter Email" required>
                                <span class="text-danger is-invalid alternet_email_err"></span>
                            </div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="alternet_address">Address/पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="alternet_address" id="alternet_address" cols="30" rows="2" placeholder="Enter Address" required></textarea>
                                <span class="text-danger is-invalid alternet_address_err"></span>
                            </div>


                            <div class="col-md-4">
                                <label class="col-form-label">Gender/लिंग<span class="text-danger">*</span></label>
                                <div class="border rounded p-2">
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="gender" id="gender" value="स्त्री" required>
                                        <label class="form-check-label" for="स्त्री">स्त्री</label>
                                    </div>

                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="gender" id="gender" value="पुरुष">
                                        <label class="form-check-label" for="पुरुष">पुरुष</label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="gender" id="gender" value="ईतर">
                                        <label class="form-check-label" for="ईतर">ईतर</label>
                                    </div>
                                </div>
                                <span class="text-danger is-invalid gender_err"></span>
                            </div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="application_type">Applicant Type/अर्जदार प्रकार</label>
                                <select class="form-select" name="application_type" id="application_type">
                                    <option value="">Select Option</option>
                                    <option value="1">परितक्ता</option>
                                    <option value="2">प्रकल्पग्रस्त</option>
                                    <option value="3">पूरग्रस्त</option>
                                    <option value="4">अपंग</option>
                                    <option value="5">विधवा </option>
                                    <option value="6">सामान्य </option>
                                </select>
                                <span class="text-danger is-invalid application_type_err"></span>
                            </div>


                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="director_photos">Director's photo/संचालकाचां फोटो<span class="text-danger">*</span></label>
                                <input class="form-control" id="director_photos" name="director_photos" type="file" required>
                                <span class="text-danger is-invalid director_photos_err"></span>
                            </div>

                        </div>

                        <div class="mb-3 row">
                            <div class="alert alert-warning fw-bold" role="alert">
                                कागदपत्र जोडणे/Attaching documents
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_prescribed_formats">Other documents (Partner form_Rental agreement_Excise license)/इतर कागद पत्रे (भागीदार फॉर्म_भाडेकरारनामा_एक्साईट परवाना)<span class="text-danger">*</span></label>
                                <input class="form-control" id="upload_prescribed_formats" name="upload_prescribed_formats" type="file" required>
                                <span class="text-danger is-invalid upload_prescribed_formats_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="place">Fire Safety Certificate/अग्निशमन नाहरकत प्रमाणपत्र<span class="text-danger">*</span></label></label>
                                <input class="form-control" id="place" name="place" type="file" required>
                                <span class="text-danger is-invalid place_err"></span>
                            </div>


                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="ownership">Market license (at the time of renewal)/बाजार परवाना (नुतनिकरणावेळेस)</label>
                                <input class="form-control" id="ownership" name="ownership" type="file" required>
                                <span class="text-danger is-invalid ownership_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="water_bills">Registration certificate under the Food and Drugs Administration Act/अन्न व औषध प्रशासन कायद्यान्वये नोंदणी प्रत</label>
                                <input class="form-control" id="water_bill" name="water_bills" type="file" required>
                                <span class="text-danger is-invalid water_bills_err"></span>
                            </div>


                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="society">Shop Act/शॉप ऍक्ट<span class="text-danger">*</span></label>
                                <input class="form-control" id="society" name="society" type="file" required>
                                <span class="text-danger is-invalid society_err"></span>
                            </div>



                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="aadhar_pans">Director's PAN card (original copy)/संचालकांचे पॅन कार्ड (मुळ प्रत)<span class="text-danger">*</span></label>
                                <input class="form-control" id="aadhar_pans" name="aadhar_pans" type="file" required>
                                <span class="text-danger is-invalid aadhar_panss_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="property">Director's Aadhaar Card (Original)/संचालकांचे आधार कार्ड (मुळ प्रत)<span class="text-danger">*</span></label></label>
                                <input class="form-control" id="property" name="property" type="file" required>
                                <span class="text-danger is-invalid property_err"></span>
                            </div>


                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="tenancy">Income tax receipt for the current year/चालु वर्षाची कर पावती<span class="text-danger">*</span></label></label>
                                <input class="form-control" id="tenancy" name="tenancy" type="file" required>
                                <span class="text-danger is-invalid tenancy_err"></span>
                            </div>


                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="occupancy">Interior photos of the shop/दुकानाचे आतील फोटो<span class="text-danger">*</span></label></label>
                                <input class="form-control" id="occupancy" name="occupancy" type="file" required>
                                <span class="text-danger is-invalid occupancy_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="medical">Photo of the outside of the shop/दुकानाचे बाहेरील फोटो<span class="text-danger">*</span></label></label>
                                <input class="form-control" id="medical" name="medical" type="file" required>
                                <span class="text-danger is-invalid medical_err"></span>
                            </div>

                            <div class="col-md-4" id="upload_section" style="display:none;">
                                    <label class="col-form-label" for="prescribed_docs">Upload Application In
                                        Prescribed
                                        Format / विहित नमुन्यातील अर्ज अपलोड करा <span
                                            class="text-danger">*</span></label>
                                    <input class="form-control" id="prescribed_docs" name="prescribed_docs"
                                        type="file" required>
                                    <span class="text-danger is-invalid prescribed_docs_err"></span>
                                </div>

                            <label class="col-form-label" for="is_correct_info">Declaration / घोषणापत्र:</label>
                            <div class="col-md-12">
                                <div class="form-check d-flex align-items-start">
                                    <input type="checkbox" class="form-check-input mt-1" id="is_correct_info" name="is_correct_info" value="yes">
                                    <label class="form-check-label ms-2" for="is_correct_info">
                                        "All information provided above is correct and I shall be fully responsible for any discrepancy. <br> वरील पुरविलेली सर्व माहिती ही अचूक असून, त्यात कुठल्याही प्रकारची तफावत आढळल्यास त्यास मी पूर्णतः जबाबदार
                                        असेन."
                                    </label>
                                </div>
                                <span class="text-danger is-invalid is_correct_info_err"></span>
                            </div>

                        </div>
                    </div>
                    <div class="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-warning">Reset / पुन्हा भरा</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</x-admin.layout>

<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>
    $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('trade-renew-license-loading.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');
            },
        });

    });
</script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
    attachGlobalValidation('#addForm', '#saveAndPrintBtn', {
        containerId: 'addContainer',
        printTitle: 'Trade-renew-license',
    });
});
</script>
<script>
    document.addEventListener('DOMContentLoaded', () => {

    // --- Detect field type based on name/id/placeholder ---
    function detectFieldType(input) {
        const s = ((input.name || '') + ' ' + (input.id || '') + ' ' + (input.placeholder || '')).toLowerCase();
        if (/\baadhaar|\baadhar|\baadhar_no|\baadhar_num|\baadhar-number/.test(s)) return 'aadhar';
        if (/\bmobile|\bmobile_no|\bcontact|\bcontact_no|\bphone|\btelephone|\btel/.test(s)) return 'phone';
        if (/\bemail|\be-mail|\bmail|\balternet_email|\balternate_email|\bemail_id/.test(s)) return 'email';
        if (/\bpan|\bpancard|\bpan_no|\bpan_number/.test(s)) return 'pan';
        return null;
    }

    // --- Get associated 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, input) {
        if (type === 'aadhar') {
            if (input.type === 'file') {
                if (required && !input.files.length) return 'This field is required';
                return '';
            } else {
                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 === '') return 'Mobile number is required';
            if (value && !/^[6-9]\d{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 is required';
            if (value && !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(value.toUpperCase()))
                return 'Enter a valid PAN number (e.g., ABCDE1234F)';
            return '';
        }

        return '';
    }

    // --- Validate a single field ---
    function validateField(input) {
        const type = detectFieldType(input);
        const required = input.hasAttribute('required');
        const value = (input.value || '').trim();

        let err = '';
        if (type) {
            err = validateValueByType(value, type, required, input);
        } else if (required) {
            if (input.type === 'file' && !input.files.length) {
                err = 'This field is required';
            } else if (input.type !== 'checkbox' && input.type !== 'radio' && 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 radio button groups ---
    function validateRadioGroups(form) {
        let allValid = true;
        const radioGroups = {};

        // Group all radios by name
        form.querySelectorAll('input[type="radio"]').forEach(radio => {
            if (!radioGroups[radio.name]) radioGroups[radio.name] = [];
            radioGroups[radio.name].push(radio);
        });

        // Validate each group
        for (const groupName in radioGroups) {
            const radios = radioGroups[groupName];
            const errorSpan = document.querySelector(`.${groupName}_err`);
            const isRequired = radios.some(r => r.hasAttribute('required'));
            const isChecked = radios.some(r => r.checked);

            if (isRequired && !isChecked) {
                if (errorSpan) {
                    errorSpan.textContent = 'Please select an option';
                    errorSpan.style.display = 'block';
                }
                radios.forEach(r => r.classList.add('is-invalid'));
                allValid = false;
            } else {
                if (errorSpan) {
                    errorSpan.textContent = '';
                    errorSpan.style.display = 'none';
                }
                radios.forEach(r => r.classList.remove('is-invalid'));
            }
        }

        return allValid;
    }

    // --- Validate all visible fields (including checkbox & radio) ---
    function validateAllFields(form) {
        let allValid = true;
        const inputs = Array.from(form.querySelectorAll('input, textarea, select'));

        inputs.forEach(field => {
            if (field.offsetParent === null) return; // skip hidden fields

            // ✅ Special rule for checkbox (is_correct_info)
            if (field.type === 'checkbox' && (field.id === 'is_correct_info' || field.name === 'is_correct_info')) {
                const errorSpan = getErrorSpan(field);
                if (!field.checked) {
                    if (errorSpan) {
                        errorSpan.textContent = 'Please accept the declaration.';
                        errorSpan.style.display = 'block';
                    }
                    allValid = false;
                } else {
                    if (errorSpan) {
                        errorSpan.textContent = '';
                        errorSpan.style.display = 'none';
                    }
                }
                return;
            }

            // ✅ Normal validation for all other inputs (except radios)
            if (field.type !== 'radio' && !validateField(field)) allValid = false;
        });

        // ✅ Run radio validation separately
        if (!validateRadioGroups(form)) 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));

        // ✅ If checkbox is checked later, hide error immediately
        if (input.type === 'checkbox' && (input.id === 'is_correct_info' || input.name === 'is_correct_info')) {
            input.addEventListener('change', () => {
                const span = getErrorSpan(input);
                if (span && input.checked) {
                    span.textContent = '';
                    span.style.display = 'none';
                }
            });
        }
    });

    // Expose global function
    window.validateAllFields = validateAllFields;

});
</script>
<script>
document.getElementById('business_start').addEventListener('input', function () {
    // Allow only digits
    this.value = this.value.replace(/\D/g, '');

    // Limit to 4 digits
    if (this.value.length > 4) {
        this.value = this.value.slice(0, 4);
    }

});
</script>