<x-admin.layout>
    <x-slot name="title">Sewerage Property Connection\सीवरेज प्रॉपर्टी कनेक्शन</x-slot>
    <x-slot name="heading">Sewerage Property Connection\सीवरेज प्रॉपर्टी कनेक्शन</x-slot>

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

                        {{-- Applicant Details --}}
                        <h5 class="text-primary">Applicant Details / अर्जदाराची माहिती</h5>
                        <div class="mb-3 row">

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name">Applicant Full Name  / अर्जदाराचे नाव<span class="text-danger">*</span></label>
                                <input class="form-control"  id="applicant_name" name="applicant_name" type="text" placeholder="Enter Applicant Name / अर्जदाराचे नाव भरा"
                                pattern="^[A-Za-z\s]+$"
                                title="Only letters and spaces are allowed">
                                <span class="text-danger is-invalid applicant_name_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" type="text" placeholder="Enter Mobile No. / मोबाईल नंबर भरा" maxlength="10" pattern="\d{10}"
                               title="Please enter exactly 10 digits"  inputmode="numeric" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10);">
                               <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>


                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="property_no">Survey No. /Hissa No. /C T No. / सर्व्हे क्रमांक / हिस्सा क्रमांक / सीटी क्रमांक.<span class="text-danger">*</span></label>
                                <input class="form-control" id="property_no" name="property_no" type="text"  placeholder="Enter Survey No./Hissa No./C T No./ सर्व्हे क्रमांक / हिस्सा क्रमांक / सीटी क्रमांक.">
                                <span class="text-danger is-invalid property_no_err"></span>
                            </div> --}}

                            <div class="col-md-4">
                                    <label class="col-form-label" for="survey_no">
                                        Survey No. / Hissa No. / C T No. / सर्व्हे क्रमांक / हिस्सा क्रमांक / सीटी
                                        क्रमांक.
                                        <span class="text-danger">*</span>
                                    </label>
                                    <textarea class="form-control" id="property_no" name="property_no" rows="3"
                                        placeholder="Enter Survey No. / Hissa No. / C T No. / सर्व्हे क्रमांक / हिस्सा क्रमांक / सीटी क्रमांक."></textarea>
                                    <span class="text-danger is-invalid property_no_err"></span>
                                </div>



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


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


                            <div class="col-md-4">
                                <label class="col-form-label" for="ward_area">Ward<span class="text-danger">*</span></label>
                                <select class="form-select" name="ward_area" id="ward_area" >
                                    <option value="">Select Ward </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>


                        <h5 class="text-primary">Documents / कागदपत्रे</h5>
                        <div class="mb-3 row">
                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="application_doc">Application form downloaded in the prescribed format/ विहित नमुन्यात डाउनलोड केलेला अर्ज<span class="text-danger">*</span></label>
                                <input class="form-control" id="application_doc" name="application_doc" type="file" required>
                                <span class="text-danger is-invalid application_doc_err"></span>
                            </div> --}}

                            <div class="col-md-4">
                                <label class="col-form-label" for="bill_doc">Unloaded/ Oc & Cc / अनलोड केलेले / ओसी आणि सीसी <span class="text-danger">*</span></label>
                                <input class="form-control" id="bill_doc" name="bill_doc" type="file" >
                                <span class="text-danger is-invalid bill_doc_err"></span>
                            </div>


                            <div class="col-md-4">
                                    <label class="col-form-label" for="site_photo">Site photo / साइट फोटो<span
                                            class="text-danger"></span></label>
                                    <input class="form-control" id="site_photo" name="site_photo" type="file">
                                    <span class="text-danger is-invalid site_photo_err"></span>
                                </div>
								
								
								 <div class="col-md-4">
                                    <label class="col-form-label" for="blue_print">Blue print / ब्लू प्रिंट<span
                                            class="text-danger"></span></label>
                                    <input class="form-control" id="blue_print" name="blue_print" type="file">
                                    <span class="text-danger is-invalid blue_print_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="other_doc">Other relevant Documents / इतर
                                        संबंधित कागदपत्रे<span class="text-danger"></span></label>
                                    <input class="form-control" id="other_doc" name="other_doc" type="file">
                                    <span class="text-danger is-invalid other_doc_err"></span>
                                </div>
								




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

                        </div>

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


                          <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 class="form-group" style="text-align: center;">
                            <button type="button" id="saveAndPrintBtn" class="btn btn-success">Save and Print</button>
                        </div>

                    {{-- Footer --}}
                    <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>
                         {{-- <button class="save" class="btn btn-warning">Save & Print/सेव्ह करा आणि प्रिंट करा</button> --}}
                    </div>

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

</x-admin.layout>




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

    // Client-side check for file
    var fileInput = $("#application_doc")[0].files;
    if ($('#upload_section').is(':visible') && fileInput.length === 0) {
        $(".application_doc_err").text("Please upload the file");
        $("#addSubmit").prop('disabled', false);
        return false;
    }
    var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('sewerage-peoperty.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_doc){
                    $(".application_doc_err").text(responseObject.responseJSON.errors.application_doc[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('applicant_name').addEventListener('input', function () {
    
    this.value = this.value.replace(/[^A-Za-z\s]/g, '');
});
</script>


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

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

    // 1️⃣ Validate the form first
    if (!form.checkValidity()) {
        form.reportValidity();
        return; // Stop execution if form invalid
    }

    // 2️⃣ Show hidden sections required for PDF
    const uploadSection = document.getElementById('upload_section');
    if (uploadSection) uploadSection.style.display = 'block';

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

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

    // 3️⃣ Clone content for printing
    const printContainerClone = addContainer.cloneNode(true);

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

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

    // Add title
    const printTitle = document.createElement('h2');
    printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
    printTitle.textContent = 'Certificate of sewerage peoperty';
    printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);

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

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

    // 4️⃣ 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(printContainerClone);

    // 5️⃣ Generate PDF after a tiny delay to ensure DOM updates
    setTimeout(() => {
        html2canvas(printContainerClone, {
            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('CertificateofSewerageProperty.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); // tiny delay
});
</script> --}}

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

    // ✅ Validation messages for each field
    const messages = {
        applicant_name: 'Applicant is Required',
        mobile_no: 'Mobile No is Required',
        property_no: 'Property No is Required',
        applicant_address: 'Applicant Address is Required',
        tax_no: 'Tax No is Required',
        ward_area: 'Ward Area is Required',
        bill_doc: 'Bill Doc is Required',
         is_correct_info: 'Please accept the declaration'
    };

    let isValid = true;

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

    // Loop through required fields and show inline error
    Object.keys(messages).forEach(name => {
        const field = form.querySelector(`[name="${name}"]`);
        if (!field) return;

        let errorText = '';

        if (field.type === 'checkbox') {
            if (!field.checked) errorText = messages[name];
        } else if (!field.value.trim()) {
            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 (field.parentNode) field.parentNode.appendChild(error);
        }
    });

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

    // ✅ Continue if form valid
    const uploadSection = document.getElementById('upload_section');
    if (uploadSection) uploadSection.style.display = 'block';

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

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

    // Clone content for printing
    const printContainerClone = addContainer.cloneNode(true);

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

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

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

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

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

    // 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(printContainerClone);

    // Generate PDF
    setTimeout(() => {
        html2canvas(printContainerClone, {
            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('CertificateofSewerageProperty.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 for each field
    const messages = {
        applicant_name: 'Applicant is Required',
        mobile_no: 'Mobile No is Required',
        property_no: 'Property No is Required',
        applicant_address: 'Applicant Address is Required',
        tax_no: 'Tax No is Required',
        ward_area: 'Ward Area is Required',
        bill_doc: 'Bill Doc is Required',
        is_correct_info: 'Please accept the declaration'
    };

    let isValid = true;

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

    // Loop through required fields and show inline error
    Object.keys(messages).forEach(name => {
        const field = form.querySelector(`[name="${name}"]`);
        if (!field) return;

        let errorText = '';

        // ✅ Mobile number specific validation
        if (name === 'mobile_no') {
            const value = field.value.trim();
            if (!value) {
                errorText = messages[name];
            } else if (!/^\d{10}$/.test(value)) {
                errorText = 'Please enter a valid 10-digit Mobile Number';
            }
        }
        else if (field.type === 'checkbox') {
            if (!field.checked) errorText = messages[name];
        }
        else if (!field.value.trim()) {
            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 (field.parentNode) field.parentNode.appendChild(error);
        }
    });

    // 🛑 Stop and scroll to the first error if invalid
    if (!isValid) {
        const firstError = form.querySelector('.error-message');
        if (firstError) {
            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            window.scrollTo({ top: firstError.getBoundingClientRect().top + window.scrollY - 100, behavior: 'smooth' });
        }
        return;
    }

    // ✅ Continue if form is valid
    const uploadSection = document.getElementById('upload_section');
    if (uploadSection) uploadSection.style.display = 'block';

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

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

    // ✅ Clone content for printing
    const printContainerClone = addContainer.cloneNode(true);

    // ❌ Remove upload section from PDF clone
    const uploadSectionClone = printContainerClone.querySelector('#upload_section');
    if (uploadSectionClone) uploadSectionClone.remove();

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

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

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

    // Remove interactive elements
    printContainerClone.querySelectorAll('button, input[type="file"]').forEach(el => el.remove());

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

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

    // 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(printContainerClone);

    // ✅ Generate PDF
    setTimeout(() => {
        html2canvas(printContainerClone, {
            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('CertificateofSewerageProperty.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 = {
        applicant_name: 'Applicant is Required',
        mobile_no: 'Mobile No is Required',
        property_no: 'Property No is Required',
        applicant_address: 'Applicant Address is Required',
        tax_no: 'Tax No is Required',
        ward_area: 'Ward Area is Required',
        bill_doc: 'Bill Doc 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 = '';
        if (name === 'mobile_no') {
            const value = field.value.trim();
            if (!value) errorText = messages[name];
            else if (!/^\d{10}$/.test(value)) errorText = 'Please enter a valid 10-digit Mobile Number';
        }
        else if (field.type === 'checkbox') {
            if (!field.checked) errorText = messages[name];
        }
        else if (!field.value.trim()) {
            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 (field.parentNode) field.parentNode.appendChild(error);
        }
    });

    if (!isValid) {
        const firstError = form.querySelector('.error-message');
        if (firstError) {
            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            window.scrollTo({ top: firstError.getBoundingClientRect().top + window.scrollY - 100, behavior: 'smooth' });
        }
        return;
    }

    const uploadSection = document.getElementById('upload_section');
    if (uploadSection) uploadSection.style.display = 'block';

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

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

    // ✅ Clone the form container
    const printContainerClone = addContainer.cloneNode(true);

    // ✅ Sync selected values (especially Ward dropdowns) before replacing
    const originalSelects = form.querySelectorAll('select');
    const clonedSelects = printContainerClone.querySelectorAll('select');
    clonedSelects.forEach((select, i) => {
        const selectedIndex = originalSelects[i].selectedIndex;
        if (selectedIndex >= 0) select.selectedIndex = selectedIndex;
    });

    // ✅ Replace select + file inputs in cloned version only
    printContainerClone.querySelectorAll('select, input[type="file"]').forEach(el => {
        let displayText = '';

        if (el.tagName.toLowerCase() === 'select') {
            const selectedOption = el.options[el.selectedIndex];
            displayText = selectedOption && selectedOption.text.trim() !== '-- Select Ward --'
                ? selectedOption.text
                : (el.value.trim() || 'Ward not selected');
        } 
        else if (el.type === 'file') {
            displayText = Array.from(el.files).map(f => f.name).join(', ') || 'No file uploaded';
        }

        const div = document.createElement('div');
        div.textContent = displayText;
        div.className = 'selected-value';
        div.style.padding = '4px 0';
        el.parentNode.replaceChild(div, el);
    });

    // ❌ Remove upload section from clone
    const uploadSectionClone = printContainerClone.querySelector('#upload_section');
    if (uploadSectionClone) uploadSectionClone.remove();

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

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

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

    // Remove buttons
    printContainerClone.querySelectorAll('button').forEach(el => el.remove());

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

    // Hidden print area
    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);

    // ✅ Generate PDF
    setTimeout(() => {
        html2canvas(printContainerClone, {
            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('CertificateofSewerageProperty.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 = {
        applicant_name: 'Applicant is Required',
        mobile_no: 'Mobile No is Required',
        property_no: 'Property No is Required',
        applicant_address: 'Applicant Address is Required',
       // tax_no: 'Tax No is Required',
        ward_area: 'Ward Area is Required',
        bill_doc: 'Bill Doc 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 = '';
        if (name === 'mobile_no') {
            const value = field.value.trim();
            if (!value) errorText = messages[name];
            else if (!/^\d{10}$/.test(value)) errorText = 'Please enter a valid 10-digit Mobile Number';
        }
        else if (field.type === 'checkbox') {
            if (!field.checked) errorText = messages[name];
        }
        else if (!field.value.trim()) {
            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 (field.parentNode) field.parentNode.appendChild(error);
        }
    });

    if (!isValid) {
        const firstError = form.querySelector('.error-message');
        if (firstError) {
            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            window.scrollTo({ top: firstError.getBoundingClientRect().top + window.scrollY - 100, behavior: 'smooth' });
        }
        return;
    }

    const uploadSection = document.getElementById('upload_section');
    if (uploadSection) uploadSection.style.display = 'block';

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

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

    // ✅ Clone the form container
    const printContainerClone = addContainer.cloneNode(true);

    // ✅ Sync selected values (especially Ward dropdowns)
    const originalSelects = form.querySelectorAll('select');
    const clonedSelects = printContainerClone.querySelectorAll('select');
    clonedSelects.forEach((select, i) => {
        const selectedIndex = originalSelects[i].selectedIndex;
        if (selectedIndex >= 0) select.selectedIndex = selectedIndex;
    });

    // ✅ Replace select + file inputs with textbox-style divs
    printContainerClone.querySelectorAll('select, input[type="file"]').forEach(el => {
        let displayText = '';

        if (el.tagName.toLowerCase() === 'select') {
            const selectedOption = el.options[el.selectedIndex];
            displayText = selectedOption && selectedOption.text.trim() !== '-- Select Ward --'
                ? selectedOption.text
                : (el.value.trim() || '');
        } 
        else if (el.type === 'file') {
            displayText = Array.from(el.files).map(f => f.name).join(', ') || '';
        }

        const div = document.createElement('div');
        div.textContent = displayText;

        // ✅ Special styling for "ward_area" and "bill_doc"
        if (el.name === 'ward_area' || el.name === 'bill_doc') {
            Object.assign(div.style, {
                border: '1px solid #000',
                padding: '6px 10px',
                borderRadius: '6px',
                minHeight: '24px',
                backgroundColor: '#fafafa',
                display: 'inline-block',
                width: '90%',
                fontSize: '15px',
                marginTop: '2px'
            });
        } else {
            div.style.padding = '4px 0';
        }

        el.parentNode.replaceChild(div, el);
    });

    // ❌ Remove upload section from clone
    const uploadSectionClone = printContainerClone.querySelector('#upload_section');
    if (uploadSectionClone) uploadSectionClone.remove();

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

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

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

    // Remove buttons
    printContainerClone.querySelectorAll('button').forEach(el => el.remove());

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

    // Hidden print area
    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);

    // ✅ Generate PDF
    setTimeout(() => {
        html2canvas(printContainerClone, {
            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('CertificateofSewerageProperty.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("applicant_name").addEventListener("input", function (e) {
    // सिर्फ letters (English + Marathi/Devanagari) और spaces allow करो
    this.value = this.value.replace(/[^A-Za-z\u0900-\u097F\s]/g, '');
});
</script>
<script>
document.getElementById("tax_no").addEventListener("input", function (e) {
    // सिर्फ digits (0-9) allow करो
    this.value = this.value.replace(/[^0-9]/g, '');
});
</script>




