<x-admin.layout>
    <x-slot name="title">Water connection repair permission/ जलजोडणी दुरुस्ती परवानगी</x-slot>
    <x-slot name="heading">Water connection repair permission/ जलजोडणी दुरुस्ती परवानगी</x-slot>
        <!-- Add Form -->
        <div class="row" id="addContainer">
            <div class="col-sm-12">
                <div class="card">
                    <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                        @csrf

                        <div class="card-header">
                            <h4 class="card-title">Add Details</h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-3 row">
                                <div class="col-md-4">
                                    <label class="col-form-label" for="water_connection_no">Name of the Owner / मालकाचे नाव<span class="text-danger">*</span></label>
                                    <input class="form-control" id="water_connection_no" name="water_connection_no" type="text" placeholder="Name of the Owner / मालकाचे नाव" required pattern="^[A-Za-z\s]+$"
                                title="Only letters and spaces are allowed">
                                    <span class="text-danger is-invalid water_connection_no_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="property_owner_name">Total Consumer No. / एकूण ग्राहक क्र.<span class="text-danger">*</span></label>
                                    <input class="form-control" id="property_owner_name" name="property_owner_name" type="text" placeholder="Enter Total Consumer No. / एकूण ग्राहक क्र." required onkeypress="return /[0-9]/.test(event.key)">
                                    <span class="text-danger is-invalid property_owner_name_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label for="col-form-label" class="comment">Consumer Number/ग्राहक संख्या<span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="comment" name="comment" placeholder="Enter Consumer Number/ग्राहक संख्या" required>
                                    <span class="text-danger is-invalid comment_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="mobile_no">Mobile Number / मोबाईल नंबर<span class="text-danger">*</span></label>
                                    <input class="form-control" id="mobile_no" name="mobile_no"  oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" type="text" placeholder="Enter Mobile Number / मोबाईल नंबर" required>
                                    <span class="text-danger is-invalid mobile_no_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="aadhar_no">Aadhar Card / आधार नंबर  <span class="text-danger">*</span></label>
                                    <input class="form-control" id="aadhar_no" name="aadhar_no"  oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" type="text" placeholder="Enter Aadhar Card / आधार नंबर " required>
                                    <span class="text-danger is-invalid aadhar_no_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="email_id"> Email Id  / ईमेल आयडी<span class="text-danger">*</span></label>
                                    <input class="form-control" id="email_id" name="email_id" type="email" placeholder="Enter Email Id  / ईमेल आयडी" required>
                                    <span class="text-danger is-invalid email_id_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="ward_area">Ward Area / प्रभाग क्षेत्र<span class="text-danger">*</span></label>
                                    <select class="form-select" name="ward_area" id="ward_area" required>
                                        <option value="">Select Ward Area</option>
                                        @foreach($wards as $ward)
                                        <option value="{{ $ward->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="plot_no">Plot Number / प्लॅाट नं किंवा हिस्सा नं <span class="text-danger">*</span></label>
                                    <input class="form-control" id="plot_no" name="plot_no" type="text" placeholder="Enter Plot Number" required>
                                    <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" required>
                                    <span class="text-danger is-invalid house_no_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="landmark">Landmark / जवळची खूण<span class="text-danger">*</span></label>
                                    <input class="form-control" id="landmark" name="landmark" type="text" placeholder="Enter Landmark" required>
                                    <span class="text-danger is-invalid landmark_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="address">Full Address Of The Property / मिळकतीचा संपुर्ण पत्ता  <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="address" id="address" cols="30" rows="2"  placeholder="Enter  Address" required></textarea>
                                    <span class="text-danger is-invalid address_err"></span>
                                </div>



                                <div class="col-md-4">
                                    <label class="col-form-label" for="resident_type">रहिवासी प्रकार <span class="text-danger">*</span></label>
                                    <select class="form-select" name="resident_type" id="resident_type" required>
                                        <option value="">Select option</option>
                                        <option value="निवासी">निवासी</option>
                                        <option value="अनिवासी">अनिवासी</option>
                                    </select>
                                    <span class="text-danger is-invalid resident_type_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="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 = ["2", "1.5", "1", "0.75", "0.5"];
                                        @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="current_connection_is_illegal">Currently Existed Tap Connection Unauthorized / मिळकतीस सध्या अस्तित्वात असलेले नळ कनेक्शन अनाधिकृत होते काय ?  <span class="text-danger">*</span></label>
                                    <select class="form-select" name="current_connection_is_illegal" id="current_connection_is_illegal" 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_illegal_err"></span>
                                </div> --}}

                                {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="applicant_is_on_rent">Is Applicant a Tenant / अर्जदार भाडेकरू आहे ?<span class="text-danger">*</span></label>
                                    <select class="form-select" name="applicant_is_on_rent" id="applicant_is_on_rent" 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_is_on_rent_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="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="current_existing_tap_type">Currently Existing Tap Connection Detail / मिळकतीस सध्या अस्तित्वात असलेल्या नळ कनेक्शनचा तपशील <span class="text-danger">*</span></label>
                                    <select class="form-select" name="current_existing_tap_type" id="current_existing_tap_type" 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 current_existing_tap_type_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="application_document">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 application_document_err"></span>
                                </div> --}}


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


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

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

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

</x-admin.layout>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>



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

    // Validation messages
    const messages = {
        water_connection_no: 'Owner Name is Required',
        property_owner_name: 'Total Consumer is Required',
        comment: 'Consumer No is Required',
        mobile_no: 'Mobile no is required',
        aadhar_no: 'Aadhaar no is required',
        email_id: 'Email ID is required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot No is Required',
        house_no: 'House No is Required',
        landmark: 'Landmark is Required',
        address: 'Address is Required',
        tap_size: 'Tap size is Required',
        is_correct_info: 'Please accept the declaration'
    };

    let isValid = true;

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

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

        let errorText = '';
        const val = (field.type === 'checkbox') ? field.checked : field.value.trim();

        if (!val) {
            errorText = messages[name];
        } else {
            if (name === 'mobile_no' && field.value.trim().length !== 10)
                errorText = 'Please enter 10 digit mobile no';
            if (name === 'aadhar_no' && field.value.trim().length !== 12)
                errorText = 'Please enter 12 digit Aadhaar no';
            if (name === 'email_id') {
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailPattern.test(field.value.trim()))
                    errorText = 'Please enter valid email';
            }
        }

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

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

    // ✅ Show sections
    document.getElementById('upload_section').style.display = 'block';
    document.getElementById('card-footer').style.display = 'block';
    // ✅ Hide Save & Print
    document.getElementById('saveAndPrintBtn').style.display = 'none';

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

    const printClone = addContainer.cloneNode(true);

    // Fill all input/select values into visible boxes (without changing design)
    printClone.querySelectorAll('input, select, textarea').forEach(el => {
        if (el.type === 'checkbox') {
            el.checked = el.checked;
        } else if (el.tagName === 'SELECT') {
            el.setAttribute('value', el.options[el.selectedIndex]?.text || '');
        } else {
            el.setAttribute('value', el.value);
        }
    });

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

    const title = document.createElement('h2');
    title.textContent = 'Certificate of Water Transfer Permission';
    title.style.cssText = 'text-align:center; margin-bottom:15px; font-size:17px;';
    printClone.insertBefore(title, printClone.firstChild);

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

    // Hidden container for print
    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 with visible input boxes (like screenshot)
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.9);
            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('CertificateofWaterTransferpermission.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 form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    const messages = {
        water_connection_no: 'Owner Name is Required',
        property_owner_name: 'Total Consumer is Required',
        comment: 'Consumer No is Required',
        mobile_no: 'Mobile no is required',
        aadhar_no: 'Aadhaar no is required',
        email_id: 'Email ID is required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot No is Required',
        house_no: 'House No is Required',
        landmark: 'Landmark is Required',
        address: 'Address is Required',
        tap_size: 'Tap size is Required',
        resident_type: 'Resident Type is Required',
        is_correct_info: 'Please accept the declaration'
    };

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

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

        let errorText = '';
        const val = (field.type === 'checkbox') ? field.checked : field.value.trim();

        if (!val) {
            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;
            field.parentNode.appendChild(error);
        }
    });

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

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

    // ✅ Step 1: Save current dropdown text before clone
    const dropdownData = {};
    form.querySelectorAll('select').forEach(sel => {
        const name = sel.getAttribute('name');
        dropdownData[name] = sel.options[sel.selectedIndex]?.text || '';
    });

    // ✅ Step 2: Clone content
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');
    const printClone = addContainer.cloneNode(true);

    // ✅ Step 3: Replace all form elements with readable text
    printClone.querySelectorAll('input, select, textarea').forEach(el => {
        const parent = el.parentNode;
        const span = document.createElement('span');
        span.style.border = '1px solid #ccc';
        span.style.display = 'block';
        span.style.padding = '6px 8px';
        span.style.borderRadius = '4px';
        span.style.minHeight = '30px';
        span.style.background = '#fff';

        if (el.tagName === 'SELECT') {
            const name = el.getAttribute('name');
            span.textContent = dropdownData[name] || '';
        } else if (el.type === 'checkbox') {
            span.textContent = el.checked ? 'Yes' : 'No';
        } else {
            span.textContent = el.value.trim();
        }

        parent.replaceChild(span, el);
    });

    // ✅ Add title
    const title = document.createElement('h2');
    title.textContent = 'Certificate of Water Transfer Permission';
    title.style.cssText = `
        text-align:center;
        margin-bottom:10px;
        font-size:18px;
        font-weight:bold;
    `;
    printClone.insertBefore(title, printClone.firstChild);

    // ✅ Clean style
    printClone.querySelectorAll('button, .error-message').forEach(e => e.remove());
    printClone.querySelectorAll('.card').forEach(card => {
        Object.assign(card.style, {
            background: 'white',
            boxShadow: 'none',
            border: '1px solid #ccc',
            marginBottom: '10px',
            padding: '10px'
        });
    });

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

    // ✅ Create 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
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.9);
            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('CertificateofWaterTransferpermission.pdf');
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 200);
});
</script> --}}

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

    const messages = {
        water_connection_no: 'Owner Name is Required',
        property_owner_name: 'Total Consumer is Required',
        comment: 'Consumer No is Required',
        mobile_no: 'Mobile no is required',
        aadhar_no: 'Aadhaar no is required',
        email_id: 'Email ID is required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot No is Required',
        house_no: 'House No is Required',
        landmark: 'Landmark is Required',
        address: 'Address is Required',
        tap_size: 'Tap size is Required',
        resident_type: 'Resident Type is Required',
        is_correct_info: 'Please accept the declaration'
    };

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

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

        let errorText = '';
        const val = (field.type === 'checkbox') ? field.checked : field.value.trim();

        if (!val) {
            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;
            field.parentNode.appendChild(error);
        }
    });

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

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

    // ✅ Step 1: Hide upload section from PDF
    const uploadSection = document.getElementById('upload_section');
    let oldDisplay = '';
    if (uploadSection) {
        oldDisplay = uploadSection.style.display;
        uploadSection.style.display = 'none';
    }

    // ✅ Step 2: Save current dropdown text before clone
    const dropdownData = {};
    form.querySelectorAll('select').forEach(sel => {
        const name = sel.getAttribute('name');
        dropdownData[name] = sel.options[sel.selectedIndex]?.text || '';
    });

    // ✅ Step 3: Clone content
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');
    const printClone = addContainer.cloneNode(true);

    // ✅ Step 4: Replace all form elements with readable text
    printClone.querySelectorAll('input, select, textarea').forEach(el => {
        const parent = el.parentNode;
        const span = document.createElement('span');
        span.style.border = '1px solid #ccc';
        span.style.display = 'block';
        span.style.padding = '6px 8px';
        span.style.borderRadius = '4px';
        span.style.minHeight = '30px';
        span.style.background = '#fff';

        if (el.tagName === 'SELECT') {
            const name = el.getAttribute('name');
            span.textContent = dropdownData[name] || '';
        } else if (el.type === 'checkbox') {
            span.textContent = el.checked ? 'Yes' : 'No';
        } else if (el.type === 'file') {
            span.textContent = ''; // remove file name display
        } else {
            span.textContent = el.value.trim();
        }

        parent.replaceChild(span, el);
    });

    // ✅ Step 5: Add title
    const title = document.createElement('h2');
    title.textContent = 'Certificate of Water Transfer Permission';
    title.style.cssText = `
        text-align:center;
        margin-bottom:10px;
        font-size:18px;
        font-weight:bold;
    `;
    printClone.insertBefore(title, printClone.firstChild);

    // ✅ Step 6: Clean style
    printClone.querySelectorAll('button, .error-message').forEach(e => e.remove());
    printClone.querySelectorAll('.card').forEach(card => {
        Object.assign(card.style, {
            background: 'white',
            boxShadow: 'none',
            border: '1px solid #ccc',
            marginBottom: '10px',
            padding: '10px'
        });
    });

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

    // ✅ Step 7: Create 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);

    // ✅ Step 8: Generate PDF
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.9);
            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('CertificateofWaterTransferpermission.pdf');

            // ✅ Restore upload section after PDF save
            if (uploadSection) uploadSection.style.display = oldDisplay;
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');

            // Restore upload section if PDF fails
            if (uploadSection) uploadSection.style.display = oldDisplay;
        });
    }, 200);
});
</script> --}}


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

    const messages = {
        water_connection_no: 'Owner Name is Required',
        property_owner_name: 'Total Consumer is Required',
        comment: 'Consumer No is Required',
        mobile_no: 'Mobile no is required',
        aadhar_no: 'Aadhaar no is required',
        email_id: 'Email ID is required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot No is Required',
        house_no: 'House No is Required',
        landmark: 'Landmark is Required',
        address: 'Address is Required',
        tap_size: 'Tap size is Required',
        resident_type: 'Resident Type is Required',
        is_correct_info: 'Please accept the declaration'
    };

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

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

        let errorText = '';
        const val = (field.type === 'checkbox') ? field.checked : field.value.trim();

        if (!val) {
            errorText = messages[name];
        } 
        else {
            // ✅ Extra Validation Rules
            if (name === 'mobile_no' && !/^\d{10}$/.test(val)) {
                errorText = 'Please enter a valid 10-digit mobile number';
            }
            if (name === 'aadhar_no' && !/^\d{12}$/.test(val)) {
                errorText = 'Please enter a valid 12-digit Aadhaar number';
            }
            if (name === 'email_id' && !/^[\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}$/.test(val)) {
                errorText = 'Please enter a valid Email ID';
            }
        }

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

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

    // ✅ SHOW the upload section (your request)
    const uploadSection = document.getElementById('upload_section');
    if (uploadSection) {
        uploadSection.style.display = 'block';
    }

    // ✅ Show footer buttons if any
    document.getElementById('card-footer').style.display = 'block';
    document.getElementById('saveAndPrintBtn').style.display = 'none';

    // ✅ Step 1: Save current dropdown text before clone
    const dropdownData = {};
    form.querySelectorAll('select').forEach(sel => {
        const name = sel.getAttribute('name');
        dropdownData[name] = sel.options[sel.selectedIndex]?.text || '';
    });

    // ✅ Step 2: Clone content
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');
    const printClone = addContainer.cloneNode(true);

    // ✅ Step 3: Replace all form elements with readable text
    printClone.querySelectorAll('input, select, textarea').forEach(el => {
        const parent = el.parentNode;
        const span = document.createElement('span');
        span.style.border = '1px solid #ccc';
        span.style.display = 'block';
        span.style.padding = '6px 8px';
        span.style.borderRadius = '4px';
        span.style.minHeight = '30px';
        span.style.background = '#fff';

        if (el.tagName === 'SELECT') {
            const name = el.getAttribute('name');
            span.textContent = dropdownData[name] || '';
        } else if (el.type === 'checkbox') {
            span.textContent = el.checked ? 'Yes' : 'No';
        } else if (el.type === 'file') {
            span.textContent = ''; // remove file name display
        } else {
            span.textContent = el.value.trim();
        }

        parent.replaceChild(span, el);
    });

    // ✅ Step 4: Add title
    const title = document.createElement('h2');
    title.textContent = 'Certificate of Water Transfer Permission';
    title.style.cssText = `
        text-align:center;
        margin-bottom:10px;
        font-size:18px;
        font-weight:bold;
    `;
    printClone.insertBefore(title, printClone.firstChild);

    // ✅ Step 5: Clean style
    printClone.querySelectorAll('button, .error-message').forEach(e => e.remove());
    printClone.querySelectorAll('.card').forEach(card => {
        Object.assign(card.style, {
            background: 'white',
            boxShadow: 'none',
            border: '1px solid #ccc',
            marginBottom: '10px',
            padding: '10px'
        });
    });

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

    // ✅ Step 6: Create 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);

    // ✅ Step 7: Generate PDF
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.9);
            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('CertificateofWaterTransferpermission.pdf');
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 200);
});
</script> --}}


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

    const messages = {
        water_connection_no: 'Owner Name is Required',
        property_owner_name: 'Total Consumer is Required',
        comment: 'Consumer No is Required',
        mobile_no: 'Mobile no is required',
        aadhar_no: 'Aadhaar no is required',
        email_id: 'Email ID is required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot No is Required',
        house_no: 'House No is Required',
        landmark: 'Landmark is Required',
        address: 'Address is Required',
        tap_size: 'Tap size is Required',
        resident_type: 'Resident Type is Required',
        is_correct_info: 'Please accept the declaration'
    };

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

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

        let errorText = '';
        const val = (field.type === 'checkbox') ? field.checked : field.value.trim();

        if (!val) {
            errorText = messages[name];
        } 
        else {
            // ✅ Extra Validation Rules
            if (name === 'mobile_no' && !/^\d{10}$/.test(val)) {
                errorText = 'Please enter a valid 10-digit mobile number';
            }
            if (name === 'aadhar_no' && !/^\d{12}$/.test(val)) {
                errorText = 'Please enter a valid 12-digit Aadhaar number';
            }
            if (name === 'email_id' && !/^[\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}$/.test(val)) {
                errorText = 'Please enter a valid Email ID';
            }
        }

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

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

    // ✅ SHOW upload section (only on screen, not in PDF)
    const uploadSection = document.getElementById('upload_section');
    let oldDisplay = '';
    if (uploadSection) {
        uploadSection.style.display = 'block';
    }

    // ✅ Show footer buttons if any
    document.getElementById('card-footer').style.display = 'block';
    document.getElementById('saveAndPrintBtn').style.display = 'none';

    // ✅ Step 1: Save current dropdown text before clone
    const dropdownData = {};
    form.querySelectorAll('select').forEach(sel => {
        const name = sel.getAttribute('name');
        dropdownData[name] = sel.options[sel.selectedIndex]?.text || '';
    });

    // ✅ Step 2: Clone content (without upload section)
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return alert('Content container not found!');

    // Temporarily hide upload section before cloning
    if (uploadSection) {
        oldDisplay = uploadSection.style.display;
        uploadSection.style.display = 'none';
    }

    const printClone = addContainer.cloneNode(true);

    // Restore upload section visibility after clone
    if (uploadSection) {
        uploadSection.style.display = oldDisplay || 'block';
    }

    // ✅ Step 3: Replace all form elements with readable text
    printClone.querySelectorAll('input, select, textarea').forEach(el => {
        const parent = el.parentNode;
        const span = document.createElement('span');
        span.style.border = '1px solid #ccc';
        span.style.display = 'block';
        span.style.padding = '6px 8px';
        span.style.borderRadius = '4px';
        span.style.minHeight = '30px';
        span.style.background = '#fff';

        if (el.tagName === 'SELECT') {
            const name = el.getAttribute('name');
            span.textContent = dropdownData[name] || '';
        } else if (el.type === 'checkbox') {
            span.textContent = el.checked ? 'Yes' : 'No';
        } else if (el.type === 'file') {
            span.textContent = ''; // ✅ file field hidden from PDF
        } else {
            span.textContent = el.value.trim();
        }

        parent.replaceChild(span, el);
    });

    // ✅ Step 4: Add title
    const title = document.createElement('h2');
    title.textContent = 'Certificate of Water Transfer Permission';
    title.style.cssText = `
        text-align:center;
        margin-bottom:10px;
        font-size:18px;
        font-weight:bold;
    `;
    printClone.insertBefore(title, printClone.firstChild);

    // ✅ Step 5: Clean style
    printClone.querySelectorAll('button, .error-message').forEach(e => e.remove());
    printClone.querySelectorAll('.card').forEach(card => {
        Object.assign(card.style, {
            background: 'white',
            boxShadow: 'none',
            border: '1px solid #ccc',
            marginBottom: '10px',
            padding: '10px'
        });
    });

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

    // ✅ Step 6: Create 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);

    // ✅ Step 7: Generate PDF
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.9);
            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('CertificateofWaterTransferpermission.pdf');
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 200);
});
</script> --}}


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

    // Validation messages
    const messages = {
        water_connection_no: 'Owner Name is Required',
        property_owner_name: 'Total Consumer is Required',
        comment: 'Consumer No is Required',
        mobile_no: 'Mobile no is required',
        aadhar_no: 'Aadhaar no is required',
        email_id: 'Email ID is required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot No is Required',
        house_no: 'House No is Required',
        landmark: 'Landmark is Required',
        address: 'Address is Required',
        tap_size: 'Tap size is Required',
        resident_type: 'Resident Type is Required',
        is_correct_info: 'Please accept the declaration'
    };

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

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

        let errorText = '';
        const val = (field.type === 'checkbox') ? field.checked : field.value.trim();

        if (!val) {
            errorText = messages[name];
        } 
        else {
            if (name === 'mobile_no' && !/^\d{10}$/.test(val)) {
                errorText = 'Please enter a valid 10-digit mobile number';
            }
            if (name === 'aadhar_no' && !/^\d{12}$/.test(val)) {
                errorText = 'Please enter a valid 12-digit Aadhaar number';
            }
            if (name === 'email_id' && !/^[\w._%+-]+@[\w.-]+\.[A-Za-z]{2,}$/.test(val)) {
                errorText = 'Please enter a valid Email ID';
            }
        }

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

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

    // ✅ Show upload section after validation
    const uploadSection = document.getElementById('upload_section');
    let oldDisplay = '';
    if (uploadSection) {
        uploadSection.style.display = 'block';
    }

    // ✅ Hide save button and show footer
    const footer = document.getElementById('card-footer');
    if (footer) footer.style.display = 'block';
    const saveBtn = document.getElementById('saveAndPrintBtn');
    if (saveBtn) saveBtn.style.display = 'none';

    // ✅ Store dropdown text before cloning
    const dropdownData = {};
    form.querySelectorAll('select').forEach(sel => {
        const name = sel.getAttribute('name');
        dropdownData[name] = sel.options[sel.selectedIndex]?.text || '';
    });

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

    // Temporarily hide upload section before cloning
    if (uploadSection) {
        oldDisplay = uploadSection.style.display;
        uploadSection.style.display = 'none';
    }

    // ✅ Clone content
    const printClone = addContainer.cloneNode(true);

    // Restore upload section visibility
    if (uploadSection) {
        uploadSection.style.display = oldDisplay || 'block';
    }

    // ✅ Replace inputs/selects with text spans and remove hidden fields
    printClone.querySelectorAll('input, select, textarea').forEach(el => {
        // Remove hidden fields (fixes unreadable random text issue)
        if (el.type === 'hidden') {
            el.parentNode.removeChild(el);
            return;
        }

        const parent = el.parentNode;
        const span = document.createElement('span');
        span.style.border = '1px solid #ccc';
        span.style.display = 'block';
        span.style.padding = '6px 8px';
        span.style.borderRadius = '4px';
        span.style.minHeight = '30px';
        span.style.background = '#fff';

        if (el.tagName === 'SELECT') {
            const name = el.getAttribute('name');
            span.textContent = dropdownData[name] || '';
        } else if (el.type === 'checkbox') {
            span.textContent = el.checked ? 'Yes' : 'No';
        } else if (el.type === 'file') {
            span.textContent = ''; // Hide file input
        } else {
            span.textContent = el.value.trim();
        }

        parent.replaceChild(span, el);
    });

    // ✅ Add title
    const title = document.createElement('h2');
    title.textContent = 'Certificate of Water Transfer Permission';
    title.style.cssText = `
        text-align:center;
        margin-bottom:10px;
        font-size:18px;
        font-weight:bold;
    `;
    printClone.insertBefore(title, printClone.firstChild);

    // ✅ Make “Add Details” bold if it exists
    const addDetails = printClone.querySelector('h5, h4, h6, .section-title');
    if (addDetails && addDetails.textContent.includes('Add Details')) {
        addDetails.style.fontWeight = 'bold';
        addDetails.style.fontSize = '16px';
    }

    // ✅ Clean style
    printClone.querySelectorAll('button, .error-message').forEach(e => e.remove());
    printClone.querySelectorAll('.card').forEach(card => {
        Object.assign(card.style, {
            background: 'white',
            boxShadow: 'none',
            border: '1px solid #ccc',
            marginBottom: '10px',
            padding: '10px'
        });
    });

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

    // ✅ Create 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
    setTimeout(() => {
        html2canvas(printClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.9);
            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('CertificateofWaterTransferpermission.pdf');
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 200);
});
</script>



































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


         // Clear previous errors
    $(".application_documents_err").text('');

    // Client-side check for file
    var fileInput = $("#application_documents")[0].files;
    if ($('#upload_section').is(':visible') && fileInput.length === 0) {
        $(".application_documents_err").text("Please upload the file");
        $("#addSubmit").prop('disabled', false);
        return false;
    }




        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route("waterrepair.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);

                    // Display server-side error inside the same span
                if(responseObject.responseJSON.errors.application_documents){
                    $(".application_documents_err").text(responseObject.responseJSON.errors.application_documents[0]);
                }
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            },
        });

    });
</script>


<!--applicant name script -->
<script>
document.getElementById('water_connection_no').addEventListener('input', function () {
    
    this.value = this.value.replace(/[^A-Za-z\s]/g, '');
});
</script>

<script>
    document.getElementById('property_owner_name').addEventListener('input', function(e) {
    this.value = this.value.replace(/[^0-9]/g, '');
});
</script>


<script>
    document.getElementById('comment').addEventListener('input', function(e) {
    this.value = this.value.replace(/[^0-9]/g, '');
});
</script>

    

