<x-admin.layout>
    <x-slot name="title">Providing drainage connections. / मलनि:सारण जोडणी करणे.  </x-slot>
    <x-slot name="heading">Providing drainage connections. / मलनि:सारण जोडणी करणे.  </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">
                        <div class="card-body">

                            <div class="card-header">
                                <h4 class="card-title">Applicant Details</h4>
                            </div>
                            <div class="mb-3 row">
                                <div class="col-md-4">
                                    <label class="col-form-label" for="applicant_name">Applicant Full Name / अर्जदाराचे पूर्ण नाव<span class="text-danger">*</span></label>
                                    <input class="form-control" id="applicant_name" name="applicant_name" type="text" value="{{ $user->name }}" placeholder="Enter Applicant Name" required readonly>
                                    <span class="text-danger is-invalid applicant_name_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="address">Applicant Full Address / अर्जदाराचा पूर्ण पत्ता <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="address" name="address" type="text" placeholder="Enter Name Of New Owner" required readonly>{{ $user->address }} </textarea>
                                    <span class="text-danger is-invalid address_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="mobile_no">Applicant Mobile No / मोबाईल नंबर<span class="text-danger">*</span></label>
                                    <input class="form-control" id="mobile_no" name="mobile_no" value="{{ $user->mobile }}" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" type="text"
                                        placeholder="Enter Mobile Number" required readonly>
                                    <span class="text-danger is-invalid mobile_no_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="email_id"> Applicant EmailID / ईमेल आयडी<span class="text-danger">*</span></label>
                                    <input class="form-control" id="email_id" name="email_id" type="email" placeholder="Enter Email" value="{{ $user->email }}" required readonly>
                                    <span class="text-danger is-invalid email_id_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="aadhar_no">Applicant Adhaar No / आधार क्रमांक <span class="text-danger">*</span></label>
                                    <input class="form-control" id="aadhar_no" name="aadhar_no" value='{{ $user->aadhar_no }}' oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" type="text"
                                        placeholder="Enter Aadhar Card No" required readonly>
                                    <span class="text-danger is-invalid aadhar_no_err"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- <div class="card">
                        <div class="card-body">
                            <div class="col-md-4">
                                <input class="form-control" id="marchantid" name="marchantid" type="hidden" value="MBMCCORE">
                                <span class="text-danger is-invalid marchantid_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="connection_no">Connection No<span class="text-danger">*</span></label>
                                <input class="form-control" id="connection_no" name="connection_no" type="text" placeholder="Enter Connection No">
                                <span class="text-danger is-invalid connection_no_err"></span>
                            </div>

                            <button type="Search" class="btn btn-primary mt-2  w-25" id="searchdetails">Search</button>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title">Water Details</h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-3 row">
                                <div class="col-md-4">
                                    <label class="col-form-label" for="Property_Owner_Name">Owner Name/मालकाचे नाव<span class="text-danger">*</span></label>
                                    <input class="form-control" id="Property_Owner_Name" name="Property_Owner_Name" type="text" placeholder="Enter Owner Name" required readonly>
                                    <span class="text-danger is-invalid Property_Owner_Name_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Full_Address_Of_The_Property"> Owner Address/मालकाचा पत्ता<span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="Full_Address_Of_The_Property" id="Full_Address_Of_The_Property" cols="30" rows="2" placeholder="Enter  Address" required readonly></textarea>
                                    <span class="text-danger is-invalid Full_Address_Of_The_Property_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Ward">Ward Area / प्रभाग क्षेत्र<span class="text-danger">*</span></label>
                                    <input class="form-control" name="Ward" id="Ward" placeholder="Enter Ward Area" required readonly>
                                    <span class="text-danger is-invalid Ward_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="zone">Zone / झोन<span class="text-danger">*</span></label>
                                    <input class="form-control" name="zone" id="zone" placeholder="Enter Zone" required readonly>
                                    <span class="text-danger is-invalid zone_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Water_Connection_Size">Water Connection Size<span class="text-danger">*</span></label>
                                    <input class="form-control" id="Water_Connection_Size" name="Water_Connection_Size" type="text" placeholder="Enter Water Connection Size" required readonly>
                                    <span class="text-danger is-invalid Water_Connection_Size_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Connection_Type">Connection Type<span class="text-danger">*</span></label>
                                    <input class="form-control" name="Connection_Type" id="Connection_Type" type="text" placeholder="Enter Connection Type" required readonly>
                                    <span class="text-danger is-invalid Connection_Type_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Water_Connection_Usage">Water Connection Usage <span class="text-danger">*</span></label>
                                    <input class="form-control" id="Water_Connection_Usage" name="Water_Connection_Usage" type="text" placeholder="Enter Water Connection Usage" required readonly>
                                    <span class="text-danger is-invalid Water_Connection_Usage_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="OutstandingAmt"> Total Outstanding Payable/ एकूण थकबाकी बिल भरले?<span class="text-danger">*</span></label>
                                    <input class="form-control" id="OutstandingAmt" name="OutstandingAmt" type="text" required readonly>
                                    <span class="text-danger is-invalid OutstandingAmt_err"></span>
                                </div>
                                <div class="col-md-4 mt-4">
                                    <button type="button" id="payaccentech" class="btn btn-success" target="_blank"
                                        onclick="window.location.href='https://watertax.nagarkaryavali.com/FrmWTConnSearch.aspx?@=AD65C7423AEA4530E3CB0528C8EFFFE4185BBCFBFA074578B362FC23AB6A7765'">Pay</button>
                                </div>

                            </div>
                        </div>
                    </div> --}}

                    {{-- <div class="card-header">
                        <h4 class="card-title">Add Providing drainage connections / जल निसारण जोडणी देणे </h4>
                    </div> --}}
                    <div class="card-body">
                        <div class="mb-3 row">
                            {{-- <div class="col-md-12 mt-3">
                                <div class="alert alert-info d-flex align-items-center" role="alert" style="font-weight: bold;">
                                    <i class="fa fa-info-circle me-2" style="font-size: 1.5rem;"></i>
                                    <span>Applicant Details / अर्जदाराची माहिती</span>
                                </div>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_name">Applicant's Full Name / अर्जदाराचे संपूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_name" name="applicant_name" pattern="^[A-Za-zअ-हऀ-ॿ\s]+$" title="Only letters and spaces are allowed. No numbers or special characters."
                                    onkeypress="return isLetterOrSpace(event)" type="text" placeholder="Enter Applicant Name">
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_full_address">Applicant's Full Address / अर्जदाराचा संपूर्ण पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="applicant_full_address" id="applicant_full_address" cols="30" rows="2" placeholder="Enter Applicant Address"></textarea>
                                <span class="text-danger is-invalid applicant_full_address_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="mobile_no">Mobile Number / मोबाईल नं.<span class="text-danger">*</span></label>
                                <input class="form-control" id="mobile_no" name="mobile_no" maxlength="10" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);" type="number" placeholder="Enter Mobile Number">
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="email_id">Email ID / ई-मेल आयडी<span class="text-danger">*</span></label>
                                <input class="form-control" id="email_id" name="email_id" type="email" placeholder="Enter Email">
                                <span class="text-danger is-invalid email_id_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="aadhar_no">Aadhar Number / आधार क्रमांक <span class="text-danger">*</span></label>
                                <input class="form-control" id="aadhar_no" name="aadhar_no" onkeypress="return isNumberKey(event)" oninput="limitAadharLength(this)" type="number" placeholder="Enter Aadhar Card No">
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div> --}}

                            <div class="col-md-12 mt-3">
                                <div class="alert alert-info d-flex align-items-center" role="alert" style="font-weight: bold;">
                                    <i class="fa fa-info-circle me-2" style="font-size: 1.5rem;"></i>
                                    <span>Connection Details/ कनेक्शन तपशील</span>
                                </div>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="connection_count">Required Connection Count / आवश्यक कनेक्शन संख्या <span class="text-danger">*</span></label>
                                <input class="form-control" id="connection_count" name="connection_count" type="text" placeholder="Enter required connection count">
                                <span class="text-danger is-invalid connection_count_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="zone"> Ward Area / प्रभाग क्षेत्र <span class="text-danger">*</span></label>
                                <input class="form-control" id="zone" name="zone" type="text" placeholder="Enter ward no" >
                                <span class="text-danger is-invalid zone_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="property_number">Property Number / मालमत्ता क्र<span class="text-danger">*</span></label>
                                <input class="form-control" id="property_number" name="property_number" type="text" placeholder="Enter Property Number" >
                                <span class="text-danger is-invalid property_number_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="property_usage">Property usage / मालमत्तेचा वापर</label>
                                <input class="form-control" id="property_usage" name="property_usage" type="text" placeholder="Enter Property Number">
                                <span class="text-danger is-invalid property_usage_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="is_toilet_available">Is Toilet Available / शौचालय उपलब्ध आहे का?<span class="text-danger">*</span></label>
                                <select name="is_toilet_available" id="is_toilet_available" class="form-select">
                                    <option value="">Select Option</option>
                                    @php
                                        $options = ['Yes', 'No'];
                                    @endphp
                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid is_toilet_available_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="lichpit_count">Enter Septic Lichpit Count/ सेप्टिक लिचपिट संख्या <span class="text-danger">*</span></label>
                                <input class="form-control" id="lichpit_count" name="lichpit_count" type="number" placeholder="Enter Septic Lichpit Count" >
                                <span class="text-danger is-invalid lichpit_count_err"></span>
                            </div>

                            {{-- <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="total_residencial_people_count">Connection No/ कनेक्शन क्रमांक <span class="text-danger">*</span></label>
                                <input class="form-control" id="total_residencial_people_count" name="total_residencial_people_count" type="number" placeholder="Enter Total Residencial People Count">
                                <span class="text-danger is-invalid total_residencial_people_count_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="connection_size_inches">Owner Full Name/मालकाचे पूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="connection_size_inches" name="connection_size_inches" pattern="^[A-Za-zअ-हऀ-ॿ\s]+$" title="Only letters and spaces are allowed. No numbers or special characters."
                                    onkeypress="return isLetterOrSpace(event)" type="text" placeholder="Enter Owner Name">
                                <span class="text-danger is-invalid connection_size_inches_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="property_usage">Owner Full Address/ मालकाचा पूर्ण पत्ता<span class="text-danger">*</span></label>
                                <textarea class="form-control" name="property_usage" id="property_usage" cols="30" rows="2" placeholder="Enter Owner Address"></textarea>
                                <span class="text-danger is-invalid property_usage_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="current_water_tax_amount">Survey No./House No./ सर्व्हे क्रमांक/घर क्रमांक. <span class="text-danger">*</span></label>
                                <input class="form-control" id="current_water_tax_amount" name="current_water_tax_amount" type="number" placeholder="Enter Current Water Tax Amount">
                                <span class="text-danger is-invalid current_water_tax_amount_err"></span>
                            </div>


                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_area_details">Land Mark/ लँडमार्क <span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_area_details" name="applicant_area_details" type="text" placeholder="Enter Applicant Area">
                                <span class="text-danger is-invalid applicant_area_details_err"></span>
                            </div> --}}



                            {{-- <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="zone">Zone <span class="text-danger">*</span></label>
                                    <select name="zone" id="zone" class="form-select">
                                        <option value="">Select Zone</option>
                                        @php
                                            $options = ["Prabhag1", "Prabhag2", "Prabhag3", "Prabhag4", "Prabhag5", "Prabhag6"];
                                        @endphp
                                        @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid zone_err"></span>
                                </div> --}}

                            {{-- <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="ward">Ward <span class="text-danger">*</span></label>
                                    <select name="ward" id="ward" class="form-select">
                                        <option value="">Select Ward</option>
                                        @php
                                            $options = ["Ward1", "Ward2", "Ward3", "Ward4", "Ward5", "Ward6"];
                                        @endphp
                                        @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid ward_err"></span>
                                </div> --}}

                            {{-- <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_prescribed_formats">Upload Application in the prescribed format / विहित नमुन्यातील अर्ज अपलोड करा<span class="text-danger">*</span></label>
                                <input class="form-control" id="upload_prescribed_formats" name="upload_prescribed_formats" type="file">
                                <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="oc_cc_docs">Upload OC Document / दस्तऐवज OC अपलोड करा<span class="text-danger">*</span></label>
                                <input class="form-control" id="oc_cc_docs" name="oc_cc_docs" type="file" >
                                <span class="text-danger is-invalid oc_cc_docs_err"></span>
                            </div>


                            {{--





                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="construction_date">Construction Date / बांधकाम दिनांक <span class="text-danger">*</span></label>
                                    <input class="form-control" id="construction_date" name="construction_date" type="date" placeholder="Select Construction Date">
                                    <span class="text-danger is-invalid construction_date_err"></span>
                                </div>

                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="flat_assesment_date">Hous or flat Assesment Date / घर किंवा सदनिकेची कर आकारणी दिनांक <span class="text-danger">*</span></label>
                                    <input class="form-control" id="flat_assesment_date" name="flat_assesment_date" type="date" placeholder="Select Flat Assesment Date">
                                    <span class="text-danger is-invalid flat_assesment_date_err"></span>
                                </div>



                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="current_tax_paid_date">Current Tax paid date / चालू कर रक्कम भरणा दिनांक <span class="text-danger">*</span></label>
                                    <input class="form-control" id="current_tax_paid_date" name="current_tax_paid_date" type="date" placeholder="Select Current Tax Paid Date">
                                    <span class="text-danger is-invalid current_tax_paid_date_err"></span>
                                </div>



                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="total_renter_count">Total Renter count if any? / भाडेकरू असल्यास त्यांची एकूण संख्या <span class="text-danger">*</span></label>
                                    <input class="form-control" id="total_renter_count" name="total_renter_count" type="number" placeholder="Enter Total Renter count">
                                    <span class="text-danger is-invalid total_renter_count_err"></span>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="connection_size_feet">Connection Size In Feet / जोडणी आकार फुटा मध्ये <span class="text-danger">*</span></label>
                                    <input class="form-control" id="connection_size_feet" name="connection_size_feet" type="number" placeholder="Enter Connection Size In Feet">
                                    <span class="text-danger is-invalid connection_size_feet_err"></span>
                                </div>



                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="upload_no_dues_certificates">Upload Tax No Dues Certificate / थकबाकी नसल्याचा दाखला अपलोड करा <span class="text-danger">*</span></label>
                                    <input class="form-control" id="upload_no_dues_certificates" name="upload_no_dues_certificates" type="file">
                                    <span class="text-danger is-invalid upload_no_dues_certificates_err"></span>
                                </div>

                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="upload_property_ownerships">Upload Documents of Property Ownership / जागा मालकीचे कागदपत्रे अपलोड करा <span class="text-danger">*</span></label>
                                    <input class="form-control" id="upload_property_ownerships" name="upload_property_ownerships" type="file">
                                    <span class="text-danger is-invalid upload_property_ownerships_err"></span>
                                </div> --}}

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

                            <label class="col-form-label" for="is_correct_info">Declaration / घोषणापत्र <span class="text-danger">*</span></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" required>
                                    <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>
    $('#searchdetails').on('click', function(e) {
        e.preventDefault();

        let formData = {
            marchantid: $('#marchantid').val(),
            connection_no: $('#connection_no').val(),
            _token: $('input[name="_token"]').val()
        };

        $.ajax({
            url: '{{ route('fetch.water.details') }}',
            method: 'POST',
            data: formData,
            datatype: JSON,
            success: function(response) {
                console.log("Encrypted Data:", response.jsonData.encr_request);

                const decryptedData = JSON.parse(response.jsonData.encr_request);


                if (decryptedData && decryptedData['connectionDetails']) {
                    // $('#water_connection_no').val(decryptedData['connectionDetails'].Water_Connection_Number);
                    $('#Connection_Type').val(decryptedData['connectionDetails'].Connection_Type);
                    $('#House_Number').val(decryptedData['connectionDetails'].House_Number);
                    $('#Property_Owner_Name').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    $('#Full_Address_Of_The_Property').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    $('#Water_Connection_Size').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    $('#Water_Connection_Usage').val(decryptedData['connectionDetails'].Water_Connection_Usage);
                    $('#zone').val(decryptedData['connectionDetails'].Zone);
                    $('#Ward').val(decryptedData['connectionDetails'].Ward);
                    $('#OutstandingAmt').val(decryptedData['connectionDetails'].OutstandingAmt);
                    // $('#existing_connection_detail').val(decryptedData['connectionDetails'].Connection_Type);
                    // $('#house_no').val(decryptedData['connectionDetails'].House_Number);
                    // $('#complainants_full_name').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    // $('#unauthorized_connection_address').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    // $('#plot_no').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    // $('#unauthorized_tap_connection').val(decryptedData['connectionDetails'].Water_Connection_Usage);
                    // $('#zone').val(decryptedData['connectionDetails'].Zone);
                    // $('#ward_area').val(decryptedData['connectionDetails'].Ward);
                    // $('#home_no').val(decryptedData['connectionDetails'].OutstandingAmt);

                    // const uploadedValue = parseInt($('#home_no').val());
                    const uploadedValue = parseInt($('#OutstandingAmt').val());
                    const savePrintBtn = document.getElementById('saveAndPrintBtn');
                    const paybtn = document.getElementById('payaccentech');

                    if (uploadedValue === 0) {
                        savePrintBtn.style.display = 'block';
                        paybtn.style.display = 'none';
                    } else {
                        savePrintBtn.style.display = 'none';
                        paybtn.style.display = 'block';
                    }
                } else {
                    console.error("connectionDetails is missing or undefined");
                }
            },

            error: function(xhr) {
                console.error(xhr.responseText);
            }
        });
    });

    // document.getElementById('saveAndPrintBtn').addEventListener('click', function() {
    //     const form = document.getElementById('addForm');
    //     if (form.checkValidity()) {
    //         document.getElementById('upload_section').style.display = 'block';
    //         document.getElementById('card-footer').style.display = 'block';
    //         html2canvas(form).then(canvas => {
    //             const imgData = canvas.toDataURL('image/png');
    //             const {
    //                 jsPDF
    //             } = window.jspdf;
    //             const pdf = new jsPDF('p', 'mm', 'a4');

    //             const title = "Issuance Of Property Tax Assessment Copy";
    //             pdf.setFont("helvetica", "bold");
    //             pdf.setFontSize(14);

    //             const pageWidth = pdf.internal.pageSize.getWidth();
    //             const margin = 10;
    //             const maxTextWidth = pageWidth - margin * 2;
    //             const lines = pdf.splitTextToSize(title, maxTextWidth);

    //             pdf.text(lines, margin, 15);

    //             const imgProps = pdf.getImageProperties(imgData);
    //             const pdfWidth = pageWidth;
    //             const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

    //             pdf.addImage(imgData, 'PNG', 0, 30, pdfWidth, pdfHeight);
    //             pdf.save('page-content.pdf');
    //         });
    //     } else {
    //         form.reportValidity();
    //     }
    // });
</script>

{{-- <script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('upload_no_dues_certificates');   

    if (!saveBtn || !form) return;  // important safety guard

    saveBtn.addEventListener('click', function () {
        // 1️⃣ Temporarily remove required only if the input exists
        if (fileInput) fileInput.removeAttribute('required');

        // 2️⃣ Validate main form
        if (!form.checkValidity()) {
            form.reportValidity();
            if (fileInput) fileInput.setAttribute('required', 'required');
            return;
        }

        // 3️⃣ Show upload section and footer
        const uploadSection = document.getElementById('upload_section');
        const cardFooter    = document.getElementById('card-footer');
        if (uploadSection) uploadSection.style.display = 'block';
        if (cardFooter)    cardFooter.style.display    = 'block';

        // 4️⃣ Clone the container to generate PDF
        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const printClone = addContainer.cloneNode(true);
        Object.assign(printClone.style, {
            fontSize: '16px',
            lineHeight: '1.4',
            padding: '20px',
            margin: '0 auto',
            background: '#fff',
            width: '210mm',
            minHeight: '297mm',
            boxSizing: 'border-box'
        });

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

        // Add title
        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {
            textAlign: 'center',
            marginBottom: '18px',
            fontSize: '18px'
        });
        printTitle.textContent = 'Certificate of construction drainage connection';
        printClone.insertBefore(printTitle, printClone.firstChild);

        // Remove buttons & style cards
        printClone.querySelectorAll('button').forEach(btn => btn.remove());
        printClone.querySelectorAll('.card').forEach(card => {
            Object.assign(card.style, {
                background: 'white',
                boxShadow: 'none',
                border: '1px solid #ccc',
                marginBottom: '12px',
                padding: '12px'
            });
        });

        // Show hidden selected values
        printClone.querySelectorAll('.selected-value').forEach(div => {
            div.classList.remove('d-none');
        });

        // Prepare container for html2canvas
        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(printClone);

        // 5️⃣ Generate PDF
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1,
            useCORS: true,
            allowTaint: true,
            logging: false
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const margin = 10;

            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );

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

            pdf.save('Construction Drainage ConnectionCertificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            // 6️⃣ Restore required if the input exists
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script> --}}

{{-- <script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('upload_no_dues_certificates');   

    if (!saveBtn || !form) return;

    // 🔹 Custom validation messages
    const messages = {
        connection_count: 'Connection No is Required',
        zone: 'Zone is Required',
        property_number: 'Property No is Required',
        is_toilet_available: 'Toilet is Required',
        lichpit_count: 'Lichpit is Required',
        oc_cc_docs: 'Document is Required',
        Connection_Type: 'Connection Type is Required',
        is_correct_info:'Please accept the Declaration',
    };

    function showError(input, msg) {
        let error;

        if (input.type === 'checkbox') {
            // ✅ For checkbox, show message inside existing span
            error = input.closest('.col-md-12').querySelector('.is_correct_info_err');
            if (error) {
                error.textContent = msg;
            }
        } else {
            // ✅ For other inputs, create or use error div
            error = input.nextElementSibling;
            if (!error || !error.classList.contains('error-message')) {
                error = document.createElement('div');
                error.classList.add('error-message');
                Object.assign(error.style, {color: 'red', fontSize: '13px', marginTop: '2px'});
                input.parentNode.insertBefore(error, input.nextSibling);
            }
            error.textContent = msg;
            input.classList.add('invalid');
        }
    }

    function clearErrors() {
        form.querySelectorAll('.error-message').forEach(e => e.remove());
        form.querySelectorAll('.invalid').forEach(inp => inp.classList.remove('invalid'));
        // Clear checkbox error span
        const checkboxError = form.querySelector('.is_correct_info_err');
        if (checkboxError) checkboxError.textContent = '';
    }

    saveBtn.addEventListener('click', function (e) {
        e.preventDefault();
        clearErrors();

        let hasError = false;

        // Validate each field
        Object.keys(messages).forEach(name => {
            const input = form.querySelector(`[name="${name}"]`);
            if (!input) return;

            if (input.type === 'checkbox' && !input.checked) {
                showError(input, messages[name]);
                hasError = true;
            } else if (input.type !== 'checkbox' && !input.value.trim()) {
                showError(input, messages[name]);
                hasError = true;
            }
        });

        // Stop if any field is invalid
        if (hasError) return;

        // Temporarily remove required for fileInput
        if (fileInput) fileInput.removeAttribute('required');

        // Show upload section & footer
        const uploadSection = document.getElementById('upload_section');
        const cardFooter    = document.getElementById('card-footer');
        if (uploadSection) uploadSection.style.display = 'block';
        if (cardFooter)    cardFooter.style.display    = 'block';

        // Clone container for PDF
        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const printClone = addContainer.cloneNode(true);
        const uploadSectionInClone = printClone.querySelector('#upload_section');
            if (uploadSectionInClone) {
                uploadSectionInClone.remove();
            } 
        Object.assign(printClone.style, {
            fontSize: '16px',
            lineHeight: '1.4',
            padding: '20px',
            margin: '0 auto',
            background: '#fff',
            width: '210mm',
            minHeight: '297mm',
            boxSizing: 'border-box'
        });

        Array.from(printClone.querySelectorAll('*')).forEach(el => el.style.fontSize = '16px');

        // Add title
        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {textAlign: 'center', marginBottom: '18px', fontSize: '18px'});
        printTitle.textContent = 'Certificate of construction drainage connection';
        printClone.insertBefore(printTitle, printClone.firstChild);

        // Remove buttons & style cards
        printClone.querySelectorAll('button').forEach(btn => btn.remove());
        printClone.querySelectorAll('.card').forEach(card => {
            Object.assign(card.style, {
                background: 'white',
                boxShadow: 'none',
                border: '1px solid #ccc',
                marginBottom: '12px',
                padding: '12px'
            });
        });

        // Show hidden selected values
        printClone.querySelectorAll('.selected-value').forEach(div => div.classList.remove('d-none'));

        // Prepare container for html2canvas
        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(printClone);

        // Generate PDF
        html2canvas(printClone, {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 margin = 10;
            pdf.addImage(imgData, 'JPEG', margin, margin, pdf.internal.pageSize.getWidth() - margin * 2, pdf.internal.pageSize.getHeight() - margin * 2);
            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) alert('Warning: PDF size is greater than 2 MB. Please reduce content.');
            pdf.save('Construction Drainage ConnectionCertificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script> --}}






<script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('upload_no_dues_certificates');   

    if (!saveBtn || !form) return;

    const messages = {
        connection_count: 'Connection No is Required',
        zone: 'Zone is Required',
        property_number: 'Property No is Required',
        is_toilet_available: 'Toilet is Required',
        lichpit_count: 'Lichpit is Required',
        oc_cc_docs: 'Document is Required',
        Connection_Type: 'Connection Type is Required',
        is_correct_info:'Please accept the Declaration',
    };

    function showError(input, msg) {
        let error;
        if (input.type === 'checkbox') {
            error = input.closest('.col-md-12').querySelector('.is_correct_info_err');
            if (error) error.textContent = msg;
        } else {
            error = input.nextElementSibling;
            if (!error || !error.classList.contains('error-message')) {
                error = document.createElement('div');
                error.classList.add('error-message');
                Object.assign(error.style, {color: 'red', fontSize: '13px', marginTop: '2px'});
                input.parentNode.insertBefore(error, input.nextSibling);
            }
            error.textContent = msg;
            input.classList.add('invalid');
        }
    }

    function clearErrors() {
        form.querySelectorAll('.error-message').forEach(e => e.remove());
        form.querySelectorAll('.invalid').forEach(inp => inp.classList.remove('invalid'));
        const checkboxError = form.querySelector('.is_correct_info_err');
        if (checkboxError) checkboxError.textContent = '';
    }

    saveBtn.addEventListener('click', function (e) {
        e.preventDefault();
        clearErrors();

        let hasError = false;

        Object.keys(messages).forEach(name => {
            const input = form.querySelector(`[name="${name}"]`);
            if (!input) return;

            if (input.type === 'checkbox' && !input.checked) {
                showError(input, messages[name]);
                hasError = true;
            } else if (input.type !== 'checkbox' && !input.value.trim()) {
                showError(input, messages[name]);
                hasError = true;
            }
        });

        if (hasError) return;

        if (fileInput) fileInput.removeAttribute('required');

        // ✅ Replace dropdown (select) with textbox-style div showing selected text
        const toiletSelect = form.querySelector('#is_toilet_available');
        const selectedText = toiletSelect.options[toiletSelect.selectedIndex]?.text || '';

        // Create a fake input box to look identical
        const fakeInput = document.createElement('input');
        fakeInput.type = 'text';
        fakeInput.className = toiletSelect.className;
        fakeInput.value = selectedText;
        fakeInput.style.width = toiletSelect.offsetWidth + 'px';
        fakeInput.style.height = toiletSelect.offsetHeight + 'px';
        fakeInput.style.textAlign = 'left';
        fakeInput.style.padding = '6px';
        fakeInput.style.border = '1px solid #ced4da';
        fakeInput.style.borderRadius = '4px';
        fakeInput.style.backgroundColor = '#fff';

        // Hide select and insert fake textbox in its place
        toiletSelect.style.display = 'none';
        toiletSelect.parentNode.insertBefore(fakeInput, toiletSelect);

        // Show upload section & footer
        const uploadSection = document.getElementById('upload_section');
        const cardFooter    = document.getElementById('card-footer');
        if (uploadSection) uploadSection.style.display = 'block';
        if (cardFooter)    cardFooter.style.display    = 'block';

        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const printClone = addContainer.cloneNode(true);
        const uploadSectionInClone = printClone.querySelector('#upload_section');
        if (uploadSectionInClone) uploadSectionInClone.remove();

        Object.assign(printClone.style, {
            fontSize: '16px',
            lineHeight: '1.4',
            padding: '20px',
            margin: '0 auto',
            background: '#fff',
            width: '210mm',
            minHeight: '297mm',
            boxSizing: 'border-box'
        });

        Array.from(printClone.querySelectorAll('*')).forEach(el => el.style.fontSize = '16px');

        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {textAlign: 'center', marginBottom: '18px', fontSize: '18px'});
        printTitle.textContent = 'Certificate of construction drainage connection';
        printClone.insertBefore(printTitle, printClone.firstChild);

        printClone.querySelectorAll('button').forEach(btn => btn.remove());
        printClone.querySelectorAll('.card').forEach(card => {
            Object.assign(card.style, {
                background: 'white',
                boxShadow: 'none',
                border: '1px solid #ccc',
                marginBottom: '12px',
                padding: '12px'
            });
        });

        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(printClone);

        html2canvas(printClone, {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 margin = 10;
            pdf.addImage(imgData, 'JPEG', margin, margin, pdf.internal.pageSize.getWidth() - margin * 2, pdf.internal.pageSize.getHeight() - margin * 2);
            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) alert('Warning: PDF size is greater than 2 MB. Please reduce content.');
            pdf.save('Construction Drainage ConnectionCertificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            if (fileInput) fileInput.setAttribute('required', 'required');
            toiletSelect.style.display = ''; // Restore dropdown after generation
            if (fakeInput && fakeInput.parentNode) fakeInput.remove();
        });
    });
});
</script>








{{-- Add --}}
{{-- <script>
    $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('construction-drainage-connection.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.error2)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        window.location.href = '{{ route('my-application') }}';
                    });
                else
                    swal("Error!", data.error2, "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> --}}




<!--kishori add -->
<script>
$("#addForm").submit(function(e) {
    e.preventDefault();

    // Check if upload section is visible
    if ($("#upload_section").is(":visible")) {
        const fileInput = $("#upload_no_dues_certificates");
        const fileValue = fileInput.val();

        if (!fileValue) {
            $(".upload_no_dues_certificates_err").text("Please upload the prescribed format application file / कृपया विहित नमुन्यातील अर्ज अपलोड करा.");
            fileInput.addClass("is-invalid");
            return false; // stop form submission
        } else {
            $(".upload_no_dues_certificates_err").text("");
            fileInput.removeClass("is-invalid");
        }
    }

    $("#addSubmit").prop('disabled', true);

    var formdata = new FormData(this);
    $.ajax({
        url: '{{ route('construction-drainage-connection.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.error2)
                swal("Successful!", data.success, "success")
                .then((action) => {
                    window.location.href = '{{ route('my-application') }}';
                });
            else
                swal("Error!", data.error2, "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>

<!--applicant name-->
<script>
    function isLetterOrSpace(e) {
        const char = String.fromCharCode(e.which || e.keyCode);
        const regex = /^[A-Za-zअ-हऀ-ॿ\s]+$/;
        return regex.test(char);
    }
</script>

<!--adhar card no validation-->
<script>
    function isNumberKey(evt) {
        var charCode = evt.which ? evt.which : evt.keyCode;

        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
            return false;
        }
        return true;
    }


    function limitAadharLength(input) {
        if (input.value.length > 12) {
            input.value = input.value.slice(0, 12);
        }
    }
</script>



<script>
document.addEventListener('DOMContentLoaded', function () {
    const existingConInput = document.getElementById('property_number');

    if (existingConInput) {
        existingConInput.addEventListener('input', function (e) {
            // Remove any non-digit characters
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    }
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const existingConInput = document.getElementById('connection_count');

    if (existingConInput) {
        existingConInput.addEventListener('input', function (e) {
            // Remove any non-digit characters
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    }
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const existingConInput = document.getElementById('zone');

    if (existingConInput) {
        existingConInput.addEventListener('input', function () {
            // Sirf letters (uppercase/lowercase) aur spaces allow karna ho to use [^a-zA-Z\s]
            this.value = this.value.replace(/[^a-zA-Z]/g, '');
        });
    }
});
</script>



