<x-admin.layout>
    <x-slot name="title">Complaint Of Illegal Water Connection / अनधिकृत नळ जोडणी तक्रार</x-slot>
    <x-slot name="heading">Complaint Of Illegal Water Connection / अनधिकृत नळ जोडणी तक्रार</x-slot>

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

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

                    <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="mb-3 row">
                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name">Complainant's 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"  readonly>
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>

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

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

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

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

                            <!--kisroi add the code -->
                            <br>
                             <div class="card-header">
                                    <h4 class="card-title">Add Details</h4>
                                </div>



                                 <div class="col-md-4">
                            <label class="col-form-label" for="total_connection">Total illegal connections<span class="text-danger">*</span></label>
                            <input class="form-control" id="total_connection" name="total_connection" type="text" placeholder="Enter total illegal connections" >
                            <span class="text-danger is-invalid total_connection_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="info_unauth_con">Information about Unauthorized connection</label>
                            <input class="form-control" id="info_unauth_con" name="info_unauth_con" type="text" placeholder="Enter Information about Unauthorized connection">
                            <span class="text-danger is-invalid info_unauth_con_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="plot_no">Plot NO</label>
                            <input class="form-control" id="plot_no" name="plot_no" type="text" placeholder="Enter Plot NO">
                            <span class="text-danger is-invalid plot_no_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="house_no">House Number / घर नं <span class="text-danger">*</span></label>
                            <input class="form-control" id="house_no" name="house_no" type="text" placeholder="Enter House Number" >
                            <span class="text-danger is-invalid house_no_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="landmark">Landmark / महत्त्वाची खूण</label>
                            <input class="form-control" name="landmark" id="landmark" placeholder="Enter Landmark">
                            <span class="text-danger is-invalid landmark_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="address_property">Full Address Of Property<span class="text-danger">*</span></label>
                            <textarea class="form-control" id="address_property" name="address_property" cols="2" type="text" placeholder="Enter Full Address Of Property" ></textarea>
                            <span class="text-danger is-invalid address_property_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="existing_tap_con_details">Existing tap connection details/ विद्यमान टॅप कनेक्शन तपशील</label>
                            <select class="form-select" name="existing_tap_con_details" id="existing_tap_con_details">
                                <option value="" selected>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 existing_tap_con_details_err"></span>
                            <div class="selected-value d-none" id="existing_tap_con_details_selected"></div>
                        </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" >
                            <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">
                                Water Connection Size <span class="text-danger">*</span>
                            </label>
                            <select class="form-control" id="Water_Connection_Size" name="Water_Connection_Size">
                                <option value="">-- Select --</option>
                                <option value="151588">घरगुती 1 इंच</option>
                                <option value="78765">घरगुती 1/2 इंच</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="existing_top_con_unautorized">Existing tap connections are unauthorized./विद्यमान टॅप कनेक्शन अनधिकृत आहेत</label>
                            <select class="form-select" name="existing_top_con_unautorized" id="existing_top_con_unautorized">
                                <option value="" selected>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 existing_top_con_unautorized_err"></span>
                            <div class="selected-value d-none" id="existing_top_con_unautorized_selected"></div>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="unauthorized_is_tenant">Is the holder of unauthorized tap connection a tenant/ अनधिकृत नळ कनेक्शन धारक भाडेकरू आहे का?</label>
                            <select class="form-select" name="unauthorized_is_tenant" id="unauthorized_is_tenant">
                                <option value="" selected>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 unauthorized_is_tenant_err"></span>
                            <div class="selected-value d-none" id="unauthorized_is_tenant_selected"></div>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="criminal_judicial_issue">Criminal or Judicial issues about existing tap connection/विद्यमान नळ कनेक्शनबद्दल फौजदारी किंवा न्यायालयीन मुद्दे</label>
                            <select class="form-select" name="criminal_judicial_issue" id="criminal_judicial_issue">
                                <option value="" selected>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 class="selected-value d-none" id="criminal_judicial_issue_selected"></div>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="application_documents">Upload Document/Photo / दस्तऐवज/फोटो अपलोड करा<span class="text-danger">*</span></label>
                            <input class="form-control" id="application_documents" name="application_documents" type="file" >
                            <span class="text-danger is-invalid application_documents_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="comments" name="comments" type="file" >
                                <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" >
                                <label class="form-check-label ms-2" for="is_correct_info">
                                    "All Information provided above is correct and shall be fully responsible for any
                                    discrepancy. "
                                </label>
                            </div>
                            {{-- <span class="text-danger is-invalid is_correct_info_err"></span> --}}
                           <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>
            </div>
            <!--kkishrii end the code-->




                            
                        </div>
                </div>
            </div>



            {{-- <div class="card">
                <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-4">
                            <label class="col-form-label" for="total_connection">Total illegal connections<span class="text-danger">*</span></label>
                            <input class="form-control" id="total_connection" name="total_connection" type="text" placeholder="Enter total illegal connections" >
                            <span class="text-danger is-invalid total_connection_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="info_unauth_con">Information about Unauthorized connection</label>
                            <input class="form-control" id="info_unauth_con" name="info_unauth_con" type="text" placeholder="Enter Information about Unauthorized connection">
                            <span class="text-danger is-invalid info_unauth_con_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="plot_no">Plot NO</label>
                            <input class="form-control" id="plot_no" name="plot_no" type="text" placeholder="Enter Plot NO">
                            <span class="text-danger is-invalid plot_no_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="house_no">House Number / घर नं <span class="text-danger">*</span></label>
                            <input class="form-control" id="house_no" name="house_no" type="text" placeholder="Enter House Number" >
                            <span class="text-danger is-invalid house_no_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="landmark">Landmark / महत्त्वाची खूण</label>
                            <input class="form-control" name="landmark" id="landmark" placeholder="Enter Landmark">
                            <span class="text-danger is-invalid landmark_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="address_property">Full Address Of Property<span class="text-danger">*</span></label>
                            <textarea class="form-control" id="address_property" name="address_property" cols="2" type="text" placeholder="Enter Full Address Of Property" ></textarea>
                            <span class="text-danger is-invalid address_property_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="existing_tap_con_details">Existing tap connection details/ विद्यमान टॅप कनेक्शन तपशील</label>
                            <select class="form-select" name="existing_tap_con_details" id="existing_tap_con_details">
                                <option value="" selected>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 existing_tap_con_details_err"></span>
                            <div class="selected-value d-none" id="existing_tap_con_details_selected"></div>
                        </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" >
                            <span class="text-danger is-invalid Water_Connection_Size_err"></span>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="existing_top_con_unautorized">Existing tap connections are unauthorized./विद्यमान टॅप कनेक्शन अनधिकृत आहेत</label>
                            <select class="form-select" name="existing_top_con_unautorized" id="existing_top_con_unautorized">
                                <option value="" selected>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 existing_top_con_unautorized_err"></span>
                            <div class="selected-value d-none" id="existing_top_con_unautorized_selected"></div>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="unauthorized_is_tenant">Is the holder of unauthorized tap connection a tenant/ अनधिकृत नळ कनेक्शन धारक भाडेकरू आहे का?</label>
                            <select class="form-select" name="unauthorized_is_tenant" id="unauthorized_is_tenant">
                                <option value="" selected>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 unauthorized_is_tenant_err"></span>
                            <div class="selected-value d-none" id="unauthorized_is_tenant_selected"></div>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="criminal_judicial_issue">Criminal or Judicial issues about existing tap connection/विद्यमान नळ कनेक्शनबद्दल फौजदारी किंवा न्यायालयीन मुद्दे</label>
                            <select class="form-select" name="criminal_judicial_issue" id="criminal_judicial_issue">
                                <option value="" selected>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 class="selected-value d-none" id="criminal_judicial_issue_selected"></div>
                        </div>

                        <div class="col-md-4">
                            <label class="col-form-label" for="application_documents">Upload Document/Photo / दस्तऐवज/फोटो अपलोड करा<span class="text-danger">*</span></label>
                            <input class="form-control" id="application_documents" name="application_documents" type="file" >
                            <span class="text-danger is-invalid application_documents_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="comments" name="comments" type="file" >
                                <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 shall be fully responsible for any
                                    discrepancy. "
                                </label>
                            </div>
                            <span class="text-danger is-invalid is_correct_info_err"></span>
                        </div>

                    </div>
                </div>
                <div class="form-group" style="text-align: center;">
                    <button type="button" id="saveAndPrintBtn" class="btn btn-success">Save and Print</button>
                </div>
                <div class="card-footer" id="card-footer" style="display:none;">
                    <button type="submit" class="btn btn-primary" id="addSubmit">Submit</button>
                    <button type="reset" class="btn btn-warning">Reset</button>
                </div>
                </form>
            </div> --}}
        </div>
    </div>

</x-admin.layout>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
{{-- <script>
    $('#searchdetails').on('click', function(e) {
        e.preventDefault();

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

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

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


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

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

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

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

    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'];
        const requiredFields = ['applicant_name', 'address', 'mobile_no', 'aadhar_no'];
        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';
        });
    });

    function updateSelectedValue(selectId) {
        var select = document.getElementById(selectId);
        var selectedText = select.options[select.selectedIndex] ? select.options[select.selectedIndex].text : '';
        var selectedDiv = document.getElementById(selectId + '_selected');
        if (selectedDiv) {
            selectedDiv.textContent = 'Selected: ' + selectedText;
        }
    }

    ['existing_tap_con_details', 'unauthorized_is_tenant', 'criminal_judicial_issue', 'existing_top_con_unautorized'].forEach(function(id) {
        document.getElementById(id).addEventListener('change', function() {
            updateSelectedValue(id);
        });
        updateSelectedValue(id);
    });
</script> --}}




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

   
    fileInput.removeAttribute('required');

  
    if (!form.checkValidity()) {
        form.reportValidity();   
        fileInput.setAttribute('required', 'required'); 
        return;
    }

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

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

    const printClone = addContainer.cloneNode(true);
    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';



    Array.from(printClone.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 = 'Certificate of water illegal connection';
    printClone.insertBefore(printTitle, printClone.firstChild);

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

   
    Array.from(printClone.querySelectorAll('.selected-value')).forEach(div => {
        div.classList.remove('d-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(printClone);

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

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

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

       
        pdf.save('Water-Illegal-ConnectionCertificate.pdf');

       
        document.getElementById('saveAndPrintBtn').style.display = 'none';
    });

    
    fileInput.setAttribute('required', 'required');
});
</script> --}}

{{-- <script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    // ✅ Custom validation messages for each field
    const messages = {
  
        total_connection:'Total Connection is Required',
        zone: 'Zone is Required',
        house_no:'House No is Required',
        address_property:'Address Property is Required',
        application_documents:'Application Documents is Required',
        is_correct_info:'Please Accept the Declaration',
        Water_Connection_Size:'Water Connection Size is Required',
        
    };

    let isValid = true;

   
    form.querySelectorAll('.error-message').forEach(e => e.remove());

    // 2️⃣ Loop through required fields and show inline errors
    Object.keys(messages).forEach(name => {
        const fields = form.querySelectorAll(`[name="${name}"]`);
        if (!fields || fields.length === 0) return;

        let errorText = '';

        // ✅ Handle checkboxes (group)
        if (fields[0].type === 'checkbox') {
            const checked = Array.from(fields).some(f => f.checked);
            if (!checked) errorText = messages[name];
        } else {
            // Input, select, textarea
            const value = fields[0].value.trim();
            if (!value) errorText = messages[name];
        }

        if (errorText) {
                isValid = false;
                const error = document.createElement('div');
                error.className = 'error-message text-danger mt-1';
                error.style.fontSize = '13px';
                error.textContent = errorText;

                if (fields[0].type === 'checkbox') {
                    // Append error just below the checkbox
                    const wrapper = fields[0].closest('.col-md-12') || fields[0].parentNode;
                    wrapper.appendChild(error);
                } else {
                    // Append for normal inputs/selects
                    const parent = fields[fields.length - 1].closest('.form-group') || fields[fields.length - 1].parentNode;
                    parent.appendChild(error);
                }
            }
        });


    

    // Stop if validation fails
    if (!isValid) {
        const firstError = form.querySelector('.error-message');
        if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        return;
    }

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

    const cardFooter = document.getElementById('card-footer');
    if (cardFooter) cardFooter.style.display = 'block';

    // 4️⃣ Clone content for PDF
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');

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

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

    // Optional title
    const printTitle = document.createElement('h2');
    printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
    printTitle.textContent = 'Certificate of Water Illegal Connection';
    printClone.insertBefore(printTitle, printClone.firstChild);

    // Remove buttons from clone
    printClone.querySelectorAll('button').forEach(btn => btn.remove());

    // Style cards inside clone
    printClone.querySelectorAll('.card').forEach(card => {
        Object.assign(card.style, {
            background: 'white',
            boxShadow: 'none',
            border: '1px solid #ccc',
            marginBottom: '12px',
            padding: '12px'
        });
    });

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

    // 5️⃣ Hidden container for html2canvas
    let printContainer = document.getElementById('printContainer');
    if (!printContainer) {
        printContainer = document.createElement('div');
        printContainer.id = 'printContainer';
        printContainer.style.position = 'fixed';
        printContainer.style.left = '-9999px';
        document.body.appendChild(printContainer);
    }
    printContainer.innerHTML = '';
    printContainer.appendChild(printClone);

    // 6️⃣ Generate PDF
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);

            if (!window.jspdf || !window.jspdf.jsPDF) {
                return alert('jsPDF library not loaded!');
            }

            const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
            const margin = 10;

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

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

            pdf.save('WaterIllegalConnectionCertificate.pdf');

            const saveBtn = document.getElementById('saveAndPrintBtn');
            if (saveBtn) saveBtn.style.display = 'none';
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 100);
});
</script> --}}


{{-- <script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    // ✅ Custom validation messages
    const messages = {
        total_connection: 'Total Connection is Required',
        zone: 'Ward is Required',
        house_no: 'House No is Required',
        address_property: 'Address Property is Required',
        application_documents: 'Application Documents is Required',
        is_correct_info: 'Please Accept the Declaration',
        Water_Connection_Size: 'Water Connection Size is Required',
    };

    let isValid = true;

    // Remove previous errors
    form.querySelectorAll('.error-message').forEach(e => e.remove());

    // Validate each field
    Object.keys(messages).forEach(name => {
        const fields = form.querySelectorAll(`[name="${name}"]`);
        if (!fields || fields.length === 0) return;

        let errorText = '';

        if (fields[0].type === 'checkbox') {
            const checked = Array.from(fields).some(f => f.checked);
            if (!checked) errorText = messages[name];
        } else {
            const value = fields[0].value.trim();
            if (!value) errorText = messages[name];
        }

        if (errorText) {
            isValid = false;
            const error = document.createElement('div');
            error.className = 'error-message text-danger mt-1';
            error.style.fontSize = '13px';
            error.textContent = errorText;

            if (fields[0].type === 'checkbox') {
                const wrapper = fields[0].closest('.col-md-12') || fields[0].parentNode;
                wrapper.appendChild(error);
            } else {
                const parent = fields[fields.length - 1].closest('.form-group') || fields[fields.length - 1].parentNode;
                parent.appendChild(error);
            }
        }
    });

    if (!isValid) {
        const firstError = form.querySelector('.error-message');
        if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        return;
    }

    // Show upload section & footer in the form (optional)
    const uploadSection = document.getElementById('upload_section');
    if (uploadSection) uploadSection.style.display = 'block';

    const cardFooter = document.getElementById('card-footer');
    if (cardFooter) cardFooter.style.display = 'block';

    // Clone content for PDF
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');

    const printClone = addContainer.cloneNode(true);

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

    // Hide upload section in PDF
    printClone.querySelectorAll('#upload_section').forEach(el => el.style.display = 'none');

    // Remove buttons
    printClone.querySelectorAll('button').forEach(btn => btn.remove());

    // Style cards inside clone
    printClone.querySelectorAll('.card').forEach(card => {
        Object.assign(card.style, {
            background: 'white',
            boxShadow: 'none',
            border: '1px solid #ccc',
            marginBottom: '12px',
            padding: '12px'
        });
    });

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

    // Optional title at top
    const printTitle = document.createElement('h2');
    printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
    printTitle.textContent = 'Certificate of Water Illegal Connection';
    printClone.insertBefore(printTitle, printClone.firstChild);

    // Create hidden container for html2canvas
    let printContainer = document.getElementById('printContainer');
    if (!printContainer) {
        printContainer = document.createElement('div');
        printContainer.id = 'printContainer';
        printContainer.style.position = 'fixed';
        printContainer.style.left = '-9999px';
        document.body.appendChild(printContainer);
    }
    printContainer.innerHTML = '';
    printContainer.appendChild(printClone);

    // Generate PDF
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);

            if (!window.jspdf || !window.jspdf.jsPDF) {
                return alert('jsPDF library not loaded!');
            }

            const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
            const margin = 10;

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

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

            pdf.save('WaterIllegalConnectionCertificate.pdf');

            // Hide save button after PDF
            const saveBtn = document.getElementById('saveAndPrintBtn');
            if (saveBtn) saveBtn.style.display = 'none';
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 100);
});
</script> --}}

{{-- <script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    // ✅ Validation messages
    const messages = {
        total_connection: 'Total Connection is Required',
        zone: 'Ward is Required',
        house_no: 'House No is Required',
        address_property: 'Address Property is Required',
        application_documents: 'Application Documents is Required',
        is_correct_info: 'Please Accept the Declaration',
        Water_Connection_Size: 'Water Connection Size is Required',
    };

    let isValid = true;
    form.querySelectorAll('.error-message').forEach(e => e.remove());

    Object.keys(messages).forEach(name => {
        const fields = form.querySelectorAll(`[name="${name}"]`);
        if (!fields || fields.length === 0) return;

        let errorText = '';
        if (fields[0].type === 'checkbox') {
            const checked = Array.from(fields).some(f => f.checked);
            if (!checked) errorText = messages[name];
        } else {
            const value = fields[0].value.trim();
            if (!value) errorText = messages[name];
        }

        if (errorText) {
            isValid = false;
            const error = document.createElement('div');
            error.className = 'error-message text-danger mt-1';
            error.style.fontSize = '13px';
            error.textContent = errorText;
            const parent = fields[fields.length - 1].closest('.form-group') || fields[fields.length - 1].parentNode;
            parent.appendChild(error);
        }
    });

    if (!isValid) {
        const firstError = form.querySelector('.error-message');
        if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        return;
    }

    // ✅ Fetch only the selected value ("Yes" or "No") and show inside box
    const tapSelect = document.getElementById('existing_tap_con_details');
    const tapSelectedDiv = document.getElementById('existing_tap_con_details_selected');
    if (tapSelect && tapSelectedDiv) {
        const selectedValue = tapSelect.options[tapSelect.selectedIndex].text;
        tapSelectedDiv.textContent = selectedValue; // ✅ only "Yes" or "No"
        tapSelectedDiv.classList.remove('d-none');
        tapSelectedDiv.classList.add('textbox-style');
    }

    // ======== PDF generation part ========
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');
    const printClone = addContainer.cloneNode(true);

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

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

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

    const printTitle = document.createElement('h2');
    printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
    printTitle.textContent = 'Certificate of Water Illegal Connection';
    printClone.insertBefore(printTitle, printClone.firstChild);

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

    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);

            const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
            const margin = 10;

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

            pdf.save('WaterIllegalConnectionCertificate.pdf');
            const saveBtn = document.getElementById('saveAndPrintBtn');
            if (saveBtn) saveBtn.style.display = 'none';
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 100);
});
</script> --}}




{{-- <script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    // ✅ Validation messages
    const messages = {
        total_connection: 'Total Connection is Required',
        zone: 'Ward is Required',
        house_no: 'House No is Required',
        address_property: 'Address Property is Required',
        application_documents: 'Application Documents is Required',
        is_correct_info: 'Please Accept the Declaration',
        Water_Connection_Size: 'Water Connection Size is Required',
    };

    let isValid = true;
    form.querySelectorAll('.error-message').forEach(e => e.remove());

    Object.keys(messages).forEach(name => {
        const fields = form.querySelectorAll(`[name="${name}"]`);
        if (!fields || fields.length === 0) return;

        let errorText = '';
        if (fields[0].type === 'checkbox') {
            const checked = Array.from(fields).some(f => f.checked);
            if (!checked) errorText = messages[name];
        } else {
            const value = fields[0].value.trim();
            if (!value) errorText = messages[name];
        }

        if (errorText) {
            isValid = false;
            const error = document.createElement('div');
            error.className = 'error-message text-danger mt-1';
            error.style.fontSize = '13px';
            error.textContent = errorText;

            // ✅ Place error below correct field
            let parent;
            if (fields[0].type === 'checkbox') {
                parent = fields[0].closest('.col-md-12') || fields[0].parentNode;
            } else {
                parent = fields[fields.length - 1].closest('.form-group') || fields[fields.length - 1].parentNode;
            }
            parent.appendChild(error);
        }
    });

    if (!isValid) {
        const firstError = form.querySelector('.error-message');
        if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        return;
    }

    // ✅ Replace dropdowns with selected values (inline box style)
    const selectFields = [
        { id: 'existing_tap_con_details', boxId: 'existing_tap_con_details_selected' },
        { id: 'existing_top_con_unautorized', boxId: 'existing_top_con_unautorized_selected' },
        { id: 'unauthorized_is_tenant', boxId: 'unauthorized_is_tenant_selected' },
        { id: 'criminal_judicial_issue', boxId: 'criminal_judicial_issue_selected' },
        { id: 'Water_Connection_Size', boxId: 'Water_Connection_Size_selected' },
    ];

    selectFields.forEach(({ id, boxId }) => {
        const select = document.getElementById(id);
        if (!select) return;

        let selectedDiv = document.getElementById(boxId);
        if (!selectedDiv) {
            selectedDiv = document.createElement('div');
            selectedDiv.id = boxId;
            selectedDiv.className = 'selected-value';
            select.insertAdjacentElement('afterend', selectedDiv);
        }

        const selectedValue = select.options[select.selectedIndex]?.text || '';
        if (!selectedValue || selectedValue === 'Select option' || selectedValue === '-- Select --') return;

        // ✅ Show inline styled textbox
        selectedDiv.textContent = selectedValue;
        selectedDiv.classList.remove('d-none');
        Object.assign(selectedDiv.style, {
            border: '1px solid #ccc',
            padding: '6px 8px',
            borderRadius: '4px',
            fontSize: '14px',
            backgroundColor: '#f8f9fa',
            width: '100%',
            marginTop: '4px'
        });

        select.style.display = 'none';
    });

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

    // ======== PDF generation ========
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');

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

    // Hide upload section + buttons while generating PDF
    printClone.querySelectorAll('#upload_section, #card-footer').forEach(el => el.style.display = 'none');
    printClone.querySelectorAll('button').forEach(btn => btn.remove());

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

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

    // Title
    const printTitle = document.createElement('h2');
    printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
    printTitle.textContent = 'Certificate of Water Illegal Connection';
    printClone.insertBefore(printTitle, printClone.firstChild);

    // Temporary 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
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
            const margin = 10;
            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );
            pdf.save('WaterIllegalConnectionCertificate.pdf');
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 100);
});
</script> --}}


<script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const saveBtn = this; // ✅ reference to button
    const form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    // ✅ Validation messages
    const messages = {
        total_connection: 'Total Connection is Required',
        zone: 'Ward is Required',
        house_no: 'House No is Required',
        address_property: 'Address Property is Required',
        application_documents: 'Application Documents is Required',
        is_correct_info: 'Please Accept the Declaration',
        Water_Connection_Size: 'Water Connection Size is Required',
    };

    let isValid = true;
    form.querySelectorAll('.error-message').forEach(e => e.remove());

    Object.keys(messages).forEach(name => {
        const fields = form.querySelectorAll(`[name="${name}"]`);
        if (!fields || fields.length === 0) return;

        let errorText = '';
        if (fields[0].type === 'checkbox') {
            const checked = Array.from(fields).some(f => f.checked);
            if (!checked) errorText = messages[name];
        } else {
            const value = fields[0].value.trim();
            if (!value) errorText = messages[name];
        }

        if (errorText) {
            isValid = false;
            const error = document.createElement('div');
            error.className = 'error-message text-danger mt-1';
            error.style.fontSize = '13px';
            error.textContent = errorText;

            let parent;
            if (fields[0].type === 'checkbox') {
                parent = fields[0].closest('.col-md-12') || fields[0].parentNode;
            } else {
                parent = fields[fields.length - 1].closest('.form-group') || fields[fields.length - 1].parentNode;
            }
            parent.appendChild(error);
        }
    });

    if (!isValid) {
        const firstError = form.querySelector('.error-message');
        if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        return;
    }

    // ✅ Hide button after successful validation
    saveBtn.style.display = 'none';

    // ✅ Replace dropdowns with selected values (inline box style)
    const selectFields = [
        { id: 'existing_tap_con_details', boxId: 'existing_tap_con_details_selected' },
        { id: 'existing_top_con_unautorized', boxId: 'existing_top_con_unautorized_selected' },
        { id: 'unauthorized_is_tenant', boxId: 'unauthorized_is_tenant_selected' },
        { id: 'criminal_judicial_issue', boxId: 'criminal_judicial_issue_selected' },
        { id: 'Water_Connection_Size', boxId: 'Water_Connection_Size_selected' },
    ];

    selectFields.forEach(({ id, boxId }) => {
        const select = document.getElementById(id);
        if (!select) return;

        let selectedDiv = document.getElementById(boxId);
        if (!selectedDiv) {
            selectedDiv = document.createElement('div');
            selectedDiv.id = boxId;
            selectedDiv.className = 'selected-value';
            select.insertAdjacentElement('afterend', selectedDiv);
        }

        const selectedValue = select.options[select.selectedIndex]?.text || '';
        if (!selectedValue || selectedValue === 'Select option' || selectedValue === '-- Select --') return;

        selectedDiv.textContent = selectedValue;
        selectedDiv.classList.remove('d-none');
        Object.assign(selectedDiv.style, {
            border: '1px solid #ccc',
            padding: '6px 8px',
            borderRadius: '4px',
            fontSize: '14px',
            backgroundColor: '#f8f9fa',
            width: '100%',
            marginTop: '4px'
        });

        select.style.display = 'none';
    });

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

    // ======== PDF generation ========
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');

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

    printClone.querySelectorAll('#upload_section, #card-footer').forEach(el => el.style.display = 'none');
    printClone.querySelectorAll('button').forEach(btn => btn.remove());

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

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

    const printTitle = document.createElement('h2');
    printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
    printTitle.textContent = 'Certificate of Water Illegal Connection';
    printClone.insertBefore(printTitle, printClone.firstChild);

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

    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
            const margin = 10;
            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );
            pdf.save('WaterIllegalConnectionCertificate.pdf');
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 100);
});
</script>
















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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('water-illegal-connection.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $('#preloader').css('opacity', '0.5');
                $('#preloader').css('visibility', 'visible');
            },
            success: function(data) {
                $("#addSubmit").prop('disabled', false);
                if (!data.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>
function allowStrictNumbers(e) {
    // Allow: backspace, delete, tab, escape, enter, arrows
    if ([8, 9, 13, 27, 46, 37, 38, 39, 40].includes(e.keyCode)) return;

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

function preventPasteNonNumbers(e) {
    const paste = (e.clipboardData || window.clipboardData).getData('text');
    // Block if anything other than digits
    if (/[^0-9]/.test(paste)) {
        e.preventDefault();
    }
}

// Apply strict validation to all three fields
['total_connection', 'plot_no', 'house_no'].forEach(id => {
    const field = document.getElementById(id);
    field.addEventListener('keydown', allowStrictNumbers);
    field.addEventListener('paste', preventPasteNonNumbers);
});
</script>
