<x-admin.layout>
    <x-slot name="title">Water connection transfer permission/ जलजोडणी स्थानांतरीत परवानगी </x-slot>
    <x-slot name="heading">Water connection transfer 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="Enter Name of the Owner / मालकाचे नाव">
                                    <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. / एकूण ग्राहक क्र." 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/ग्राहक संख्या">
                                    <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 / मोबाईल नंबर" >
                                    <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 / आधार नंबर " >
                                    <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  / ईमेल आयडी">
                                    <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">
                                        <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 / प्लॅाट नं किंवा हिस्सा नं">
                                    <span class="text-danger is-invalid plot_no_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="house_no">House Number / घर नं  <span class="text-danger">*</span></label>
                                    <input class="form-control" id="house_no" name="house_no" type="text" placeholder="Enter House Number / घर नं ">
                                    <span class="text-danger is-invalid house_no_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="landmark">Landmark / जवळची खूण<span class="text-danger">*</span></label>
                                    <input class="form-control" id="landmark" name="landmark" type="text" placeholder="Enter Landmark / जवळची खूण">
                                    <span class="text-danger is-invalid landmark_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="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 Full Address Of The Property / मिळकतीचा संपुर्ण पत्ता" ></textarea>
                                    <span class="text-danger is-invalid address_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" >
                                        <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="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">
                                        <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_documents">Upload Application In Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा  <span class="text-danger">*</span></label>
                                    <input class="form-control" id="application_documents" name="application_documents" type="file" required>
                                    <span class="text-danger is-invalid application_documents_err"></span>
                                </div> --}}

                                 <div class="col-md-4" id="upload_section" style="display:none;">
                                    <label class="col-form-label" for="uploaded_applications">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 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>




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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route("watertransferpermission.store") }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function()
            {
                $('#preloader').css('opacity', '0.5');
                $('#preloader').css('visibility', 'visible');
            },
            success: function(data)
            {
                $("#addSubmit").prop('disabled', false);
                if (!data.error)
                    swal("Successful!", data.success, "success")
                        .then((action) => {
                            window.location.href = '{{ route("my-application") }}';
                        });
                else
                    swal("Error!", data.error, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            },
        });

    });
</script> --}}
<script>
$("#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("watertransferpermission.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(() => {
                        window.location.href = '{{ route("my-application") }}';
                    });
            } else {
                swal("Error!", data.error, "error");
            }
        },
        statusCode: {
            422: function(responseObject) {
                $("#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() {
                $("#addSubmit").prop('disabled', false);
                swal("Error occured!", "Something went wrong please try again", "error");
            }
        },
        complete: function() {
            $('#preloader').css('opacity', '0');
            $('#preloader').css('visibility', 'hidden');
        },
    });
});
</script>


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

   
    if (!form.checkValidity()) {
        form.reportValidity();
        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!');


     // Updated field names and messages
    const messages = {
        water_connection_no:  'Water Connection No is Required',
        property_owner_name: 'Property Owner Name is Required',
        comment: 'Comment is Required',
        mobile_no: 'Mobile No is Required',
        aadhar_no: 'Adhar No  is Required',
        email_id: 'Email ID is Required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot No is Required',
        landmark: 'Landmark is Required',
        address: 'Address is Required',
        tap_size: 'Tap size is Required',
        is_correct_info: 'Please accept the declaration',
    };

    // 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 water transfer permission';
    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('CertificateofWaterTransferpermission.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 = {
        water_connection_no:  'Water Connection No is Required',
        property_owner_name: 'Property Owner Name is Required',
        comment: 'Comment is Required',
        mobile_no: 'Mobile No is Required',
        aadhar_no: 'Aadhar No is Required',
        email_id: 'Email ID is Required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot No is Required',
        landmark: 'Landmark is Required',
        address: 'Address is Required',
        tap_size: 'Tap size is Required',
        is_correct_info: 'Please accept the declaration',
        house_no:'House No is Required'
    };

    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];
        } else {
            // Additional validations
            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 Aadhar 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;

            if (field.parentNode) field.parentNode.appendChild(error);
        }
    });

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

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

    const printContainerClone = addContainer.cloneNode(true);

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

    // Also optionally hide input fields like mobile, aadhar, email if you want
    // printContainerClone.querySelectorAll('#mobile_no,#aadhar_no,#email_id').forEach(el => el.closest('.col-md-4').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 water transfer permission';
    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'));

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

    setTimeout(() => {
        html2canvas(printContainerClone, { scrollY: -window.scrollY, backgroundColor: '#fff', scale: 1 }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
            const margin = 10;
            pdf.addImage(imgData, 'JPEG', margin, margin, pdf.internal.pageSize.getWidth() - margin * 2, pdf.internal.pageSize.getHeight() - margin * 2);
            pdf.save('CertificateofWaterTransferpermission.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!');

    const messages = {
        water_connection_no: 'Water Connection No is Required',
        property_owner_name: 'Property Owner Name is Required',
        comment: 'Comment is Required',
        mobile_no: 'Mobile No is Required',
        aadhar_no: 'Aadhar No is Required',
        email_id: 'Email ID is Required',
        ward_area: 'Ward Area is Required',
        plot_no: 'Plot 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',
        house_no: 'House No is Required'
    };

    let isValid = true;

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

    // Validation
    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];
        } 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 Aadhar 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;
            if (field.parentNode) field.parentNode.appendChild(error);
        }
    });

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

    // ✅ Show upload section and footer, hide save+print button
    const uploadSection = document.getElementById('upload_section');
    const cardFooter = document.getElementById('card-footer');
    const saveBtn = document.getElementById('saveAndPrintBtn');
    if (uploadSection) uploadSection.style.display = 'block';
    if (cardFooter) cardFooter.style.display = 'block';
    if (saveBtn) saveBtn.style.display = 'none';

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

    const printContainerClone = addContainer.cloneNode(true);

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

    // ✅ Convert dropdowns (ward_area, resident_type, tap_size) to text
    const selectFields = ['ward_area', 'resident_type', 'tap_size'];
    selectFields.forEach(name => {
        const originalSelect = form.querySelector(`[name="${name}"]`);
        const clonedSelect = printContainerClone.querySelector(`[name="${name}"]`);
        if (originalSelect && clonedSelect) {
            const selectedOption = originalSelect.options[originalSelect.selectedIndex];
            const displayText = selectedOption ? selectedOption.text : '';
            const div = document.createElement('div');
            div.textContent = displayText || '__________';
            div.style.border = '1px solid #000';
            div.style.borderRadius = '5px';
            div.style.padding = '6px 10px';
            div.style.background = '#f9f9f9';
            div.style.minHeight = '24px';
            div.style.width = '90%';
            div.style.fontSize = '15px';
            div.style.marginTop = '4px';
            clonedSelect.parentNode.replaceChild(div, clonedSelect);
        }
    });

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

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

    // Remove buttons
    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 container for rendering
    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);
            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>




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

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





