<x-admin.layout>
    <x-slot name="title">रस्त्यांवरील खड्डे बुजविणे/Filling potholes on roads</x-slot>
    <x-slot name="heading">रस्त्यांवरील खड्डे बुजविणे/Filling potholes on roads</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="row">
                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="application_name">Applicant Name <span class="text-danger">*</span></label>
                                <input class="form-control" id="application_name" name="application_name" type="text" placeholder="Enter Applicant Name" required>
                                <span class="text-danger is-invalid application_name_err"></span>
                            </div> --}}

                            <div class="col-md-4">
    <label class="col-form-label" for="application_name">
        Applicant Name <span class="text-danger">*</span>
    </label>
    <input class="form-control" id="application_name" name="application_name" 
           type="text" placeholder="Enter Applicant Name" required 
           onkeypress="return onlyAlphabets(event)">
    <span class="text-danger is-invalid application_name_err"></span>
</div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="area">Area <span class="text-danger">*</span></label>
                                <input class="form-control" id="area" name="area" type="text" placeholder="Enter the area" required>
                                <span class="text-danger is-invalid area_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="location">Locality <span class="text-danger">*</span></label>
                                <input class="form-control" id="location" name="location" type="text" placeholder="Enter the location" required>
                                <span class="text-danger is-invalid location_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="number" maxlength="10" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);" placeholder="Enter the mobile_no" required>
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="email">Email<span class="text-danger">*</span></label>
                                <input class="form-control" id="email" name="email" type="text" placeholder="Enter the email" required>
                                <span class="text-danger is-invalid email_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="adhaarno">Aadhaar Number <span class="text-danger">*</span></label>
                                <input class="form-control" id="adhaarno" name="adhaarno" type="number" onkeypress="return isNumberKey(event)" oninput="limitAadharLength(this)" maxlength="12"  placeholder="Enter the adhaar number" required>
                                <span class="text-danger is-invalid adhaarno_err"></span>
                            </div>
                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="pincode">Pincode<span class="text-danger">*</span></label>
                                <input class="form-control" id="pincode" name="pincode" type="text" placeholder="Enter the pincode" required pattern="^\d{6}$" maxlength="6">
                                <span class="text-danger is-invalid pincode_err"></span>
                            </div> --}}
                            {{-- <div class="col-md-4">
    <label class="col-form-label" for="pincode">
        Pincode <span class="text-danger">*</span>
    </label>
    <input class="form-control" id="pincode" name="pincode" type="text" 
           placeholder="Enter the pincode" required 
           maxlength="6" pattern="^\d{6}$"
           onkeypress="return onlyNumbers(event)">
    <span class="text-danger is-invalid pincode_err"></span>
</div> --}}

<div class="col-md-4">
    <label class="col-form-label" for="pincode">
        Pincode <span class="text-danger">*</span>
    </label>
    <input class="form-control" id="pincode" name="pincode" type="text" 
           placeholder="Enter the pincode" required 
           maxlength="6" pattern="^\d{6}$"
           onkeypress="return onlyNumbers(event)">
    <span class="text-danger is-invalid pincode_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 the landmark" required>
                                <span class="text-danger is-invalid landmark_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="ward_area">Ward Type<span class="text-danger">*</span></label>
                                <select name="ward_area" id="ward_area" class="form-select" required>
                                    <option value="">Select </option>
                                    @foreach ($options as $option)
                                        <option value="{{ $option->id }}">{{ $option->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_err"></span>
                                <div class="selected-value d-none" id="ward_area"></div>
                            </div>



                            <div class="col-md-4">
                                <label class="col-form-label" for="details">Details/तक्रारीचे स्वरूप<span class="text-danger">*</span></label>
                                <textarea class="form-control" id="details" maxlength="255" name="details" type="text" placeholder="Enter the details" required></textarea>
                                <span class="text-danger is-invalid details_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="gpsphotos">Upload GPS Photo/GPS फोटो अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="gpsphotos" name="gpsphotos" accept=".jpg,.jpeg,.png,.pdf" type="file" required>
                                <span class="text-danger is-invalid gpsphotos_err"></span>
                            </div>

                            <div id="upload_section" style="display: none;">
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="upload_prescribed_formats">Upload Application in Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                                    <input class="form-control" id="upload_prescribed_formats" name="upload_prescribed_formats" accept=".pdf, image/*" type="file" required>
                                    <span class="text-danger is-invalid upload_prescribed_formats_err"></span>
                                </div>
                            </div>

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

                    <div 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>
    function isNumberKey(evt) {
        var charCode = evt.which ? evt.which : evt.keyCode;

        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
            return false;
        }
        return true;
    }


    function limitAadharLength(input) {
        if (input.value.length > 12) {
            input.value = input.value.slice(0, 12);
        }
    }

    document.getElementById('saveAndPrintBtn').addEventListener('click', function() {
        document.getElementById('upload_section').style.display = 'block';
        document.getElementById('card-footer').style.display = 'block';

        // var select = document.getElementById('ward');
        // var selectedDiv = document.getElementById('ward_selected');
        // if (!selectedDiv) {
        //     selectedDiv = document.createElement('div');
        //     selectedDiv.id = 'ward_selected';
        //     selectedDiv.className = 'selected-value';
        //     select.parentNode.appendChild(selectedDiv);
        // }
        // var selectedText = select.options[select.selectedIndex] ? select.options[select.selectedIndex].text : '';
        // selectedDiv.textContent = 'Selected: ' + selectedText;
        // selectedDiv.classList.remove('d-none');
        // select.style.display = 'none';

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

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

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

        // Array.from(printContainerClone.querySelectorAll('input[type="checkbox"]')).forEach(checkbox => {
        //     const info = document.createElement('div');
        //     info.textContent = checkbox.checked ? 'Checked' : 'Not checked';
        //     checkbox.parentNode.appendChild(info);
        //     checkbox.style.display = 'none';
        // });
        let printContainer = document.getElementById('printContainer');
        if (!printContainer) {
            printContainer = document.createElement('div');
            printContainer.id = 'printContainer';
            printContainer.style.position = 'fixed';
            printContainer.style.left = '-9999px';
            document.body.appendChild(printContainer);
        }
        printContainer.innerHTML = '';
        printContainer.appendChild(printContainerClone);
        html2canvas(printContainerClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1,
            useCORS: true,
            allowTaint: true,
            logging: false
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            const {
                jsPDF
            } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const pageWidth = pdf.internal.pageSize.getWidth();
            const pageHeight = pdf.internal.pageSize.getHeight();
            const margin = 10;
            const pdfWidth = pageWidth - margin * 2;
            const pdfHeight = pageHeight - margin * 2;
            pdf.addImage(imgData, 'JPEG', margin, margin, pdfWidth, pdfHeight);
            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content or try again.');
            }
            pdf.save('Fillingpotholesonroads.pdf');
            document.getElementById('saveAndPrintBtn').style.display = 'none';
        });
    });

    // function updateSelectedValue(selectId) {
    //     var select = document.getElementById(selectId);
    //     var selectedText = select.options[select.selectedIndex] ? select.options[select.selectedIndex].text : '';
    //     var selectedDiv = document.getElementById(selectId + '_selected');
    //     if (!selectedDiv) {
    //         selectedDiv = document.createElement('div');
    //         selectedDiv.id = selectId + '_selected';
    //         selectedDiv.className = 'selected-value';
    //         select.parentNode.appendChild(selectedDiv);
    //     }
    //     selectedDiv.textContent = 'Selected: ' + selectedText;
    //     selectedDiv.classList.remove('d-none');
    // }

    document.getElementById('ward').addEventListener('change', function() {
        updateSelectedValue('ward');
    });

    updateSelectedValue('ward');
</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.addEventListener('DOMContentLoaded', function() {

    function isNumberKey(evt) {
        var charCode = evt.which ? evt.which : evt.keyCode;
        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
            return false;
        }
        return true;
    }

    function limitAadharLength(input) {
        if (input.value.length > 12) input.value = input.value.slice(0, 12);
    }

    document.getElementById('saveAndPrintBtn').addEventListener('click', function(e) {
        e.preventDefault();

        const form = document.getElementById('addForm');
        if(!form) return alert('Form not found!');

        // Validation messages
        const messages = {
            application_name: 'Applicant Type is Required',
            area: 'Applicant Name is Required',
            mobile_no: 'Mobile No is Required',
            location: 'Aadhaar No is Required',
            email: 'Email is Required',
            adhaarno:'Adhar No is Required',
            pincode:'Pincode is Required',
            landmark:'Landmark is Required',
            ward_area:'Ward Area is Required',
            details:'Details is Required',
            gpsphotos:'GPS photos is Required',
            is_correct_info: 'Please accept the declaration'
        };

        let isValid = true;

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

        // Validate
        Object.entries(messages).forEach(([id, msg]) => {
            const field = document.getElementById(id);
            if(!field) return;
            let hasError = false;
            let customMsg = msg;

            if(field.type === 'checkbox') hasError = !field.checked;
            else hasError = !field.value.trim();

            if(!hasError && id==='mobile_no' && !/^\d{10}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 10-digit mobile number';
            }
            if(!hasError && id==='aadhar_no' && !/^\d{12}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 12-digit Aadhaar number';
            }
            if(!hasError && id==='email_id' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid email';
            }

            if(hasError){
                isValid = false;
                const errEl = document.querySelector(`.${id}_err`);
                if(errEl) errEl.textContent = customMsg;
            }
        });

        if(!isValid) return;

        // Clone container for PDF
        const clone = document.getElementById('addContainer').cloneNode(true);
        clone.style.background = '#fff';
        clone.style.padding = '20px';
        clone.style.width = '210mm';
        clone.style.minHeight = '297mm';
        clone.style.boxSizing = 'border-box';

        // Replace input/select/textarea with values for PDF
        clone.querySelectorAll('input, select, textarea').forEach(el => {
            const parent = el.parentNode;
            if(!parent) return;
            const label = parent.querySelector('label')?.innerText || '';
            let text = '';
            if(el.tagName==='SELECT') text = el.options[el.selectedIndex]?.text || '';
            else if(el.type==='checkbox') text = el.checked ? 'Checked' : 'Not checked';
            else if(el.type!=='file') text = el.value || '';
            if(text){
                const div = document.createElement('div');
                div.innerHTML = `<strong>${label}</strong>: ${text}`;
                parent.appendChild(div);
            }
            if(el.type!=='file') el.style.display='none';
        });

        // Add PDF title
        const title = document.createElement('h2');
        title.style.textAlign='center';
        title.style.marginBottom='18px';
        title.textContent='Filling Potholes on Roads';
        clone.insertBefore(title, clone.firstChild);

        // Hidden container for PDF
        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(clone);

        // Generate PDF using html2canvas + jsPDF
        html2canvas(clone, {scrollY:-window.scrollY, backgroundColor:'#fff', useCORS:true}).then(canvas=>{
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p','mm','a4');
            const margin = 10;
            const pdfWidth = pdf.internal.pageSize.getWidth() - margin*2;
            const pdfHeight = pdf.internal.pageSize.getHeight() - margin*2;
            pdf.addImage(imgData, 'JPEG', margin, margin, pdfWidth, pdfHeight);
            pdf.save('FillingPotholesOnRoads.pdf');

            // ✅ After PDF generation:
            // Show upload section
            document.getElementById('upload_section').style.display = 'block';
            // Hide Save and Print button
            document.getElementById('saveAndPrintBtn').style.display = 'none';
            // Show card-footer (submit/reset)
            document.getElementById('card-footer').style.display = 'block';
        }).catch(err=>{
            console.error(err);
            alert('PDF generation failed');
        });

    });
});
</script> --}}


{{-- <script>
document.addEventListener('DOMContentLoaded', function () {

    // ✅ Utility functions
    function isNumberKey(evt) {
        var charCode = evt.which ? evt.which : evt.keyCode;
        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
            return false;
        }
        return true;
    }

    function limitAadharLength(input) {
        if (input.value.length > 12) input.value = input.value.slice(0, 12);
    }

    const gpsPhotoInput = document.getElementById('gpsphotos');
    if (gpsPhotoInput) {
        gpsPhotoInput.addEventListener('change', function () {
            const file = this.files[0];
            const errEl = document.querySelector('.gpsphotos_err');
            errEl.textContent = '';

            if (!file) return;

            const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
            const maxSize = 2 * 1024 * 1024; // 2MB

            if (!allowedTypes.includes(file.type)) {
                errEl.textContent = 'Only JPG, PNG, or PDF files are allowed.';
                this.value = '';
                return;
            }

            if (file.size > maxSize) {
                errEl.textContent = 'File size must not exceed 2 MB.';
                this.value = '';
                return;
            }
        });
    }

    // ✅ Main Save & Print button handler
    document.getElementById('saveAndPrintBtn').addEventListener('click', async function (e) {
        e.preventDefault();

        const form = document.getElementById('addForm');
        if (!form) return alert('Form not found!');

        // ✅ Validation messages
        const messages = {
            application_name: 'Applicant Type is Required',
            area: 'Applicant Name is Required',
            mobile_no: 'Mobile No is Required',
            location: 'Aadhaar No is Required',
            email: 'Email is Required',
            adhaarno: 'Aadhaar No is Required',
            pincode: 'Pincode is Required',
            landmark: 'Landmark is Required',
            ward_area: 'Ward Area is Required',
            details: 'Details are Required',
            gpsphotos: 'GPS photos are Required',
            is_correct_info: 'Please accept the declaration'
        };

        let isValid = true;
        let firstErrorEl = null;

        // ✅ Clear old errors
        Object.keys(messages).forEach(id => {
            const errEl = document.querySelector(`.${id}_err`);
            if (errEl) errEl.textContent = '';
        });

        // ✅ Validate all fields
        for (const [id, msg] of Object.entries(messages)) {
            const field = document.getElementById(id);
            if (!field) continue;
            let hasError = false;
            let customMsg = msg;

            if (field.type === 'checkbox') hasError = !field.checked;
            else hasError = !field.value.trim();

            if (!hasError && id === 'mobile_no' && !/^\d{10}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 10-digit mobile number';
            }
            if (!hasError && id === 'adhaarno' && !/^\d{12}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 12-digit Aadhaar number';
            }
            if (!hasError && id === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid email';
            }

            if (hasError) {
                isValid = false;
                const errEl = document.querySelector(`.${id}_err`);
                if (errEl) errEl.textContent = customMsg;
                if (!firstErrorEl) firstErrorEl = field;
            }
        }

        if (!isValid) {
            if (firstErrorEl) {
                firstErrorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstErrorEl.focus();
            }
            return;
        }

        // ✅ Capture dropdown values
        const selectValues = {};
        document.querySelectorAll('select').forEach((sel, i) => {
            const opt = sel.options[sel.selectedIndex];
            const text = opt ? opt.text.trim() : '';
            const key = sel.id || `select_${i}`;
            selectValues[key] = text;
        });

        // ✅ Hide Save button, show upload section & footer
        document.getElementById('upload_section').style.display = 'block';
        document.getElementById('card-footer').style.display = 'block';
        document.getElementById('saveAndPrintBtn').style.display = 'none';

        // ✅ Clone main container for PDF
        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return alert('Container not found!');
        const pdfClone = addContainer.cloneNode(true);

        // ✅ Replace all selects with readable divs
        const originalSelects = form.querySelectorAll('select');
        const cloneSelects = pdfClone.querySelectorAll('select');
        cloneSelects.forEach((cloneSelect, i) => {
            const original = originalSelects[i];
            const selectedText = selectValues[original?.id] || '-';
            const div = document.createElement('div');
            div.textContent = selectedText;
            Object.assign(div.style, {
                fontSize: '15px',
                padding: '6px 10px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: '#fff',
                margin: '4px 0'
            });
            cloneSelect.parentNode.replaceChild(div, cloneSelect);
        });

        // ✅ Replace inputs & textareas with styled text
        pdfClone.querySelectorAll('input, textarea').forEach(el => {
            if (el.type === 'file') {
                el.style.display = 'none';
                return;
            }
            if (el.type === 'checkbox') {
                const div = document.createElement('div');
                div.textContent = el.checked ? '☑ Accepted' : '☐ Not Accepted';
                div.style.marginTop = '4px';
                el.parentNode.appendChild(div);
                el.style.display = 'none';
                return;
            }
            const val = el.value.trim() || '-';
            const div = document.createElement('div');
            div.textContent = val;
            Object.assign(div.style, {
                fontSize: '15px',
                padding: '6px 10px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: '#fff',
                margin: '4px 0'
            });
            el.parentNode.replaceChild(div, el);
        });

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

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

        // ✅ Add title
        // ✅ Add title with reduced top space
const title = document.createElement('h2');
title.textContent = 'Certificate of Filling Potholes on Roads';
title.style.cssText = `
    text-align: center;
    margin-top: 0;
    margin-bottom: 10px;
    font-size: 18px;
    font-weight: 600;
`;
pdfClone.insertBefore(title, pdfClone.firstChild);

// ✅ Reduce top padding of the entire PDF
Object.assign(pdfClone.style, {
    fontSize: '15px',
    lineHeight: '1.4',
    padding: '10px 20px 20px 20px', // reduced top padding from 20px → 10px
    background: '#fff',
    width: '210mm',
    minHeight: '297mm',
    boxSizing: 'border-box',
    margin: '0 auto'
});


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

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


{{-- <script>
document.addEventListener('DOMContentLoaded', function () {

    // ✅ Utility functions
    function isNumberKey(evt) {
        var charCode = evt.which ? evt.which : evt.keyCode;
        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
            return false;
        }
        return true;
    }

    function limitAadharLength(input) {
        if (input.value.length > 12) input.value = input.value.slice(0, 12);
    }

    // ✅ GPS Photo Validation
    const gpsPhotoInput = document.getElementById('gpsphotos');
    if (gpsPhotoInput) {
        gpsPhotoInput.addEventListener('change', function () {
            const file = this.files[0];
            const errEl = document.querySelector('.gpsphotos_err');
            errEl.textContent = '';

            if (!file) return;

            const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
            const maxSize = 2 * 1024 * 1024; // 2MB

            if (!allowedTypes.includes(file.type)) {
                errEl.textContent = 'Only JPG, PNG, or PDF files are allowed.';
                this.value = '';
                return;
            }

            if (file.size > maxSize) {
                errEl.textContent = 'File size must not exceed 2 MB.';
                this.value = '';
                return;
            }
        });
    }

    // ✅ Remove unwanted random IDs/texts (e.g. wHOIRWmRGdp3exAQIfNdlEsjSy5Mea0MD9y474g4)
    function removeRandomIDs(root) {
        const badPattern = /(wHOIRWmRGdp3exAQIfNdlEsjSy5Mea0MD9y474g4|w[A-Za-z0-9]{20,})/;

        root.querySelectorAll('*').forEach(el => {
            // ID or class
            if (el.id && badPattern.test(el.id)) el.remove();
            else if (el.className && badPattern.test(el.className)) el.remove();

            // Inner text
            if (badPattern.test(el.textContent.trim())) {
                el.innerHTML = el.innerHTML.replace(badPattern, '');
            }

            // Attributes
            for (const attr of el.getAttributeNames()) {
                const val = el.getAttribute(attr);
                if (val && badPattern.test(val)) el.removeAttribute(attr);
            }
        });

        // Text nodes
        const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
        const textNodes = [];
        while (walker.nextNode()) textNodes.push(walker.currentNode);
        textNodes.forEach(node => {
            if (badPattern.test(node.textContent.trim())) {
                node.textContent = node.textContent.replace(badPattern, '');
            }
        });
    }

    // ✅ Main Save & Print button handler
    document.getElementById('saveAndPrintBtn').addEventListener('click', async function (e) {
        e.preventDefault();

        const form = document.getElementById('addForm');
        if (!form) return alert('Form not found!');

        // ✅ Validation messages
        const messages = {
            application_name: 'Applicant Type is Required',
            area: 'Applicant Name is Required',
            mobile_no: 'Mobile No is Required',
            location: 'Aadhaar No is Required',
            email: 'Email is Required',
            adhaarno: 'Aadhaar No is Required',
            pincode: 'Pincode is Required',
            landmark: 'Landmark is Required',
            ward_area: 'Ward Area is Required',
            details: 'Details are Required',
            gpsphotos: 'GPS photos are Required',
            is_correct_info: 'Please accept the declaration'
        };

        let isValid = true;
        let firstErrorEl = null;

        // ✅ Clear old errors
        Object.keys(messages).forEach(id => {
            const errEl = document.querySelector(`.${id}_err`);
            if (errEl) errEl.textContent = '';
        });

        // ✅ Validate all fields
        for (const [id, msg] of Object.entries(messages)) {
            const field = document.getElementById(id);
            if (!field) continue;
            let hasError = false;
            let customMsg = msg;

            if (field.type === 'checkbox') hasError = !field.checked;
            else hasError = !field.value.trim();

            if (!hasError && id === 'mobile_no' && !/^\d{10}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 10-digit mobile number';
            }
            if (!hasError && id === 'adhaarno' && !/^\d{12}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 12-digit Aadhaar number';
            }
            if (!hasError && id === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid email';
            }

            if (hasError) {
                isValid = false;
                const errEl = document.querySelector(`.${id}_err`);
                if (errEl) errEl.textContent = customMsg;
                if (!firstErrorEl) firstErrorEl = field;
            }
        }

        if (!isValid) {
            if (firstErrorEl) {
                firstErrorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstErrorEl.focus();
            }
            return;
        }

        // ✅ Capture dropdown values
        const selectValues = {};
        document.querySelectorAll('select').forEach((sel, i) => {
            const opt = sel.options[sel.selectedIndex];
            const text = opt ? opt.text.trim() : '';
            const key = sel.id || `select_${i}`;
            selectValues[key] = text;
        });

        // ✅ Show upload section & hide Save button
        document.getElementById('upload_section').style.display = 'block';
        document.getElementById('card-footer').style.display = 'block';
        document.getElementById('saveAndPrintBtn').style.display = 'none';

        // ✅ Clone main container for PDF
        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return alert('Container not found!');
        const pdfClone = addContainer.cloneNode(true);

        // 🚫 Remove unwanted elements
        pdfClone.querySelectorAll(
            '#saveAndPrintBtn, #resetBtn, #upload_section, .prescribed_upload, #card-footer'
        ).forEach(el => el.remove());

        // 🔥 Remove random unwanted text/IDs
        removeRandomIDs(pdfClone);

        // ✅ Force white background on all cloned elements
        pdfClone.querySelectorAll('*').forEach(el => {
            el.style.backgroundColor = '#ffffff';
            el.style.color = '#000000';
        });

        // ✅ Replace all selects with readable divs
        const originalSelects = form.querySelectorAll('select');
        const cloneSelects = pdfClone.querySelectorAll('select');
        cloneSelects.forEach((cloneSelect, i) => {
            const original = originalSelects[i];
            const selectedText = selectValues[original?.id] || '-';
            const div = document.createElement('div');
            div.textContent = selectedText;
            Object.assign(div.style, {
                fontSize: '15px',
                padding: '6px 10px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: '#fff',
                margin: '4px 0'
            });
            cloneSelect.parentNode.replaceChild(div, cloneSelect);
        });

        // ✅ Replace inputs & textareas with styled text
        pdfClone.querySelectorAll('input, textarea').forEach(el => {
            if (el.type === 'file') {
                if (el.id === 'gpsphotos' && el.files.length > 0) {
                    const fileName = el.files[0].name;
                    const div = document.createElement('div');
                    div.textContent = fileName;
                    Object.assign(div.style, {
                        fontSize: '15px',
                        padding: '6px 10px',
                        border: '1px solid #ccc',
                        borderRadius: '4px',
                        backgroundColor: '#fff',
                        margin: '4px 0'
                    });
                    el.parentNode.replaceChild(div, el);
                } else {
                    el.style.display = 'none';
                }
                return;
            }
            const val = el.value.trim() || '-';
            const div = document.createElement('div');
            div.textContent = val;
            Object.assign(div.style, {
                fontSize: '15px',
                padding: '6px 10px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: '#fff',
                margin: '4px 0'
            });
            el.parentNode.replaceChild(div, el);
        });

        // ✅ PDF Styling — white background enforced
        Object.assign(pdfClone.style, {
            fontSize: '15px',
            lineHeight: '1.4',
            padding: '10px 20px 20px 20px',
            backgroundColor: '#ffffff',
            width: '210mm',
            minHeight: '297mm',
            boxSizing: 'border-box',
            margin: '0 auto'
        });

        // ✅ Add Title
        const title = document.createElement('h2');
        title.textContent = 'Certificate of Filling Potholes on Roads';
        title.style.cssText = `
            text-align: center;
            margin-top: 0;
            margin-bottom: 2px; /* reduced space */
            font-size: 18px;
            font-weight: 600;
        `;
        pdfClone.insertBefore(title, pdfClone.firstChild);

        // ✅ Prepare 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(pdfClone);

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

<script>
document.addEventListener('DOMContentLoaded', function () {

    // ✅ Utility functions
    function isNumberKey(evt) {
        const charCode = evt.which ? evt.which : evt.keyCode;
        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
            return false;
        }
        return true;
    }

    function limitAadharLength(input) {
        if (input.value.length > 12) input.value = input.value.slice(0, 12);
    }

    // ✅ GPS Photo Validation
    const gpsPhotoInput = document.getElementById('gpsphotos');
    if (gpsPhotoInput) {
        gpsPhotoInput.addEventListener('change', function () {
            const file = this.files[0];
            const errEl = document.querySelector('.gpsphotos_err');
            errEl.textContent = '';
            if (!file) return;

            const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
            const maxSize = 2 * 1024 * 1024; // 2MB

            if (!allowedTypes.includes(file.type)) {
                errEl.textContent = 'Only JPG, PNG, or PDF files are allowed.';
                this.value = '';
                return;
            }

            if (file.size > maxSize) {
                errEl.textContent = 'File size must not exceed 2 MB.';
                this.value = '';
                return;
            }
        });
    }

    // ✅ Remove unwanted random IDs/texts (e.g. wHOIRWmRGdp3exAQIfNdlEsjSy5Mea0MD9y474g4)
    function removeRandomIDs(root) {
        const badPattern = /(wHOIRWmRGdp3exAQIfNdlEsjSy5Mea0MD9y474g4|w[A-Za-z0-9]{20,})/;

        root.querySelectorAll('*').forEach(el => {
            // Remove unwanted ID or class
            if (el.id && badPattern.test(el.id)) el.remove();
            else if (el.className && badPattern.test(el.className)) el.remove();

            // Clean unwanted inner text
            if (badPattern.test(el.textContent.trim())) {
                el.innerHTML = el.innerHTML.replace(badPattern, '');
            }

            // Clean unwanted attributes
            for (const attr of el.getAttributeNames()) {
                const val = el.getAttribute(attr);
                if (val && badPattern.test(val)) el.removeAttribute(attr);
            }
        });

        // Clean raw text nodes
        const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
        const textNodes = [];
        while (walker.nextNode()) textNodes.push(walker.currentNode);
        textNodes.forEach(node => {
            if (badPattern.test(node.textContent.trim())) {
                node.textContent = node.textContent.replace(badPattern, '');
            }
        });
    }

    // ✅ Main Save & Print button handler
    document.getElementById('saveAndPrintBtn').addEventListener('click', async function (e) {
        e.preventDefault();

        const form = document.getElementById('addForm');
        if (!form) return alert('Form not found!');

        // ✅ Validation messages
        const messages = {
            application_name: 'Applicant Name is Required',
            area: 'Area is Required',
            mobile_no: 'Mobile No is Required',
            location: 'Locality is Required',
            email: 'Email is Required',
            adhaarno: 'Aadhaar No is Required',
            pincode: 'Pincode is Required',
            landmark: 'Landmark is Required',
            ward_area: 'Ward Type is Required',
            details: 'Details are Required',
            gpsphotos: 'GPS photos are Required',
            is_correct_info: 'Please accept the declaration'
        };

        let isValid = true;
        let firstErrorEl = null;

        // ✅ Clear old errors
        Object.keys(messages).forEach(id => {
            const errEl = document.querySelector(`.${id}_err`);
            if (errEl) errEl.textContent = '';
        });

        // ✅ Field validation
        for (const [id, msg] of Object.entries(messages)) {
            const field = document.getElementById(id);
            if (!field) continue;
            let hasError = false;
            let customMsg = msg;

            if (field.type === 'checkbox') hasError = !field.checked;
            else hasError = !field.value.trim();

            if (!hasError && id === 'mobile_no' && !/^\d{10}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 10-digit mobile number';
            }
            if (!hasError && id === 'adhaarno' && !/^\d{12}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 12-digit Aadhaar number';
            }
            if (!hasError && id === 'pincode' && !/^\d{6}$/.test(field.value.trim())) {
                    hasError = true;
                    customMsg = 'Please enter a valid 6-digit pincode';
                }
            if (!hasError && id === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid email';
            }

            if (hasError) {
                isValid = false;
                const errEl = document.querySelector(`.${id}_err`);
                if (errEl) errEl.textContent = customMsg;
                if (!firstErrorEl) firstErrorEl = field;
            }
        }

        if (!isValid) {
            if (firstErrorEl) {
                firstErrorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstErrorEl.focus();
            }
            return;
        }

        // ✅ Capture dropdown selected values
        const selectValues = {};
        document.querySelectorAll('select').forEach((sel, i) => {
            const opt = sel.options[sel.selectedIndex];
            const text = opt ? opt.text.trim() : '';
            const key = sel.id || `select_${i}`;
            selectValues[key] = text;
        });

        // ✅ Show upload section & hide Save button
        document.getElementById('upload_section').style.display = 'block';
        document.getElementById('card-footer').style.display = 'block';
        document.getElementById('saveAndPrintBtn').style.display = 'none';

        // ✅ Clone container for PDF
        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return alert('Container not found!');
        const pdfClone = addContainer.cloneNode(true);

        // 🚫 Remove unnecessary UI elements
       pdfClone.querySelectorAll(
    '#saveAndPrintBtn, #resetBtn, #upload_section, .prescribed_upload, #card-footer'
).forEach(el => el.remove());

// 🚫 Remove empty elements (like that box above “Add Details”)
pdfClone.querySelectorAll('div, p, span, section').forEach(el => {
    const text = el.textContent.trim();
    const hasChildren = el.children.length > 0;
    if (!text && !hasChildren) el.remove();
});

// ✅ Specifically remove any empty element just before “Add Details”
const addDetailsHeading = [...pdfClone.querySelectorAll('*')]
    .find(el => el.textContent.trim().toLowerCase() === 'add details');
if (addDetailsHeading) {
    const prevEl = addDetailsHeading.previousElementSibling;
    if (prevEl && prevEl.textContent.trim() === '') prevEl.remove();
}
        removeRandomIDs(pdfClone);

        // 🚫 Remove empty top div (above Add Details)
        const firstDiv = pdfClone.querySelector('div');
        if (firstDiv && firstDiv.textContent.trim() === '') firstDiv.remove();

        // ✅ Add Title neatly at the top
        const title = document.createElement('h2');
        title.textContent = 'Certificate of Filling Potholes on Roads';
        title.style.cssText = `
            text-align: center;
            font-size: 18px;
            font-weight: 600;
            margin-top: 0;
            margin-bottom: 4px; /* balanced spacing */
        `;
        pdfClone.insertBefore(title, pdfClone.firstChild);

        // ✅ Force white background for all
        pdfClone.querySelectorAll('*').forEach(el => {
            el.style.backgroundColor = '#ffffff';
            el.style.color = '#000000';
        });

        // ✅ Replace all selects with plain divs
        const originalSelects = form.querySelectorAll('select');
        const cloneSelects = pdfClone.querySelectorAll('select');
        cloneSelects.forEach((cloneSelect, i) => {
            const original = originalSelects[i];
            const selectedText = selectValues[original?.id] || '-';
            const div = document.createElement('div');
            div.textContent = selectedText;
            Object.assign(div.style, {
                fontSize: '15px',
                padding: '6px 10px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: '#fff',
                margin: '4px 0'
            });
            cloneSelect.parentNode.replaceChild(div, cloneSelect);
        });

        // ✅ Replace inputs/textareas with static text
        pdfClone.querySelectorAll('input, textarea').forEach(el => {
            if (el.type === 'file') {
                if (el.id === 'gpsphotos' && el.files.length > 0) {
                    const fileName = el.files[0].name;
                    const div = document.createElement('div');
                    div.textContent = fileName;
                    Object.assign(div.style, {
                        fontSize: '15px',
                        padding: '6px 10px',
                        border: '1px solid #ccc',
                        borderRadius: '4px',
                        backgroundColor: '#fff',
                        margin: '4px 0'
                    });
                    el.parentNode.replaceChild(div, el);
                } else {
                    el.style.display = 'none';
                }
                return;
            }
            const val = el.value.trim() || '-';
            const div = document.createElement('div');
            div.textContent = val;
            Object.assign(div.style, {
                fontSize: '15px',
                padding: '6px 10px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: '#fff',
                margin: '4px 0'
            });
            el.parentNode.replaceChild(div, el);
        });

        // ✅ PDF container styling
        Object.assign(pdfClone.style, {
            fontSize: '15px',
            lineHeight: '1.4',
            padding: '10px 20px 20px 20px',
            backgroundColor: '#ffffff',
            width: '210mm',
            minHeight: '297mm',
            boxSizing: 'border-box',
            margin: '0 auto'
        });

        // ✅ Hidden print container setup
        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(pdfClone);

        // ✅ Generate PDF
        try {
            const canvas = await html2canvas(pdfClone, {
                scrollY: -window.scrollY,
                backgroundColor: '#ffffff',
                scale: 1.5
            });
            const imgData = canvas.toDataURL('image/jpeg', 0.8);
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const margin = 10;
            pdf.addImage(
                imgData,
                'JPEG',
                margin,
                margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );
            pdf.save('FillingPotholesOnRoads.pdf');
        } catch (err) {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        }
    });
});
</script>


















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

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

    });
</script>

<script>
function isNumberKey(evt) {
    var charCode = evt.which ? evt.which : evt.keyCode;
    return charCode >= 48 && charCode <= 57; // Only digits
}

function limitAadharLength(input) {
    if(input.value.length > 12) {
        input.value = input.value.slice(0, 12);
    }
}
</script>

<script>
function onlyAlphabets(evt) {
    const charCode = evt.which ? evt.which : evt.keyCode;

    // Allow backspace, space, and basic letters (A-Z, a-z)
    if (
        (charCode >= 65 && charCode <= 90) || // A-Z
        (charCode >= 97 && charCode <= 122) || // a-z
        charCode === 32 || // space
        charCode === 8 // backspace
    ) {
        return true;
    } else {
        evt.preventDefault();
        return false;
    }
}
</script>

<script>
function onlyNumbers(evt) {
    const charCode = evt.which ? evt.which : evt.keyCode;

    // Allow only digits (0–9) and backspace
    if (charCode >= 48 && charCode <= 57 || charCode === 8) {
        return true;
    } else {
        evt.preventDefault();
        return false;
    }
}
</script>
