<x-admin.layout>
    <x-slot name="title">Making Change In Ownership / मालकी हक्कात बदल करणे</x-slot>
    <x-slot name="heading">Making Change In Ownership / मालकी हक्कात बदल करणे</x-slot>

    <!-- Add Form -->
    <div class="row" id="addContainer">
        <div class="col-sm-12">
            <div class="card">


                <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                    @csrf

                    <div class="card-header">
                        <h4 class="card-title">Applicant Details</h4>
                    </div>
                    <div class="card">
                        <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 / आधार क्रमांक</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">
                                    <span class="text-danger is-invalid aadhar_no_err"></span>
                                </div>

                            </div>
                        </div>

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

                                <form class="theme-form" name="detailfetch" id="detailfetch" enctype="multipart/form-data">
                                    @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" required>
                                        <span class="text-danger is-invalid connection_no_err"></span>
                                    </div>

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

                            </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">New 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">Connection Details</h4>
                        </div>

                        <div class="card-body">
                            <div class="row">
                                <!-- Total Connection -->
                                <div class="col-md-4">
                                    <label class="col-form-label" for="total_connection">Total Connection / एकूण कनेक्शन <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="total_connection" name="total_connection" placeholder="Enter Total Connections" required>
                                    <span class="text-danger is-invalid total_connection_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="3000">घारगुती</option>
                                <option value="5000">वाणिज्य </option>
                            </select>
                            <span class="text-danger is-invalid Water_Connection_Size_err"></span>
                        </div>

                                <!-- Connection Number -->
                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="connection_no">Connection Number / कनेक्शन क्रमांक <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="connection_no" name="connection_no" placeholder="Enter connection number" required>
                                    <span class="text-danger is-invalid connection_no_err"></span>
                                </div> --}}

                                <!-- Owner Name -->
                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="owner_name">Owner Name / मालकाचे नाव <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="owner_name" name="owner_name" placeholder="Enter owner name" required>
                                    <span class="text-danger is-invalid owner_name_err"></span>
                                </div> --}}

                                <!-- Owner Address -->
                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="owner_add">Owner Address / मालकाचा पत्ता <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="owner_add" name="owner_add" placeholder="Enter owner address" required>
                                    <span class="text-danger is-invalid owner_add_err"></span>
                                </div> --}}

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="ward_area">Ward / प्रभाग<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->id }}">{{ $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="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->id }}">{{ $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="property_no">Property Number / मालमत्ता क्र <span class="text-danger">*</span></label>
                                    <input class="form-control" id="property_no" name="property_no" type="text" placeholder="Enter Property Number" required>
                                    <span class="text-danger is-invalid property_no_err"></span>
                                </div>

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="house_no">Usage of Water Connection /पाणी जोडणीचा वापर<span class="text-danger">*</span></label>
                                    <input class="form-control" id="house_no" name="house_no" type="text" placeholder="Enter water Usage" required>
                                    <span class="text-danger is-invalid house_no_err"></span>
                                </div> --}}

                                <div class="col-md-4">
                                    <label class="col-form-label" for="sub_usage">Water Sub Usage / पाणी उपवापर</label>
                                    <input class="form-control" id="sub_usage" name="sub_usage" type="text" placeholder="Enter Sub Usage">
                                    <span class="text-danger is-invalid sub_usage_err"></span>
                                </div>

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="address">Connection Size / कनेक्शन आकार <span class="text-danger">*</span></label>
                                    <input class="form-control" name="address" id="address" placeholder="Enter  connection Size" required>
                                    <span class="text-danger is-invalid address_err"></span>
                                </div> --}}
                                {{--


                                <div class="col-md-4">
                                    <label class="col-form-label" for="new_tap_connection">Detail Of New Tap Connection / मिळकतीस नवीन मागणी केलेल्या नळ कनेक्शनचा तपशील <span class="text-danger">*</span></label>
                                    <select class="form-select" name="new_tap_connection" id="new_tap_connection" 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 new_tap_connection_err"></span>
                                </div>


                                <div class="col-md-4">
                                    <label class="col-form-label" for="current_connection_is_authorized">Currently Existed Tap Connection Unauthorized / मिळकतीस सध्या अस्तित्वात असलेले नळ कनेक्शन अनाधिकृत होते काय ? <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="applicant_or_tenant">Applicant Or Tenant / अर्जदार / भाडेकरु आहेत काय ?   <span class="text-danger">*</span></label>
                                    <select class="form-select" name="applicant_or_tenant" id="applicant_or_tenant" 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 applicant_or_tenant_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="no_of_user">Number Of Users For New Tap Connection / मागणी केलेल्या नवीन नळ कनेक्शनमधून पाणी पुरवठ्याचा वापर करणाऱ्या कुटुंबाची संख्या<span class="text-danger">*</span></label>
                                    <input class="form-control" id="no_of_user" name="no_of_user" type="number" placeholder="Enter Number Of Users For New Tap Connection" required>
                                    <span class="text-danger is-invalid no_of_user_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="criminal_judicial_issue">Criminal Judicial Issues About Existing Tap Connection / मिळकतीस सध्या असलेल्या नळ कनेक्शनाबाबत काही फौजदारी किंवा न्यायालयीन बाबी सुरु आहेत का ? <span class="text-danger">*</span></label>
                                    <select class="form-select" name="criminal_judicial_issue" id="criminal_judicial_issue" 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 criminal_judicial_issue_err"></span>
                                </div> --}}

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="old_owner_name">Name of old water connection Owenr / जुन्या नळ जोडणी मालकाचे नाव <span class="text-danger">*</span></label>
                                    <input class="form-control" id="old_owner_name" name="old_owner_name" type="text" placeholder="Enter Name of old water connection Owenr" required>
                                    <span class="text-danger is-invalid old_owner_name_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="tap_size">Tap 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="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="place_belongs_to_municipal">Place Belongs To Municipal Council Limit / सदर जागा नगरपरिषदेच्या हद्दीत आहे का ? <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="comment">Comment / टिप्पणी</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="ownership_documents">Upload ownership documents / मालकी असल्याबाबतचे कागदपत्रे जोडा <span class="text-danger">*</span></label>
                                    <input class="form-control" id="ownership_documents" name="ownership_documents" type="file" required>
                                    <span class="text-danger is-invalid ownership_documents_err"></span>
                                </div> --}}

                                <div class="col-md-4">
                                    <label class="col-form-label" for="existing_water_bill">Existing Water Bill / विद्यमान पाणी बिल<span class="text-danger">*</span></label>
                                    <input class="form-control" id="existing_water_bill" name="existing_water_bill" type="file" required>
                                    <span class="text-danger is-invalid existing_water_bill_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="tax_bill_or_transfer_order">Property Tax Bill / Property tax Name Change Transfer Order. / मालमत्ता कराचे देयक / मालमत्ता हस्तांतरण आदेश. <span class="text-danger">*</span></label>
                                    <input class="form-control" id="tax_bill_or_transfer_order" name="tax_bill_or_transfer_order" type="file" required>
                                    <span class="text-danger is-invalid tax_bill_or_transfer_order_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="stamp_paper_or_noobjection_cert">500 Bond Stamp Paper / No Objection Certificate from Existing Connection Holder / विद्यमान नळ धारका कडुन 500 रु. चे करारनामा स्टँम्प पेपर / ना हरकत प्रमाणपत्र <span class="text-danger">*</span></label>
                                    <input class="form-control" id="stamp_paper_or_noobjection_cert" name="stamp_paper_or_noobjection_cert" type="file" required>
                                    <span class="text-danger is-invalid stamp_paper_or_noobjection_cert_err"></span>
                                </div>
                               
                                <div class="col-md-4">
                                    <label class="col-form-label" for="electricity_bill_or_pan_card">Aadhar Card / Electricity Bill / Pan Card. / आधार कार्ड / वीज बिल / पॅन कार्ड<span class="text-danger">*</span></label>
                                    <input class="form-control" id="electricity_bill_or_pan_card" name="electricity_bill_or_pan_card" type="file" required>
                                    <span class="text-danger is-invalid electricity_bill_or_pan_card_err"></span>
                                </div>
                               

                               <div class="col-md-4" id="upload_section" style="display:none;">
                            
                                <label class="col-form-label" for="comment">Upload Application In Prescribed Format<span class="text-danger">*</span></label>
                                <input class="form-control" id="application_document" name="application_document" type="file" required>
                                <span class="text-danger is-invalid comment_err"></span>
                           
                        </div>


                                <label class="col-form-label" for="is_correct_info">Declaration / घोषणापत्र:</label>
                                <div class="col-md-12">
                                    <div class="form-check d-flex align-items-start">
                                        <input type="checkbox" class="form-check-input mt-1" id="is_correct_info" name="is_correct_info" value="yes" 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="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>
                        {{-- <div class="card-footer">
                            <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); // 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);
                    // $('#connection_no').val(decryptedData['connectionDetails'].Water_Connection_Number);
                    // $('#complainants_full_name').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    // $('#existing_connection_detail').val(decryptedData['connectionDetails'].Connection_Type);
                    // // $('#new_owner_name').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    // $('#unauthorized_connection_address').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    // // $('#address').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    // $('#plot_no').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    // // $('#house_no').val(decryptedData['connectionDetails'].Water_Connection_Usage);
                    // $('#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);
                    // $('#owner_add').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    // $('#ward').val(decryptedData['connectionDetails'].Ward);

                    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);
            }
        });
    });

    const validateForm = function(form, requiredFields, email) {
        let err = [];
        const formElements = form.elements;

        requiredFields.forEach(val => {
            // remove previous errors
            const errEl = document.querySelector(`.${val}_err`);
            if (errEl) errEl.innerHTML = '';

            const value = formElements[val].value.trim();

            // Validate all required fields
            if (value == '') err.push([val, 'This field is required']);

            // Validate email field
            if (email && value == email) {
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // regular expression for email
                if (!emailPattern.test(value)) {
                    err.push([val, 'Invalid email format']);
                };
            };
        });

        // display all error data
        err.forEach((val, ind) => {
            const errEl = document.querySelector(`.${val[0]}_err`);
            if (errEl) errEl.innerHTML = val[1];
        });

        return err.length > 0; // return true if there are errors
    };

    // document.getElementById('saveAndPrintBtn').addEventListener('click', function() {
    //     const form = document.getElementById('addForm');
    //     const requiredFields = ['applicant_name', 'address', 'mobile_no', 'aadhar_no', 'connection_no', 'Property_Owner_Name', 'Full_Address_Of_The_Property', 'house_no', 'application_documents'];
    //     // if (validateForm(form, requiredFields, 'email_id')) return;

    //     // document.getElementById('upload_section').style.display = 'block';
    //     document.getElementById('card-footer').style.display = 'block';

    //     // ['existing_tap_con_details', 'unauthorized_is_tenant', 'criminal_judicial_issue', 'existing_top_con_unautorized'].forEach(function(id) {
    //     //     var select = document.getElementById(id);
    //     //     var selectedDiv = document.getElementById(id + '_selected');
    //     //     if (select && selectedDiv) {
    //     //         var selectedText = select.options[select.selectedIndex] ? select.options[select.selectedIndex].text : '';
    //     //         selectedDiv.textContent = 'Selected: ' + selectedText;
    //     //         selectedDiv.classList.remove('d-none');
    //     //         // select.setAttribute('disabled', '');
    //     //         select.style.display = 'none';
    //     //     }
    //     // });

    //     const addContainer = document.getElementById('addContainer');
    //     if (!addContainer) return;
    //     const printContainerClone = addContainer.cloneNode(true);
    //     printContainerClone.style.fontSize = '16px';
    //     printContainerClone.style.lineHeight = '1.4';
    //     printContainerClone.style.padding = '20px';
    //     printContainerClone.style.margin = '0 auto';
    //     printContainerClone.style.background = '#fff';
    //     printContainerClone.style.width = '210mm';
    //     printContainerClone.style.minHeight = '297mm';
    //     printContainerClone.style.boxSizing = 'border-box';
    //     Array.from(printContainerClone.querySelectorAll('*')).forEach(el => {
    //         el.style.fontSize = '16px';
    //         el.style.margin = '4px 0';
    //     });
    //     const printTitle = document.createElement('h2');
    //     printTitle.style.textAlign = 'center';
    //     printTitle.style.marginBottom = '18px';
    //     printTitle.style.fontSize = '18px';
    //     printTitle.textContent = 'Complaint Of Illegal Water Connection';
    //     printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);
    //     Array.from(printContainerClone.querySelectorAll('button')).forEach(btn => btn.remove());
    //     Array.from(printContainerClone.querySelectorAll('.card')).forEach(card => {
    //         card.style.background = 'white';
    //         card.style.boxShadow = 'none';
    //         card.style.border = '1px solid #ccc';
    //         card.style.marginBottom = '12px';
    //         card.style.padding = '12px';
    //     });
    //     Array.from(printContainerClone.querySelectorAll('input[type="file"]')).forEach(input => {
    //         const parent = input.parentNode;
    //         const fileName = input.files && input.files.length > 0 ? input.files[0].name : 'No file chosen';
    //         const fileInfo = document.createElement('div');
    //         fileInfo.textContent = 'Selected file: ' + fileName;
    //         parent.appendChild(fileInfo);
    //         input.style.display = 'none';
    //     });

    //     Array.from(printContainerClone.querySelectorAll('select')).forEach(select => {
    //         const selected = select.options[select.selectedIndex];
    //         const info = document.createElement('div');
    //         info.textContent = 'Selected: ' + (selected ? selected.text : '');
    //         select.parentNode.appendChild(info);
    //         select.style.display = 'none';
    //     });

    //     Array.from(printContainerClone.querySelectorAll('.selected-value')).forEach(div => {
    //         div.classList.remove('d-none');
    //     });

    //     Array.from(printContainerClone.querySelectorAll('input[type="checkbox"]')).forEach(checkbox => {
    //         const info = document.createElement('div');
    //         info.textContent = checkbox.checked ? 'Checked' : 'Not checked';
    //         checkbox.parentNode.appendChild(info);
    //         checkbox.style.display = 'none';
    //     });
    //     let printContainer = document.getElementById('printContainer');
    //     if (!printContainer) {
    //         printContainer = document.createElement('div');
    //         printContainer.id = 'printContainer';
    //         printContainer.style.position = 'fixed';
    //         printContainer.style.left = '-9999px';
    //         document.body.appendChild(printContainer);
    //     }
    //     printContainer.innerHTML = '';
    //     printContainer.appendChild(printContainerClone);
    //     html2canvas(printContainerClone, {
    //         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 pageWidth = pdf.internal.pageSize.getWidth();
    //         const pageHeight = pdf.internal.pageSize.getHeight();
    //         const margin = 10;
    //         const pdfWidth = pageWidth - margin * 2;
    //         const pdfHeight = pageHeight - margin * 2;
    //         pdf.addImage(imgData, 'JPEG', margin, margin, pdfWidth, pdfHeight);
    //         const pdfBlob = pdf.output('blob');
    //         if (pdfBlob.size > 2 * 1024 * 1024) {
    //             alert('Warning: PDF size is greater than 2 MB. Please reduce content or try again.');
    //         }
    //         pdf.save('Complaint Of Illegal Water Connection.pdf');
    //         document.getElementById('saveAndPrintBtn').style.display = 'none';
    //     });
    // });


document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const form = document.getElementById('addForm');
    const fileInput = document.getElementById('application_document');

    // 1️⃣ Temporarily remove 'required' from file input
    fileInput.removeAttribute('required');

    // 2️⃣ Custom validation
    let valid = true;

    // List of fields and error messages
    const errors = {
        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',
        total_connection: 'Total Connection is Required',
        property_no: 'Property No is Required',
        existing_water_bill: 'Existing Water Bill is Required',
        tax_bill_or_transfer_order: 'Tax Bill is Required',
        stamp_paper_or_noobjection_cert: 'Stamp Paper is Required',
        electricity_bill_or_pan_card: 'Electricity Bill is Required',
        Water_Connection_Size_Count: 'Connection is Required',
        is_correct_info: 'Please accept the Declaration'
    };

    // 🔹 Clear previous error messages
    Object.keys(errors).forEach(key => {
        const span = document.querySelector(`.${key}_err`);
        if (span) span.textContent = '';
    });

    // 🔹 Validate all required fields
    Object.keys(errors).forEach(key => {
        const field = document.getElementById(key);
        if (field) {
            if ((field.type === 'checkbox' && !field.checked) ||
                (!field.value.trim() && field.type !== 'checkbox')) {
                valid = false;
                const span = document.querySelector(`.${key}_err`);
                if (span) {
                    span.textContent = errors[key];
                    span.style.color = 'red';
                }
            }
        }
    });

    if (!valid) {
        // Restore 'required' for file input and stop
        fileInput.setAttribute('required', 'required');
        return;
    }

    // ✅ If valid, show upload and footer sections
    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);

    // ❌ Remove upload section from print version
    const uploadSectionInClone = printClone.querySelector('#upload_section');
    if (uploadSectionInClone) uploadSectionInClone.remove();

    // ✅ Replace Water Connection Type dropdown with readonly textbox (no duplication)
    const originalSelect = document.getElementById('Water_Connection_Size_Count');
    if (originalSelect) {
        const selectedText = originalSelect.options[originalSelect.selectedIndex].text;

        // Find the same select inside the cloned version
        const clonedSelect = printClone.querySelector('#Water_Connection_Size_Count');
        if (clonedSelect) {
            const textBox = document.createElement('input');
            textBox.type = 'text';
            textBox.className = 'form-control';
            textBox.value = selectedText;
            textBox.setAttribute('readonly', true);
            textBox.style.background = '#f9f9f9';
            textBox.style.border = '1px solid #ccc';

            // Replace dropdown with the textbox
            clonedSelect.parentNode.replaceChild(textBox, clonedSelect);
        }
    }

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

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

    // 📜 Title
    const printTitle = document.createElement('h2');
    printTitle.style.textAlign = 'center';
    printTitle.style.marginBottom = '18px';
    printTitle.style.fontSize = '18px';
    printTitle.textContent = 'Certificate of Water Change Ownership';
    printClone.insertBefore(printTitle, printClone.firstChild);

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

    // Ensure selected-value divs are visible if any
    Array.from(printClone.querySelectorAll('.selected-value')).forEach(div => {
        div.classList.remove('d-none');
    });

    // 📄 Prepare hidden print container
    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: 2,
        useCORS: true,
        allowTaint: true,
        logging: false
    }).then(canvas => {
        const imgData = canvas.toDataURL('image/jpeg', 0.9);
        const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
        const margin = 10;
        const pageWidth = pdf.internal.pageSize.getWidth() - margin * 2;
        const pageHeight = pdf.internal.pageSize.getHeight() - margin * 2;
        pdf.addImage(imgData, 'JPEG', margin, margin, pageWidth, pageHeight);
        pdf.save('Water_Change_Ownership_Certificate.pdf');

        document.getElementById('saveAndPrintBtn').style.display = 'none';
    }).catch(err => console.error('PDF generation failed:', err));

    // ✅ Restore 'required' for file input
    fileInput.setAttribute('required', 'required');
});




</script>

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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('water-change-ownership.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 numbers for specific fields
function allowOnlyNumbers(e) {
    // Allow control keys: backspace, delete, tab, escape, enter, arrows
    if ([8, 9, 13, 27, 46, 37, 38, 39, 40].includes(e.keyCode)) return;

    // Only digits 0-9 (top row and numpad)
    if ((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
}

// Prevent pasting non-numeric content
function preventPasteNonNumbers(e) {
    const paste = (e.clipboardData || window.clipboardData).getData('text');
    if (/[^0-9]/.test(paste)) {
        e.preventDefault();
    }
}

// Apply numeric restriction to fields
['total_connection', 'property_no'].forEach(id => {
    const field = document.getElementById(id);
    if (field) {
        field.addEventListener('keydown', allowOnlyNumbers);
        field.addEventListener('paste', preventPasteNonNumbers);
    }
});
</script>

