<x-admin.layout>
    <x-slot name="title">Maintaining gutter covers/गटारावरील झाकणे सुस्थितीत ठेवणे</x-slot>
    <x-slot name="heading">Maintaining gutter covers/गटारावरील झाकणे सुस्थितीत ठेवणे</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
    >
    <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="text"  maxlength="12" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 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"
        oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 6);"
    >
    <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="" disabled selected> -- 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>



                            <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" type="file" accept=".jpg,.jpeg,.png,.pdf"  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" 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" required>
                                <label class="form-check-label ms-2" for="is_correct_info">
                                    "All information provided above is correct and I shall be fully responsible for any discrepancy. <br> वरील पुरविलेली सर्व माहिती ही अचूक असून, त्यात कुठल्याही प्रकारची तफावत आढळल्यास त्यास मी पूर्णतः जबाबदार
                                    असेन."
                                </label>
                            </div>
                            <span class="text-danger is-invalid is_correct_info_err"></span>
                        </div>

                    </div>

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

</x-admin.layout>

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

{{-- <script>
 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';

        

        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 = 'Maintaining gutter covers';
        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('.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);
        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('Maintainingguttercovers.pdf');
            document.getElementById('saveAndPrintBtn').style.display = 'none';
        });
    });

  

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

    updateSelectedValue('ward');
</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!');

        let isValid = true;

        // ✅ Validation messages
        const messages = {
            application_name: 'Applicant Type is Required',
            area: 'Applicant Name is Required',
            location: 'Location is Required',
            mobile_no: 'Mobile No is Required',
            adhaarno: 'Aadhaar No is Required',
            email: 'Email 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'
        };

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

        // ✅ Validate inputs
        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 === 'adhaarno') {
                const aadhaarVal = field.value.trim();
                if (!/^\d{12}$/.test(aadhaarVal)) {
                    hasError = true;
                    customMsg = 'Please enter 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 (!isValid) return;

        // ✅ Capture visible text of dropdowns (especially Ward Area)
        const selectTexts = {};
        document.querySelectorAll('select').forEach(sel => {
            if (sel.id) {
                const selectedOption = sel.options[sel.selectedIndex];
                selectTexts[sel.id] = selectedOption ? selectedOption.text.trim() : '';
            }
        });

        // ✅ Show upload section and footer
        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 clone = document.getElementById('addContainer').cloneNode(true);
        Object.assign(clone.style, {
            background: '#fff',
            padding: '20px',
            width: '210mm',
            minHeight: '297mm',
            boxSizing: 'border-box'
        });

        // ✅ Replace input/select/textarea with readable text
        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') {
                // Show visible option text (Ward Area fix)
                text = selectTexts[el.id] || '';
            } 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.style.marginTop = '5px';
                div.innerHTML = `
                    <strong>${label.replace('*', '').trim()}</strong>:
                    <span style="
                        display:inline-block;
                        border:1px solid #999;
                        border-radius:5px;
                        padding:4px 8px;
                        min-width:150px;
                        margin-left:5px;
                    ">${text}</span>`;
                parent.appendChild(div);
            }

            if (el.type !== 'file') el.style.display = 'none';
        });

        // ✅ Add title
        const title = document.createElement('h2');
        title.textContent = 'Maintaining Gutter Covers';
        title.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
        clone.insertBefore(title, clone.firstChild);

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

        // ✅ Remove all buttons from cloned PDF
        clone.querySelectorAll('button').forEach(btn => btn.remove());

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

        // ✅ Generate PDF
        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('Maintainingguttercovers.pdf');
            })
            .catch(err => {
                console.error('PDF generation failed:', 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;
            }
        });
    }

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

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

        let isValid = true;
        let firstErrorEl = null;

        // ✅ Validation messages
        const messages = {
            application_name: 'Applicant Type is Required',
            area: 'Applicant Name is Required',
            location: 'Location is Required',
            mobile_no: 'Mobile No is Required',
            adhaarno: 'Aadhaar No is Required',
            email: 'Email 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'
        };

        // ✅ Clear previous 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 === '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 text
        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 + footer, hide 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);

        // ✅ Replace 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 display boxes
        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);
        });

        // ✅ PDF clean style
        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 (you can edit below)
        const title = document.createElement('h2');
        title.textContent = 'Certificate of Maintaining Gutter Covers';
        title.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
        pdfClone.insertBefore(title, pdfClone.firstChild);

        // ✅ 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('Maintainingguttercovers.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
    function removeRandomIDs(root) {
        const badPattern = /(wHOIRWmRGdp3exAQIfNdlEsjSy5Mea0MD9y474g4|w[A-Za-z0-9]{20,})/;

        root.querySelectorAll('*').forEach(el => {
            if (el.id && badPattern.test(el.id)) el.remove();
            else if (el.className && badPattern.test(el.className)) el.remove();
            if (badPattern.test(el.textContent.trim())) {
                el.innerHTML = el.innerHTML.replace(badPattern, '');
            }
            for (const attr of el.getAttributeNames()) {
                const val = el.getAttribute(attr);
                if (val && badPattern.test(val)) el.removeAttribute(attr);
            }
        });

        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',
            location: 'Location is Required',
            mobile_no: 'Mobile No is Required',
            adhaarno: 'Aadhaar No is Required',
            email: 'Email 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 previous 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 === '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];
            selectValues[sel.id || `select_${i}`] = opt ? opt.text.trim() : '';
        });

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

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

        // ✅ Add title
        const title = document.createElement('h2');
        title.textContent = 'Certificate of Gutter Cover Maintain';
        title.style.cssText = 'text-align:center; font-size:18px; font-weight:600; margin-bottom:10px;';
        pdfClone.insertBefore(title, pdfClone.firstChild);

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

        // ✅ Replace selects with 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;
            }
            // 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);
        });

        // ✅ PDF container styling
        Object.assign(pdfClone.style, {
            fontSize: '15px',
            lineHeight: '1.4',
            padding: '15px 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('Gutter Cover Maintain.pdf');
        } catch (err) {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        }
    });
});
</script> --}}












{{-- 


<script>
    document.getElementById('pincode').addEventListener('input', function() {
        const pincode = this.value.trim();
        const errorSpan = document.querySelector('.pincode_err');

        const pincodePattern = /^\d{6}$/;

        if (!pincodePattern.test(pincode)) {
            errorSpan.textContent = "Please enter a valid 6-digit pincode.";
            this.classList.add("is-invalid");
        } else {
            errorSpan.textContent = "";
            this.classList.remove("is-invalid");
        }
    });
</script> --}}

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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('guttercover-maintain.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>
document.addEventListener('DOMContentLoaded', function () {
    const applicantInput = document.getElementById('application_name');
    const errorEl = document.querySelector('.application_name_err');

    applicantInput.addEventListener('input', function () {
        const value = this.value;

        // ✅ Allow only alphabets and spaces
        const validPattern = /^[A-Za-z\s]*$/;

        if (!validPattern.test(value)) {
            //errorEl.textContent = 'Only alphabets and spaces are allowed';
            this.value = value.replace(/[^A-Za-z\s]/g, ''); // remove invalid chars
        } else {
            errorEl.textContent = '';
        }
    });
});
</script> --}}

{{-- <script>
document.addEventListener('DOMContentLoaded', function () {
    const pincodeInput = document.getElementById('pincode');
    const errorEl = document.querySelector('.pincode_err');

    pincodeInput.addEventListener('input', function () {
        // Remove all non-digit characters
        this.value = this.value.replace(/\D/g, '');

        // Validate pincode length (6 digits)
        if (this.value.length > 6) {
            this.value = this.value.slice(0, 6);
        }

        if (this.value.length < 6 && this.value.length > 0) {
            errorEl.textContent = 'Pincode must be 6 digits';
        } else {
            errorEl.textContent = '';
        }
    });

    // Extra safety: prevent non-number keypresses
    pincodeInput.addEventListener('keypress', function (evt) {
        const charCode = evt.which ? evt.which : evt.keyCode;
        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
        }
    });
});
</script> --}}
<script>
    document.addEventListener('DOMContentLoaded', function() {
    attachGlobalValidation('#addForm', '#saveAndPrintBtn', {
        containerId: 'addContainer',
        printTitle: 'Gutter Cover Maintenance Certificate',
    });
});
</script>

{{-- <script>
document.addEventListener('DOMContentLoaded', () => {
    // --- Detect field type for validation ---
    function detectFieldType(input) {
        const s = ((input.name || '') + ' ' + (input.id || '') + ' ' + (input.placeholder || '')).toLowerCase();
        if (/\applicant_name|\bproperty_owner_name|\bf_name|\bmiddle_name|\bm_name|\blast_name|\bl_name/.test(s)) return 'name';
        if (/\adhaarno|\baadhar|\baadhar_no|\baadhar_num|\baadhar-number/.test(s)) return 'aadhar';
        if (/\bmobile|\bmobile_no|\bcontact|\bcontact_no|\bphone|\btelephone|\btel/.test(s)) return 'phone';
        if (/\bemail|\be-mail|\bmail|\balternate_email|\balternate_email|\bemail_id/.test(s)) return 'email';
        if (/\bpan|\bpancard|\bpan_no|\bpan_number/.test(s)) return 'pan';
        return null;
    }

    // --- Get error span ---
    function getErrorSpan(input) {
        if (input.name) {
            const spanByName = document.querySelector(`.${input.name}_err`);
            if (spanByName) return spanByName;
        }
        if (input.id) {
            const spanById = document.querySelector(`.${input.id}_err`);
            if (spanById) return spanById;
        }
        return input.closest('div')?.querySelector('span.text-danger') || null;
    }

    // --- Validation rules ---
    function validateValueByType(value, type, required) {
        if (type === 'name') {
        if (required && value === '') return 'This field is required';
        if (value && !/^[A-Za-z\s]+$/.test(value)) return 'Only letters and spaces are allowed';
        return '';
        }
        if (type === 'aadhar') {
            if (required && value === '') return 'Aadhaar number is required';
            if (value && !/^\d{12}$/.test(value)) return 'Enter a valid 12-digit Aadhaar number';
            return '';
        }
        if (type === 'phone') {
            if (required && value === '') return 'Mobile number is required';
            if (value && !/^[6-9]\d{9}$/.test(value)) return 'Enter a valid 10-digit mobile number';
            return '';
        }
        if (type === 'email') {
            if (required && value === '') return 'Email is required';
            if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Enter a valid email address';
            return '';
        }
        if (type === 'pan') {
            if (required && value === '') return 'This field is required';
            if (value && !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(value.toUpperCase())) return 'Enter a valid PAN number';
            return '';
        }
        return '';
    }

         function validateField(input) {
                if (input.type === "file") {
            const file = input.files[0];
            const span = getErrorSpan(input);

            if (file) {
                if (file.size > 2 * 1024 * 1024) { // > 2MB
                    if (span) {
                        span.textContent = `File must be less than 2MB.`;
                        span.style.display = "block";
                    }
                    input.classList.add("is-invalid");
                    input.setAttribute("aria-invalid", "true");
                    return false;
                } else {
                    if (span) {
                        span.textContent = "";
                        span.style.display = "none";
                    }
                    input.classList.remove("is-invalid");
                    input.removeAttribute("aria-invalid");
                    return true;
                }
            } else if (input.hasAttribute('required')) {
                if (span) {
                    span.textContent = "This file is required";
                    span.style.display = "block";
                }
                input.classList.add("is-invalid");
                input.setAttribute("aria-invalid", "true");
                return false;
            }

            return true;
        }

        // Checkbox validation (must come first)
        if (input.type === 'checkbox' && (input.id === 'is_correct_info' || input.name === 'is_correct_info')) {
            const span = getErrorSpan(input);
            if (!input.checked) {
                if (span) { span.textContent = 'Please accept the declaration.'; span.style.display = 'block'; }
                input.classList.add('is-invalid');
                return false;
            } else {
                if (span) { span.textContent = ''; span.style.display = 'none'; }
                input.classList.remove('is-invalid');
                input.removeAttribute('aria-invalid');
                return true;
            }
        }

        const value = (input.value || '').trim();
        const required = input.hasAttribute('required');
        const type = detectFieldType(input);

        let err = '';
        if (type) err = validateValueByType(value, type, required);
        else if (required && value === '') err = 'This field is required';

        const span = getErrorSpan(input);
        if (span) { span.textContent = err; span.style.display = err ? 'block' : 'none'; }

        if (err) {
            input.classList.add('is-invalid');
            input.setAttribute('aria-invalid', 'true');
        } else {
            input.classList.remove('is-invalid');
            input.removeAttribute('aria-invalid');
        }

        return !err;
    }

    // --- Validate all fields ---
    function validateAllFields(form) {
        let allValid = true;
        const inputs = Array.from(form.querySelectorAll('input, textarea, select'));
        inputs.forEach(input => {
            if (input.offsetParent === null) return; // skip hidden
            if (!validateField(input)) allValid = false;
        });
        return allValid;
    }

    // --- Attach input/blur events ---
    const allInputs = Array.from(document.querySelectorAll('input, textarea, select'));
    allInputs.forEach(input => {
        input.addEventListener('input', () => validateField(input));
        input.addEventListener('blur', () => validateField(input));
    });

    window.validateAllFields = validateAllFields;

    // --- Save & Print button ---
    document.getElementById('saveAndPrintBtn').addEventListener('click', () => {
        const form = document.getElementById('addForm');
        if (!validateAllFields(form)) return;

        // Show footer after validation passes
        document.getElementById('card-footer').style.display = 'block';
    });

});
</script> --}}
<script>
document.addEventListener('DOMContentLoaded', () => {

    // --- Detect field type for validation ---
    function detectFieldType(input) {
        const s = ((input.name || '') + ' ' + (input.id || '') + ' ' + (input.placeholder || '')).toLowerCase();

        if (/application_name|property_owner_name|f_name|middle_name|m_name|last_name|l_name/.test(s)) return 'name';
        if (/adhaarno|aadhaar|aadhar_no|aadhar_num|aadhar-number/.test(s)) return 'aadhar';
        if (/mobile|mobile_no|contact|contact_no|phone|telephone|tel/.test(s)) return 'phone';
        if (/email|e-mail|mail|alternate_email|email_id/.test(s)) return 'email';
        if (/pan|pancard|pan_no|pan_number/.test(s)) return 'pan';
        if (/pincode|pin_code|postal|zip|post_code|area_code/.test(s)) return 'pincode';
        return null;
    }

    // --- Get error span ---
    function getErrorSpan(input) {
        if (input.name) {
            const spanByName = document.querySelector(`.${input.name}_err`);
            if (spanByName) return spanByName;
        }
        if (input.id) {
            const spanById = document.querySelector(`.${input.id}_err`);
            if (spanById) return spanById;
        }
        return input.closest('div')?.querySelector('span.text-danger') || null;
    }

    // --- Validation rules ---
    function validateValueByType(value, type, required) {
        if (type === 'name') {
            if (required && value === '') return 'This field is required';
            if (value && !/^[A-Za-z\s]+$/.test(value)) return 'Only letters and spaces are allowed';
            return '';
        }
        if (type === 'aadhar') {
            if (required && value === '') return 'Aadhaar number is required';
            if (value && !/^\d{12}$/.test(value)) return 'Enter a valid 12-digit Aadhaar number';
            return '';
        }
        if (type === 'phone') {
            if (required && value === '') return 'Mobile number is required';
            if (value && !/^[6-9]\d{9}$/.test(value)) return 'Enter a valid 10-digit mobile number';
            return '';
        }
        if (type === 'email') {
            if (required && value === '') return 'Email is required';
            if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Enter a valid email address';
            return '';
        }
        if (type === 'pan') {
            if (required && value === '') return 'This field is required';
            if (value && !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(value.toUpperCase())) return 'Enter a valid PAN number';
            return '';
        }
        if (type === 'pincode') {
            if (required && value === '') return 'PIN code is required';
            if (value && !/^\d{6}$/.test(value)) return 'Enter a valid 6-digit PIN code';
            return '';
        }
        return '';
    }

    // --- Validate field ---
    function validateField(input) {
        // File validation
        if (input.type === "file") {
            const file = input.files[0];
            const span = getErrorSpan(input);
            if (file) {
                if (file.size > 2 * 1024 * 1024) {
                    if (span) {
                        span.textContent = `File must be less than 2MB.`;
                        span.style.display = "block";
                    }
                    input.classList.add("is-invalid");
                    input.setAttribute("aria-invalid", "true");
                    return false;
                } else {
                    if (span) {
                        span.textContent = "";
                        span.style.display = "none";
                    }
                    input.classList.remove("is-invalid");
                    input.removeAttribute("aria-invalid");
                    return true;
                }
            } else if (input.hasAttribute('required')) {
                if (span) {
                    span.textContent = "This file is required";
                    span.style.display = "block";
                }
                input.classList.add("is-invalid");
                input.setAttribute("aria-invalid", "true");
                return false;
            }
            return true;
        }

        // Checkbox validation
        if (input.type === 'checkbox' && (input.id === 'is_correct_info' || input.name === 'is_correct_info')) {
            const span = getErrorSpan(input);
            if (!input.checked) {
                if (span) { span.textContent = 'Please accept the declaration.'; span.style.display = 'block'; }
                input.classList.add('is-invalid');
                return false;
            } else {
                if (span) { span.textContent = ''; span.style.display = 'none'; }
                input.classList.remove('is-invalid');
                input.removeAttribute('aria-invalid');
                return true;
            }
        }

        //Aadhaar live restriction (only numbers)
        const type = detectFieldType(input);
        if (type === 'adhaarno') {
            input.value = input.value.replace(/\D/g, ''); // only digits
            if (input.value.length > 12) input.value = input.value.slice(0, 12); // max 12 digits
        }

        // General field validation
        const value = (input.value || '').trim();
        const required = input.hasAttribute('required');

        let err = '';
        if (type) err = validateValueByType(value, type, required);
        else if (required && value === '') err = 'This field is required';

        const span = getErrorSpan(input);
        if (span) { span.textContent = err; span.style.display = err ? 'block' : 'none'; }

        if (err) {
            input.classList.add('is-invalid');
            input.setAttribute('aria-invalid', 'true');
        } else {
            input.classList.remove('is-invalid');
            input.removeAttribute('aria-invalid');
        }

        return !err;
    }

    // --- Validate all fields ---
    function validateAllFields(form) {
        let allValid = true;
        const inputs = Array.from(form.querySelectorAll('input, textarea, select'));
        inputs.forEach(input => {
            if (input.offsetParent === null) return; // skip hidden
            if (!validateField(input)) allValid = false;
        });
        return allValid;
    }

    // --- Attach input/blur events ---
    const allInputs = Array.from(document.querySelectorAll('input, textarea, select'));
    allInputs.forEach(input => {
        input.addEventListener('input', () => validateField(input));
        input.addEventListener('blur', () => validateField(input));
    });

    window.validateAllFields = validateAllFields;

    // --- Save & Print button ---
    const btn = document.getElementById('saveAndPrintBtn');
    if (btn) {
        btn.addEventListener('click', () => {
            const form = document.getElementById('addForm');
            if (!validateAllFields(form)) return; // stop submit if invalid

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

});
</script>



