<x-admin.layout>
    <x-slot name="title">Temporary Permanent Disconnection Water Supply / तात्पुरते किंवा कायमस्वरूपी नळजोडणी खंडीत करणे</x-slot>
    <x-slot name="heading">Temporary Permanent Disconnection Water Supply / तात्पुरते किंवा कायमस्वरूपी नळजोडणी खंडीत करणे</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">
                    <div class="card-body">
                        <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>
                                <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>{{ $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>
                                <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>
                                <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>
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>

                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">

                            @csrf
                            <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" 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"  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"  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"  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"  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"  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"  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"  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"  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>

                    <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="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">
                                    <label class="col-form-label" for="comment">Applicant Full Name/ अर्जदाराचे पूर्ण नाव</label>
                                    <input class="form-control" id="comment" name="comment" type="text" placeholder="Enter Comment ">
                                    <span class="text-danger is-invalid comment_err"></span>
                                </div>

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

                                <div class="col-md-4">
                                    <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" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" type="text" placeholder="Enter Mobile Number" required>
                                    <span class="text-danger is-invalid mobile_no_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <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" required>
                                    <span class="text-danger is-invalid email_id_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <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" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" type="text" placeholder="Enter Aadhar Card No" required>
                                    <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="water_connection_no">Water Connection No / पाणी कनेक्शन क्र<span class="text-danger">*</span></label>
                                    <input class="form-control" id="water_connection_no" name="water_connection_no" type="text" placeholder="CNNP01B0000001" required>
                                    <span class="text-danger is-invalid water_connection_no_err"></span>
                                </div> --}}

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="new_owner_name">Name Of Owner / मिळकतीच्या मालकाचे नाव <span class="text-danger">*</span></label>
                                    <input class="form-control" id="new_owner_name" name="new_owner_name" type="text" placeholder="Enter Name Of New Owner" required>
                                    <span class="text-danger is-invalid new_owner_name_err"></span>
                                </div> --}}

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

                                <div class="col-md-4">
                                    <label class="col-form-label" for="landmark">Landmark / जवळची खूण </label>
                                    <input class="form-control" id="landmark" name="landmark" type="text" placeholder="Enter Landmark">
                                    <span class="text-danger is-invalid landmark_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" required>
                                        <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_area">Ward Area / प्रभाग क्षेत्र<span class="text-danger">*</span></label>
                                    <select class="form-select" name="ward_area" id="ward_area" required>
                                        <option value="">Select Ward Area</option>

                                        @foreach ($wards as $ward)
                                        <option value="{{ $ward->name }}">{{ $ward->name }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid ward_area_err"></span>
                                </div> --}}


                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="house_no">Property Number /मालमत्ता क्रमांक <span class="text-danger">*</span></label>
                                    <input class="form-control" id="house_no" name="house_no" type="text" placeholder="Enter House Number" required>
                                    <span class="text-danger is-invalid house_no_err"></span>
                                </div> --}}

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="current_connection_is_authorized">Usage of Water Connection / पाण्याच्या कनेक्शनचा वापर <span class="text-danger">*</span></label>
                                    <select class="form-select" name="current_connection_is_authorized" id="current_connection_is_authorized" required>
                                        <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 current_connection_is_authorized_err"></span>
                                </div> --}}

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="sub_usage">Water Sub Usage / पाण्याचा उप-वापर<span class="text-danger">*</span></label>
                                    <select class="form-select" name="sub_usage" id="sub_usage" required>
                                        <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 sub_usage_err"></span>
                                </div> --}}

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="tap_size">Connection Size/कनेक्शन आकार<span class="text-danger">*</span></label>
                                    <select class="form-select" name="tap_size" id="tap_size" required>
                                        <option value="">Select option</option>
                                        @php
                                            $options = ['15mm', '20mm', '25mm', '40mm', '50mm', '80mm', '100mm', '150mm', '300mm'];
                                        @endphp
                                        @foreach ($options as $option)
                                            <option value="{{ $option }}">{{ $option }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid tap_size_err"></span>
                                </div> --}}
                                <div class="col-md-4">
                                    <label class="col-form-label" for="no_of_existing_con">Number of Existing Water Connection/ विद्यमान पाणी जोडणींची संख्या <span class="text-danger">*</span></label>
                                    <input class="form-control" id="no_of_existing_con" name="no_of_existing_con" type="text" placeholder="Enter Plot Number" >
                                    <span class="text-danger is-invalid no_of_existing_con_err"></span>
                                </div>

                                 {{-- <div class="col-md-4">
                            <label class="col-form-label" for="Water_Connection_Size">
                                Water Connection Type <span class="text-danger">*</span>
                            </label>
                            <select class="form-control" id="Water_Connection_Size_Count" name="Water_Connection_Size_Count">
                                <option value="">-- Select --</option>
                                <option value="3570">घरगुती</option>
                                <option value="3570">वाणिज्य </option>
                            </select>
                            <span class="text-danger is-invalid Water_Connection_Size_err"></span>
                        </div> --}}
                        <div class="col-md-4">
    <label class="col-form-label" for="Water_Connection_Size_Count">
        Water Connection Type <span class="text-danger">*</span>
    </label>
    <select class="form-control" id="Water_Connection_Size_Count" name="Water_Connection_Size_Count" required>
        <option value="">-- Select --</option>
        <option value="3570" data-label="घरगुती">घरगुती</option>
        <option value="3570" data-label="वाणिज्य">वाणिज्य</option>
    </select>

    <!-- Hidden field to store label -->
    <input type="hidden" id="Water_Connection_Label" name="Water_Connection_Label">

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


                                <div class="col-md-4">
                                    <label class="col-form-label" for="disconnection_type">Disconnection Type / डिस्कनेक्शन प्रकार<span class="text-danger">*</span></label>
                                    <select class="form-select" name="disconnection_type" id="disconnection_type" >
                                        <option value="">Select option</option>
                                        @php
                                            $options = ['Temporary Disconnection', 'Permanent Disconnection'];
                                        @endphp
                                        @foreach ($options as $option)
                                            <option value="{{ $option }}">{{ $option }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid disconnection_type_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="criminal_judicial_issue">If Any Criminal Judicial Issue exist on Connection/जर कनेक्शनवर कोणताही फौजदारी न्यायिक मुद्दा अस्तित्वात असेल तर<span
                                            class="text-danger"></span></label>
                                    <select class="form-select" name="criminal_judicial_issue" id="criminal_judicial_issue" >
                                        <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 criminal_judicial_issue_err"></span>
                                </div>


                                <div class="col-md-4">
                                <label class="col-form-label" for="prev_water_bill">Water Tax Bill/पाणी बिल देयक </label>
                                <input class="form-control" id="prev_water_bills" name="prev_water_bills" type="file">
                                <span class="text-danger is-invalid prev_water_bill_err"></span>
                            </div>







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

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="place_belongs_to_municipal">If Any Criminal Judicial Issue exist on Connection /जर कनेक्शनवर कोणताही फौजदारी न्यायिक मुद्दा अस्तित्वात असेल तर<span class="text-danger">*</span></label>
                                    <select class="form-select" name="place_belongs_to_municipal" id="place_belongs_to_municipal" required>
                                        <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 place_belongs_to_municipal_err"></span>
                                </div> --}}

                                {{--
                                <div class="col-md-4">
                                    <label class="col-form-label" for="existing_connection_detail">Currently Existing Tap Connection Detail / मिळकतीस सध्या अस्तित्वात असलेल्या नळ कनेक्शनचा तपशील<span class="text-danger">*</span></label>
                                    <select class="form-select" name="existing_connection_detail" id="existing_connection_detail" required>
                                        <option value="">Select option</option>
                                        @php
                                            $options = ["बांधकाम", "औद्योगीक", "निवासी", "विशेष प्रवर्ग (शैक्षणिक संस्था,शासकीय,निमशासकीय कार्यालय,पथसंस्था,इतर)", "व्यावसायिक अथवा वाणिज्य"];
                                        @endphp
                                        @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid existing_connection_detail_err"></span>
                                </div>



                                <div class="col-md-4">
                                    <label class="col-form-label" for="nodues_documents">Upload Certificate Of No Dues / थकबाकी नसल्याचा दाखला अपलोड करा <span class="text-danger">*</span></label>
                                    <input class="form-control" id="nodues_documents" name="nodues_documents" type="file" required>
                                    <span class="text-danger is-invalid nodues_documents_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" required 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. / वरील पुरविलेली सर्व माहिती ही अचूक असून, त्यात कुठल्याही प्रकारची तफावत आढळल्यास त्यास मी पूर्णतः जबाबदार
                                            असेन."
                                        </label>
                                    </div>
                                    <span class="text-danger is-invalid is_correct_info_err d-block mt-1"></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>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn = document.getElementById('saveAndPrintBtn');
    const form = document.getElementById('addForm');

    const validationMessages = {
        connection_no: 'Connection No is Required',
        Property_Owner_Name: 'Property Owner is Required',
        Full_Address_Of_The_Property: 'Full Address is Required',
        Ward: 'Ward is Required',
        zone: 'Zone is Required',
        Water_Connection_Size: 'Water Connection is Required',
        Connection_Type: 'Connection Type is Required',
        Water_Connection_Usage: 'Water Connection Usage is Required',
        OutstandingAmt: 'Outstanding is Required',
        no_of_existing_con: 'Total Connection is Required',
        disconnection_type: 'Property No is Required',
        criminal_judicial_issue: 'Existing Water Bill is Required',
        is_correct_info: 'Please accept the Declaration'
    };

    if (!saveBtn || !form) return;

    saveBtn.addEventListener('click', function (e) {
        e.preventDefault(); // Prevent form submit until validation

        let isValid = true;

        // Clear previous errors
        Object.keys(validationMessages).forEach(field => {
            const errorSpan = document.querySelector(`.${field}_err`);
            if (errorSpan) errorSpan.textContent = '';
        });

        // Validate each field
        Object.keys(validationMessages).forEach(field => {
            const input = form.querySelector(`[name="${field}"]`);
            if (input) {
                if ((input.type === 'checkbox' || input.type === 'radio') && !input.checked) {
                    isValid = false;
                    const errorSpan = document.querySelector(`.${field}_err`);
                    if (errorSpan) errorSpan.textContent = validationMessages[field];
                } else if (!input.value.trim()) {
                    isValid = false;
                    const errorSpan = document.querySelector(`.${field}_err`);
                    if (errorSpan) errorSpan.textContent = validationMessages[field];
                }
            }
        });

        if (!isValid) {
            // Scroll to first error
            const firstError = form.querySelector('.text-danger:not(:empty)');
            if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            return;
        }

        // ✅ If validation passes, continue with PDF generation...
        // Your existing html2canvas + jsPDF code goes here
    });
});
</script> --}}





{{-- <script>
$(document).ready(function () {
    const validationMessages = {
        connection_no: 'Connection No is Required',
        Property_Owner_Name: 'Property Owner is Required',
        Full_Address_Of_The_Property: 'Full Address is Required',
        Ward: 'Ward is Required',
        zone: 'Zone is Required',
        Water_Connection_Size_Count: 'Water Connection Type is Required',
        Connection_Type: 'Connection Type is Required',
        Water_Connection_Usage: 'Water Connection Usage is Required',
        OutstandingAmt: 'Outstanding is Required',
        no_of_existing_con: 'Total Connection is Required',
        disconnection_type: 'Disconnection Type is Required',
        criminal_judicial_issue: 'Existing Water Bill is Required',
        is_correct_info: 'Please accept the Declaration'
    };

    $('#saveAndPrintBtn').click(function (e) {
        e.preventDefault();
        let isValid = true;

        
        $.each(validationMessages, function (field) {
            $('.' + field + '_err').text('');
        });

       
        $.each(validationMessages, function (field, message) {
            const input = $('[name="' + field + '"]');
            if (input.length) {
                if ((input.attr('type') === 'checkbox' || input.attr('type') === 'radio') && !input.is(':checked')) {
                    isValid = false;
                    $('.' + field + '_err').text(message);
                } else if (!input.val() || $.trim(input.val()) === '') {
                    isValid = false;
                    $('.' + field + '_err').text(message);
                }
            }
        });

        
        if (!isValid) {
            const firstError = $('.text-danger:contains("Required"), .text-danger:contains("Declaration")').first();
            if (firstError.length) {
                $('html, body').animate({ scrollTop: firstError.offset().top - 100 }, 600);
            }
            return;
        }

        
        const $uploadSection = $('#upload_section');
        const $cardFooter = $('#card-footer');
        $uploadSection.hide();
        $cardFooter.hide();

       
        const dropdownValues = {};
        [
            'Water_Connection_Size_Count',
            'disconnection_type',
            'criminal_judicial_issue'
        ].forEach(id => {
            const $select = $('#' + id);
            if ($select.length) {
                dropdownValues[id] = $select.find('option:selected').text().trim();
            }
        });

       
        const $clone = $('#addForm').clone();

       
        $clone.css({
            background: '#fff',
            padding: '25px 30px',
            width: '210mm',
            margin: '0 auto',
            border: '1.8px solid #dcdcdc',
            borderRadius: '8px',
            boxSizing: 'border-box',
            fontFamily: 'Arial, sans-serif',
            lineHeight: '1.5'
        });

        $clone.find('*').css({
            fontSize: '15px',
            margin: '4px 0'
        });

        
        $clone.find('button, #upload_section, #card-footer').remove();

        
        const $title = $('<h2>')
            .text('Certificate of Water Disconnection Application')
            .css({
                textAlign: 'center',
                fontSize: '18px',
                marginBottom: '20px',
                fontWeight: 'bold'
            });
        $clone.prepend($title);

        
        $clone.find('.card').css({
            background: 'white',
            border: '1px solid #e0e0e0',
            boxShadow: 'none',
            marginBottom: '12px',
            padding: '12px'
        });

        
        Object.entries(dropdownValues).forEach(([id, text]) => {
            const clonedSelect = $clone.find('#' + id);
            if (clonedSelect.length) {
                clonedSelect.after(`
                    <div style="
                        margin-top:5px;
                        font-size:15px;
                        border:1px solid #ccc;
                        padding:6px 10px;
                        border-radius:5px;
                        background:#fff;
                        display:inline-block;
                        min-width:160px;
                    ">${text}</div>
                `);
                clonedSelect.remove();
            }
        });

       
        let $printContainer = $('#printContainer');
        if (!$printContainer.length) {
            $('body').append('<div id="printContainer" style="position:fixed;left:-9999px;top:0;background:#fff;"></div>');
            $printContainer = $('#printContainer');
        }
        $printContainer.html($clone);

       
        html2canvas($clone[0], {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1.3,
            useCORS: true
        }).then(canvas => {
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const margin = 8;
            const imgData = canvas.toDataURL('image/jpeg', 0.98);

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

            pdf.save('Water_Disconnection_Application.pdf');

            // ✅ After PDF saved, show upload & footer again
            $uploadSection.show();
            $cardFooter.show();

        }).catch(err => {
            console.error(err);
            alert('Error generating PDF.');
            $uploadSection.show();
            $cardFooter.show();
        });
    });
});
</script> --}}


<script>
$(document).ready(function () {
    const validationMessages = {
        connection_no: 'Connection No is Required',
        Property_Owner_Name: 'Property Owner is Required',
        Full_Address_Of_The_Property: 'Full Address is Required',
        Ward: 'Ward is Required',
        zone: 'Zone is Required',
        Water_Connection_Size_Count: 'Water Connection Type is Required',
        Connection_Type: 'Connection Type is Required',
        Water_Connection_Usage: 'Water Connection Usage is Required',
        OutstandingAmt: 'Outstanding is Required',
        no_of_existing_con: 'Total Connection is Required',
        disconnection_type: 'Disconnection Type is Required',
        //criminal_judicial_issue: 'Existing Water Bill is Required',
        is_correct_info: 'Please accept the Declaration'
    };

    $('#saveAndPrintBtn').click(function (e) {
        e.preventDefault();
        let isValid = true;

        // Clear old error messages
        $.each(validationMessages, function (field) {
            $('.' + field + '_err').text('');
        });

        // Validation check
        $.each(validationMessages, function (field, message) {
            const input = $('[name="' + field + '"]');
            if (input.length) {
                if ((input.attr('type') === 'checkbox' || input.attr('type') === 'radio') && !input.is(':checked')) {
                    isValid = false;
                    $('.' + field + '_err').text(message);
                } else if (!input.val() || $.trim(input.val()) === '') {
                    isValid = false;
                    $('.' + field + '_err').text(message);
                }
            }
        });

        if (!isValid) {
            const firstError = $('.text-danger:contains("Required"), .text-danger:contains("Declaration")').first();
            if (firstError.length) {
                $('html, body').animate({ scrollTop: firstError.offset().top - 100 }, 600);
            }
            return;
        }

        // ✅ SHOW upload & footer, HIDE save/print button
        $('#upload_section').show();
        $('#card-footer').show();
        $('#saveAndPrintBtn').closest('.form-group').hide();

        // --- Existing PDF generation logic below ---
        const dropdownValues = {};
        ['Water_Connection_Size_Count', 'disconnection_type', 'criminal_judicial_issue'].forEach(id => {
            const $select = $('#' + id);
            if ($select.length) {
                dropdownValues[id] = $select.find('option:selected').text().trim();
            }
        });

        const $clone = $('#addForm').clone();

        $clone.css({
            background: '#fff',
            padding: '25px 30px',
            width: '210mm',
            margin: '0 auto',
            border: '1.8px solid #dcdcdc',
            borderRadius: '8px',
            boxSizing: 'border-box',
            fontFamily: 'Arial, sans-serif',
            lineHeight: '1.5'
        });

        $clone.find('*').css({ fontSize: '15px', margin: '4px 0' });
        $clone.find('button, #upload_section, #card-footer').remove();

        const $title = $('<h2>')
            .text('Certificate of Water Disconnection Application')
            .css({
                textAlign: 'center',
                fontSize: '18px',
                marginBottom: '20px',
                fontWeight: 'bold'
            });
        $clone.prepend($title);

        $clone.find('.card').css({
            background: 'white',
            border: '1px solid #e0e0e0',
            boxShadow: 'none',
            marginBottom: '12px',
            padding: '12px'
        });

        Object.entries(dropdownValues).forEach(([id, text]) => {
            const clonedSelect = $clone.find('#' + id);
            if (clonedSelect.length) {
                clonedSelect.after(`
                    <div style="
                        margin-top:5px;
                        font-size:15px;
                        border:1px solid #ccc;
                        padding:6px 10px;
                        border-radius:5px;
                        background:#fff;
                        display:inline-block;
                        min-width:160px;
                    ">${text}</div>
                `);
                clonedSelect.remove();
            }
        });

        let $printContainer = $('#printContainer');
        if (!$printContainer.length) {
            $('body').append('<div id="printContainer" style="position:fixed;left:-9999px;top:0;background:#fff;"></div>');
            $printContainer = $('#printContainer');
        }
        $printContainer.html($clone);

        html2canvas($clone[0], {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1.3,
            useCORS: true
        }).then(canvas => {
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const margin = 8;
            const imgData = canvas.toDataURL('image/jpeg', 0.98);

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

            pdf.save('Water_Disconnection_Application.pdf');
        }).catch(err => {
            console.error(err);
            alert('Error generating PDF.');
        });
    });
});
</script>























{{-- Add --}}
<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); // Replace with actual decryption function

                console.log("Decrypted Data:", decryptedData['connectionDetails'].Water_Connection_Number);

                if (decryptedData && decryptedData['connectionDetails']) {
                    $('#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);
                    // $('#water_connection_no').val(decryptedData['connectionDetails'].Water_Connection_Number);
                    // $('#applicant_full_name').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    // $('#new_owner_name').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    // $('#address').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    // $('#house_no').val(decryptedData['connectionDetails'].Water_Connection_Usage);
                    // $('#owner_add').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    // $('#ward').val(decryptedData['connectionDetails'].Ward);
                } else {
                    console.error("connectionDetails is missing or undefined");
                }
            },

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

    $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('water-disconnect-supply.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>
    // ✅ Allow only numeric input (no letters or special chars)
    document.getElementById('no_of_existing_con').addEventListener('input', function (e) {
        this.value = this.value.replace(/[^0-9]/g, ''); // removes everything except digits
    });
</script>

<script>
document.getElementById('Water_Connection_Size_Count').addEventListener('change', function() {
    const selected = this.options[this.selectedIndex];
    document.getElementById('Water_Connection_Label').value = selected.getAttribute('data-label') || '';
});
</script>
