<x-admin.layout>
    <x-slot name="title">Renewal Of Plumber License / प्लंबर परवाना नुतनीकरण करणे</x-slot>
    <x-slot name="heading">Renewal Of Plumber License / प्लंबर परवाना नुतनीकरण करणे</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">Applicant Details</h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">
                            <div class="col-md-4">
                                <label class="col-form-label" for="plumber_license_no">Enter Plumber License Number / प्लंबर परवाना क्रमांक प्रविष्ट करा<span class="text-danger">*</span></label>
                                <input class="form-control" id="plumber_license_no" name="plumber_license_no" type="text" placeholder="Enter Plumber License Number">
                                <span class="text-danger is-invalid plumber_license_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name">Name Of The Applicant / अर्जदाराचे नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_name" name="applicant_name" type="text" placeholder="Enter Applicant's Full Name" >
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="address">Applicant Address/ अर्जदाराचा पत्ता<span class="text-danger">*</span></label>
                                <textarea class="form-control" name="address" id="address" cols="30" rows="2" placeholder="Enter Address" ></textarea>
                                <span class="text-danger is-invalid address_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="mobile_no">
                                    Mobile Number / मोबाईल नंबर<span class="text-danger">*</span>
                                </label>
                                <input 
                                    class="form-control" 
                                    id="mobile_no" 
                                    name="mobile_no" 
                                    type="text"
                                    maxlength="10" 
                                    minlength="10"
                                    placeholder="Enter Mobile Number"
                                    oninput="this.value = this.value.replace(/[^0-9]/g, '')"
                                >
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="email_id"> Email Id / ईमेल आयडी<span class="text-danger"></span></label>
                                <input class="form-control" id="email_id" name="email_id" type="email" placeholder="Enter Email" >
                                <span class="text-danger is-invalid email_id_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="aadhar_no">
                                    Aadhar Number / आधार नं <span class="text-danger">*</span>
                                </label>
                                <input 
                                    class="form-control" 
                                    id="aadhar_no" 
                                    name="aadhar_no" 
                                    type="text"
                                    maxlength="12" 
                                    minlength="12"
                                    placeholder="Enter Aadhar Number"
                                    oninput="this.value = this.value.replace(/[^0-9]/g, '')"
                                >
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="zone">Zone / झोन<span class="text-danger">*</span></label>
                                <input class="form-control" id="zone" name="zone" type="text" placeholder="Enter zone" >
                                <span class="text-danger is-invalid zone_err"></span>
                            </div>

                            {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="ward_area">Ward Area / प्रभाग क्षेत्र<span class="text-danger">*</span></label>
                                    <select class="form-select" name="ward_area" id="ward_area" required>
                                        <option value="">Select Ward Area</option>
                                        @foreach ($wards as $ward)
                                        <option value="{{ $ward->name }}">{{ $ward->name }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid ward_area_err"></span>
                                </div> --}}


                            <div class="col-md-4">
                                <label class="col-form-label" for="education_qualification">Educational Qualification / शैक्षणिक पात्रता</label>
                                <input class="form-control" id="education_qualification" name="education_qualification" type="text" placeholder="Enter Educational Qualification">
                                <span class="text-danger is-invalid education_qualification_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="education_institutation">Educational Institution / शैक्षणिक संस्था</label>
                                <input class="form-control" id="education_institutation" name="education_institutation" type="text" placeholder="Enter Educational Institution">
                                <span class="text-danger is-invalid education_institutation_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="training_institute_name">Name of industrial training institute / औद्योगिक प्रशिक्षण संस्थेचे नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="training_institute_name" name="training_institute_name" type="text" placeholder="Enter Name of industrial training institute" >
                                <span class="text-danger is-invalid training_institute_name_err"></span>
                            </div>

                            <div class="col-md-4">
                            <label class="col-form-label" for="year_of_passing">
                                Year Of Passing / उत्तीर्ण झाल्याचे वर्ष<span class="text-danger">*</span>
                            </label>
                            <input 
                                class="form-control" 
                                id="year_of_passing" 
                                name="year_of_passing" 
                                type="text"
                                maxlength="4"
                                minlength="4"
                                placeholder="Enter Year Of Passing"
                                oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,4)"
                            >
                            <span class="text-danger is-invalid year_of_passing_err"></span>
                        </div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="have_experience">Are you having experienced / अनुभव आहे का ? <span class="text-danger">*</span></label>
                                <select class="form-select" name="have_experience" id="have_experience" >
                                    <option value="">Select option</option>
                                    @php
                                        $options = ['Yes', 'No'];
                                    @endphp
                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid have_experience_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="plumber_remark">Remark For Plumber License Renewal / प्लंबर लायसन्स नूतनीकरण साठी टिप्पणी<span class="text-danger">*</span></label>
                                <input class="form-control" id="plumber_remark" name="plumber_remark" type="text" placeholder="Enter Remark For Plumber License Renewal">
                                <span class="text-danger is-invalid plumber_remark_err"></span>
                            </div>

                           

                            {{-- <div class="col-md-4">
                                    <label class="col-form-label" for="nodues_documents">Upload Certificate Of No Dues / थकबाकी नसल्याचा दाखला अपलोड करा <span class="text-danger">*</span></label>
                                    <input class="form-control" id="nodues_documents" name="nodues_documents" type="file" required>
                                    <span class="text-danger is-invalid nodues_documents_err"></span>
                                </div> --}}

                            <div class="col-md-4">
                                <label class="col-form-label" for="educational_certificate_document">Upload Certificate Of Educational Qualification / शैक्षणिक पात्रतेचे प्रमाणपत्र अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="educational_certificate_document" name="educational_certificate_documents" type="file" >
                                <span class="text-danger is-invalid educational_certificate_document_err"></span>
                            </div>

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


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



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

</x-admin.layout>


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


{{-- <script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('application_documents');   

    if (!saveBtn || !form) return;  

    saveBtn.addEventListener('click', function () {
       
        if (fileInput) fileInput.removeAttribute('required');

        
        if (!form.checkValidity()) {
            form.reportValidity();
            if (fileInput) fileInput.setAttribute('required', 'required');
            return;
        }

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

        
        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

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

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

        
        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {
            textAlign: 'center',
            marginBottom: '18px',
            fontSize: '18px'
        });
        printTitle.textContent = 'Certificate of renewal plumber license';
        printClone.insertBefore(printTitle, printClone.firstChild);

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

       
        printClone.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(printClone);

        
        html2canvas(printClone, {
            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 margin = 10;

            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );

            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content.');
            }

            pdf.save('Renewal Plumber LicenseCertificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script> --}}

{{-- <script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('application_documents');   

    if (!saveBtn || !form) return;  

    // ✅ Custom field validation messages
    const messages = {
        plumber_license_no: 'Plumber License No is Required',
        applicant_name: 'Applicant Name is Required',
        address: 'Address is Required',
        mobile_no: 'Mobile No is Required',
        email_id: 'Email is Required',
        aadhar_no: 'Aadhar No is Required',
        zone: 'Zone is Required',
        training_institute_name: 'Training Institute Name is Required',
        year_of_passing: 'Year of Passing is Required',
        have_experience: 'Experience is Required',
        plumber_remark: 'Plumber Remark is Required',
        educational_certificate_document: 'Educational Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

    // 🧹 Function to clear previous error messages
    function clearErrors() {
        form.querySelectorAll('.error-message').forEach(e => e.remove());
    }

    function showError(input, message) {
    if (!input) return;
    let error = document.createElement('div');
    error.className = 'error-message';
    error.style.color = 'red';
    error.style.fontSize = '14px';
    error.style.marginTop = '4px';
    error.textContent = message;

    // ✅ Special case: Declaration checkbox — show error below its span
    if (input.name === 'is_correct_info') {
        const span = document.querySelector('.is_correct_info_err');
        if (span) {
            span.textContent = message;
            return;
        }
    }

    // Default: show after field
    input.insertAdjacentElement('afterend', error);
}

    saveBtn.addEventListener('click', function (e) {
        e.preventDefault(); // Stop form from auto-submitting

        clearErrors(); // remove old errors
        let hasError = false;

        // ✅ Validate all fields with custom messages
        for (const [field, message] of Object.entries(messages)) {
            const input = form.querySelector(`[name="${field}"]`);
            
            if (input) {
                const type = input.type;

                if ((type === 'checkbox' && !input.checked) || input.value.trim() === '') {
                    showError(input, message);
                    hasError = true;
                }
            }
        }

        if (hasError) return; // stop execution if any error

        // ✅ Remove "required" for JS-based validation
        if (fileInput) fileInput.removeAttribute('required');

        // ✅ Proceed to print logic if valid
        const uploadSection = document.getElementById('upload_section');
        const cardFooter = document.getElementById('card-footer');
        if (uploadSection) uploadSection.style.display = 'block';
        if (cardFooter) cardFooter.style.display = 'block';

        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const printClone = addContainer.cloneNode(true);

         const uploadSectionInClone = printClone.querySelector('#upload_section');
            if (uploadSectionInClone) {
                uploadSectionInClone.remove();
            }

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

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

        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {
            textAlign: 'center',
            marginBottom: '18px',
            fontSize: '18px'
        });
        printTitle.textContent = 'Certificate of Renewal Plumber License';
        printClone.insertBefore(printTitle, printClone.firstChild);

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

        printClone.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(printClone);

        html2canvas(printClone, {
            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 margin = 10;

            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );

            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content.');
            }

            pdf.save('Renewal_Plumber_License_Certificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script> --}}

{{-- <script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('application_documents');   

    if (!saveBtn || !form) return;  

    // ✅ Custom field validation messages
    const messages = {
        plumber_license_no: 'Plumber License No is Required',
        applicant_name: 'Applicant Name is Required',
        address: 'Address is Required',
        mobile_no: 'Mobile No is Required',
        email_id: 'Email is Required',
        aadhar_no: 'Aadhar No is Required',
        zone: 'Zone is Required',
        training_institute_name: 'Training Institute Name is Required',
        year_of_passing: 'Year of Passing is Required',
        have_experience: 'Experience is Required',
        plumber_remark: 'Plumber Remark is Required',
        educational_certificate_document: 'Educational Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

    // 🧹 Function to clear previous error messages
    function clearErrors() {
        form.querySelectorAll('.error-message').forEach(e => e.remove());
        const specialErr = document.querySelector('.is_correct_info_err');
        if (specialErr) specialErr.textContent = '';
    }

    function showError(input, message) {
        if (!input) return;
        let error = document.createElement('div');
        error.className = 'error-message';
        error.style.color = 'red';
        error.style.fontSize = '14px';
        error.style.marginTop = '4px';
        error.textContent = message;

        // ✅ Special case: Declaration checkbox — show error below its span
        if (input.name === 'is_correct_info') {
            const span = document.querySelector('.is_correct_info_err');
            if (span) {
                span.textContent = message;
                return;
            }
        }

        // Default: show after field
        input.insertAdjacentElement('afterend', error);
    }

    saveBtn.addEventListener('click', function (e) {
        e.preventDefault(); // Stop form from auto-submitting

        clearErrors(); // remove old errors
        let hasError = false;
        let firstErrorEl = null;

        // ✅ Validate all fields with custom messages
        for (const [field, message] of Object.entries(messages)) {
            const input = form.querySelector(`[name="${field}"]`);
            
            if (input) {
                const type = input.type;
                if ((type === 'checkbox' && !input.checked) || input.value.trim() === '') {
                    showError(input, message);
                    hasError = true;
                    if (!firstErrorEl) firstErrorEl = input;
                }
            }
        }

        // ✅ Additional Format Validation
        const aadhar = document.getElementById('aadhar_no')?.value.trim();
        const mobile = document.getElementById('mobile_no')?.value.trim();
        const email  = document.getElementById('email_id')?.value.trim();

        if (aadhar && !/^\d{12}$/.test(aadhar)) {
            const el = document.getElementById('aadhar_no');
            showError(el, 'Aadhar number must be 12 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        if (mobile && !/^\d{10}$/.test(mobile)) {
            const el = document.getElementById('mobile_no');
            showError(el, 'Mobile number must be 10 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            const el = document.getElementById('email_id');
            showError(el, 'Please enter a valid email.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        // ✅ Scroll to first invalid field
        if (hasError && firstErrorEl) {
            firstErrorEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
            firstErrorEl.focus();
            return;
        }

        // ✅ Remove "required" for JS-based validation
        if (fileInput) fileInput.removeAttribute('required');

        // ✅ Proceed to print logic if valid
        const uploadSection = document.getElementById('upload_section');
        const cardFooter = document.getElementById('card-footer');
        if (uploadSection) uploadSection.style.display = 'block';
        if (cardFooter) cardFooter.style.display = 'block';

        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const printClone = addContainer.cloneNode(true);
        const uploadSectionInClone = printClone.querySelector('#upload_section');
        if (uploadSectionInClone) uploadSectionInClone.remove();

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

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

        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {
            textAlign: 'center',
            marginBottom: '18px',
            fontSize: '18px'
        });
        printTitle.textContent = 'Certificate of Renewal Plumber License';
        printClone.insertBefore(printTitle, printClone.firstChild);

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

        printClone.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(printClone);

        html2canvas(printClone, {
            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 margin = 10;

            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );

            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content.');
            }

            pdf.save('Renewal_Plumber_License_Certificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script> --}}


{{-- <script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('application_documents');   

    if (!saveBtn || !form) return;  

    const messages = {
        plumber_license_no: 'Plumber License No is Required',
        applicant_name: 'Applicant Name is Required',
        address: 'Address is Required',
        mobile_no: 'Mobile No is Required',
        email_id: 'Email is Required',
        aadhar_no: 'Aadhar No is Required',
        zone: 'Zone is Required',
        training_institute_name: 'Training Institute Name is Required',
        year_of_passing: 'Year of Passing is Required',
        have_experience: 'Experience is Required',
        plumber_remark: 'Plumber Remark is Required',
        educational_certificate_document: 'Educational Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

    function clearErrors() {
        form.querySelectorAll('.error-message').forEach(e => e.remove());
        const specialErr = document.querySelector('.is_correct_info_err');
        if (specialErr) specialErr.textContent = '';
    }

    function showError(input, message) {
        if (!input) return;
        let error = document.createElement('div');
        error.className = 'error-message';
        error.style.color = 'red';
        error.style.fontSize = '14px';
        error.style.marginTop = '4px';
        error.textContent = message;

        if (input.name === 'is_correct_info') {
            const span = document.querySelector('.is_correct_info_err');
            if (span) {
                span.textContent = message;
                return;
            }
        }
        input.insertAdjacentElement('afterend', error);
    }

    saveBtn.addEventListener('click', function (e) {
        e.preventDefault();

        clearErrors();
        let hasError = false;
        let firstErrorEl = null;

        for (const [field, message] of Object.entries(messages)) {
            const input = form.querySelector(`[name="${field}"]`);
            if (input) {
                const type = input.type;
                if ((type === 'checkbox' && !input.checked) || input.value.trim() === '') {
                    showError(input, message);
                    hasError = true;
                    if (!firstErrorEl) firstErrorEl = input;
                }
            }
        }

        const aadhar = document.getElementById('aadhar_no')?.value.trim();
        const mobile = document.getElementById('mobile_no')?.value.trim();
        const email  = document.getElementById('email_id')?.value.trim();

        if (aadhar && !/^\d{12}$/.test(aadhar)) {
            const el = document.getElementById('aadhar_no');
            showError(el, 'Aadhar number must be 12 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        if (mobile && !/^\d{10}$/.test(mobile)) {
            const el = document.getElementById('mobile_no');
            showError(el, 'Mobile number must be 10 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            const el = document.getElementById('email_id');
            showError(el, 'Please enter a valid email.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

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

        if (fileInput) fileInput.removeAttribute('required');

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

        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const printClone = addContainer.cloneNode(true);
        const uploadSectionInClone = printClone.querySelector('#upload_section');
        if (uploadSectionInClone) uploadSectionInClone.remove();

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

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

        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {
            textAlign: 'center',
            marginBottom: '18px',
            fontSize: '18px'
        });
        printTitle.textContent = 'Certificate of Renewal Plumber License';
        printClone.insertBefore(printTitle, printClone.firstChild);

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

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

        // ✅ SHOW SELECTED VALUE FOR 'have_experience'
        const experienceSelect = printClone.querySelector('#have_experience');
        if (experienceSelect) {
            const selectedText = experienceSelect.options[experienceSelect.selectedIndex].text;
            const displayDiv = document.createElement('div');
            displayDiv.style.fontWeight = 'bold';
            displayDiv.style.marginTop = '4px';
            displayDiv.textContent = selectedText;
            experienceSelect.insertAdjacentElement('afterend', displayDiv);
            experienceSelect.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(printClone);

        html2canvas(printClone, {
            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 margin = 10;

            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );

            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content.');
            }

            pdf.save('Renewal_Plumber_License_Certificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script> --}}

{{-- <script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('application_documents');   

    if (!saveBtn || !form) return;  

    const messages = {
        plumber_license_no: 'Plumber License No is Required',
        applicant_name: 'Applicant Name is Required',
        address: 'Address is Required',
        mobile_no: 'Mobile No is Required',
        email_id: 'Email is Required',
        aadhar_no: 'Aadhar No is Required',
        zone: 'Zone is Required',
        training_institute_name: 'Training Institute Name is Required',
        year_of_passing: 'Year of Passing is Required',
        have_experience: 'Experience is Required',
        plumber_remark: 'Plumber Remark is Required',
        educational_certificate_document: 'Educational Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

    function clearErrors() {
        form.querySelectorAll('.error-message').forEach(e => e.remove());
        const specialErr = document.querySelector('.is_correct_info_err');
        if (specialErr) specialErr.textContent = '';
    }

    function showError(input, message) {
        if (!input) return;
        let error = document.createElement('div');
        error.className = 'error-message';
        error.style.color = 'red';
        error.style.fontSize = '14px';
        error.style.marginTop = '4px';
        error.textContent = message;

        if (input.name === 'is_correct_info') {
            const span = document.querySelector('.is_correct_info_err');
            if (span) {
                span.textContent = message;
                return;
            }
        }
        input.insertAdjacentElement('afterend', error);
    }

    saveBtn.addEventListener('click', function (e) {
        e.preventDefault();

        clearErrors();
        let hasError = false;
        let firstErrorEl = null;

        for (const [field, message] of Object.entries(messages)) {
            const input = form.querySelector(`[name="${field}"]`);
            if (input) {
                const type = input.type;
                if ((type === 'checkbox' && !input.checked) || input.value.trim() === '') {
                    showError(input, message);
                    hasError = true;
                    if (!firstErrorEl) firstErrorEl = input;
                }
            }
        }

        const aadhar = document.getElementById('aadhar_no')?.value.trim();
        const mobile = document.getElementById('mobile_no')?.value.trim();
        const email  = document.getElementById('email_id')?.value.trim();

        if (aadhar && !/^\d{12}$/.test(aadhar)) {
            const el = document.getElementById('aadhar_no');
            showError(el, 'Aadhar number must be 12 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        if (mobile && !/^\d{10}$/.test(mobile)) {
            const el = document.getElementById('mobile_no');
            showError(el, 'Mobile number must be 10 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            const el = document.getElementById('email_id');
            showError(el, 'Please enter a valid email.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

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

        if (fileInput) fileInput.removeAttribute('required');

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

        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const printClone = addContainer.cloneNode(true);
        const uploadSectionInClone = printClone.querySelector('#upload_section');
        if (uploadSectionInClone) uploadSectionInClone.remove();

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

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

        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {
            textAlign: 'center',
            marginBottom: '18px',
            fontSize: '18px'
        });
        printTitle.textContent = 'Certificate of Renewal Plumber License';
        printClone.insertBefore(printTitle, printClone.firstChild);

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

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

        // ✅ FIX: SHOW SELECTED VALUE FOR 'have_experience' PROPERLY
        const experienceSelect = form.querySelector('#have_experience');
        if (experienceSelect) {
            const selectedText = experienceSelect.options[experienceSelect.selectedIndex]?.text || '';
            const experienceFieldInClone = printClone.querySelector('#have_experience');
            if (experienceFieldInClone) {
                const displayDiv = document.createElement('div');
                displayDiv.style.fontWeight = 'bold';
                displayDiv.style.marginTop = '4px';
                displayDiv.textContent = selectedText !== '' ? selectedText : 'N/A';
                experienceFieldInClone.insertAdjacentElement('afterend', displayDiv);
                experienceFieldInClone.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(printClone);

        html2canvas(printClone, {
            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 margin = 10;

            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );

            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content.');
            }

            pdf.save('Renewal_Plumber_License_Certificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script> --}}

<script>
document.addEventListener('DOMContentLoaded', function () {
    const saveBtn   = document.getElementById('saveAndPrintBtn');
    const form      = document.getElementById('addForm');
    const fileInput = document.getElementById('application_documents');   

    if (!saveBtn || !form) return;  

    const messages = {
        plumber_license_no: 'Plumber License No is Required',
        applicant_name: 'Applicant Name is Required',
        address: 'Address is Required',
        mobile_no: 'Mobile No is Required',
        //email_id: 'Email is Required',
        aadhar_no: 'Aadhar No is Required',
        zone: 'Zone is Required',
        training_institute_name: 'Training Institute Name is Required',
        year_of_passing: 'Year of Passing is Required',
        have_experience: 'Experience is Required',
        plumber_remark: 'Plumber Remark is Required',
        educational_certificate_document: 'Educational Document is Required',
        is_correct_info: 'Please Accept the Declaration'
    };

    function clearErrors() {
        form.querySelectorAll('.error-message').forEach(e => e.remove());
        const specialErr = document.querySelector('.is_correct_info_err');
        if (specialErr) specialErr.textContent = '';
    }

    function showError(input, message) {
        if (!input) return;
        let error = document.createElement('div');
        error.className = 'error-message';
        error.style.color = 'red';
        error.style.fontSize = '14px';
        error.style.marginTop = '4px';
        error.textContent = message;

        if (input.name === 'is_correct_info') {
            const span = document.querySelector('.is_correct_info_err');
            if (span) {
                span.textContent = message;
                return;
            }
        }
        input.insertAdjacentElement('afterend', error);
    }

    saveBtn.addEventListener('click', function (e) {
        e.preventDefault();

        clearErrors();
        let hasError = false;
        let firstErrorEl = null;

        for (const [field, message] of Object.entries(messages)) {
            const input = form.querySelector(`[name="${field}"]`);
            if (input) {
                const type = input.type;
                if ((type === 'checkbox' && !input.checked) || input.value.trim() === '') {
                    showError(input, message);
                    hasError = true;
                    if (!firstErrorEl) firstErrorEl = input;
                }
            }
        }

        const aadhar = document.getElementById('aadhar_no')?.value.trim();
        const mobile = document.getElementById('mobile_no')?.value.trim();
        const email  = document.getElementById('email_id')?.value.trim();

        if (aadhar && !/^\d{12}$/.test(aadhar)) {
            const el = document.getElementById('aadhar_no');
            showError(el, 'Aadhar number must be 12 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        if (mobile && !/^\d{10}$/.test(mobile)) {
            const el = document.getElementById('mobile_no');
            showError(el, 'Mobile number must be 10 digits.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            const el = document.getElementById('email_id');
            showError(el, 'Please enter a valid email.');
            if (!firstErrorEl) firstErrorEl = el;
            hasError = true;
        }

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

        if (fileInput) fileInput.removeAttribute('required');

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

        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const printClone = addContainer.cloneNode(true);
        const uploadSectionInClone = printClone.querySelector('#upload_section');
        if (uploadSectionInClone) uploadSectionInClone.remove();

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

        Array.from(printClone.querySelectorAll('*')).forEach(el => {
            el.style.fontSize = '16px';
            el.style.margin = '4px 0';
            el.style.fontWeight = 'normal'; // ✅ remove boldness
        });

        const printTitle = document.createElement('h2');
        Object.assign(printTitle.style, {
            textAlign: 'center',
            marginBottom: '18px',
            fontSize: '18px'
        });
        printTitle.textContent = 'Certificate of Renewal Plumber License';
        printClone.insertBefore(printTitle, printClone.firstChild);

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

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

        // ✅ Fixed uniform style for "Are you having experienced"
        const experienceSelect = form.querySelector('#have_experience');
        if (experienceSelect) {
            const selectedText = experienceSelect.options[experienceSelect.selectedIndex]?.text || '';
            const experienceFieldInClone = printClone.querySelector('#have_experience');
            if (experienceFieldInClone) {
                const displayDiv = document.createElement('div');
                displayDiv.style.border = '1px solid #ced4da';
                displayDiv.style.borderRadius = '4px';
                displayDiv.style.padding = '6px 10px';
                displayDiv.style.fontSize = '14px';
                displayDiv.style.height = '38px';
                displayDiv.style.display = 'flex';
                displayDiv.style.alignItems = 'center';
                displayDiv.style.backgroundColor = '#fff';
                displayDiv.style.fontWeight = 'normal'; // ✅ ensure non-bold
                displayDiv.textContent = selectedText !== '' ? selectedText : 'N/A';
                experienceFieldInClone.parentNode.replaceChild(displayDiv, experienceFieldInClone);
            }
        }

        let printContainer = document.getElementById('printContainer');
        if (!printContainer) {
            printContainer = document.createElement('div');
            printContainer.id = 'printContainer';
            printContainer.style.position = 'fixed';
            printContainer.style.left = '-9999px';
            document.body.appendChild(printContainer);
        }
        printContainer.innerHTML = '';
        printContainer.appendChild(printClone);

        html2canvas(printClone, {
            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 margin = 10;

            pdf.addImage(
                imgData, 'JPEG',
                margin, margin,
                pdf.internal.pageSize.getWidth() - margin * 2,
                pdf.internal.pageSize.getHeight() - margin * 2
            );

            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content.');
            }

            pdf.save('Renewal_Plumber_License_Certificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script>








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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('renewal-plumber-license.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>
document.addEventListener('DOMContentLoaded', function () {
    const existingConInput = document.getElementById('applicant_name');

    if (existingConInput) {
        existingConInput.addEventListener('input', function () {
            // Sirf letters (uppercase/lowercase) aur spaces allow karna ho to use [^a-zA-Z\s]
            this.value = this.value.replace(/[^a-zA-Z]/g, '');
        });
    }
});
</script>
