<x-admin.layout>
    <x-slot name="title">Plumber License / प्लंबर परवाना</x-slot>
    <x-slot name="heading"> 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">

                    <div class="card-body">
                        <div class="mb-3 row">
                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name">Applicant Full Name / अर्जदाराचे पूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_name" name="applicant_name" type="text" value="{{ $user->name }}" placeholder="Enter Applicant Name" required>
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="address">Applicant Full Address / अर्जदाराचा पूर्ण पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="address" name="address" type="text" placeholder="Enter Name Of New Owner" required>{{ $user->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">Applicant Mobile No / मोबाईल नंबर<span class="text-danger">*</span></label>
                                <input class="form-control" id="mobile_no" name="mobile_no" value="{{ $user->mobile }}" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" type="text"
                                    placeholder="Enter Mobile Number" required>
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>

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

                            <div class="col-md-4">
                                <label class="col-form-label" for="aadhar_no">Applicant Adhaar No / आधार क्रमांक <span class="text-danger">*</span></label>
                                <input class="form-control" id="aadhar_no" name="aadhar_no" value='{{ $user->aadhar_no }}' oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" type="text"
                                    placeholder="Enter Aadhar Card No" required>
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>

                        </div>
                    </div>

                    {{-- <div class="card">
                        <div class="card-body">

                            @csrf
                            <div class="col-md-4">
                                <input class="form-control" id="marchantid" name="marchantid" type="hidden" value="MBMCCORE">
                                <span class="text-danger is-invalid marchantid_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="connection_no">Connection No<span class="text-danger">*</span></label>
                                <input class="form-control" id="connection_no" name="connection_no" type="text" placeholder="Enter Connection No">
                                <span class="text-danger is-invalid connection_no_err"></span>
                            </div>

                            <button type="Search" class="btn btn-primary mt-2" id="searchdetails">Search</button>
                        </div>
                    </div> --}}



                    {{-- <div class="card">
                        <div class="card-header">
                            <h4 class="card-title">Water Details</h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-3 row">
                                <div class="col-md-4">
                                    <label class="col-form-label" for="Property_Owner_Name">Owner Name/मालकाचे नाव<span class="text-danger">*</span></label>
                                    <input class="form-control" id="Property_Owner_Name" name="Property_Owner_Name" type="text" placeholder="Enter Owner Name" required readonly>
                                    <span class="text-danger is-invalid Property_Owner_Name_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Full_Address_Of_The_Property"> Owner Address/मालकाचा पत्ता<span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="Full_Address_Of_The_Property" id="Full_Address_Of_The_Property" cols="30" rows="2" placeholder="Enter  Address" required readonly></textarea>
                                    <span class="text-danger is-invalid Full_Address_Of_The_Property_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Ward">Ward Area / प्रभाग क्षेत्र</label>
                                    <input class="form-control" name="Ward" id="Ward" placeholder="Enter Ward Area" required readonly>
                                    <span class="text-danger is-invalid Ward_err"></span>
                                </div>

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

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Water_Connection_Size">Water Connection Size<span class="text-danger">*</span></label>
                                    <input class="form-control" id="Water_Connection_Size" name="Water_Connection_Size" type="text" placeholder="Enter Water Connection Size" required readonly>
                                    <span class="text-danger is-invalid Water_Connection_Size_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Connection_Type">Connection Type<span class="text-danger">*</span></label>
                                    <input class="form-control" name="Connection_Type" id="Connection_Type" type="text" placeholder="Enter Connection Type" required readonly>
                                    <span class="text-danger is-invalid Connection_Type_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Water_Connection_Usage">Water Connection Usage <span class="text-danger">*</span></label>
                                    <input class="form-control" id="Water_Connection_Usage" name="Water_Connection_Usage" type="text" placeholder="Enter Water Connection Usage" required readonly>
                                    <span class="text-danger is-invalid Water_Connection_Usage_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="OutstandingAmt"> Total Outstanding Payable/ एकूण थकबाकी बिल भरले?<span class="text-danger">*</span></label>
                                    <input class="form-control" id="OutstandingAmt" name="OutstandingAmt" type="text" required readonly>
                                    <span class="text-danger is-invalid OutstandingAmt_err"></span>
                                </div>
                                <div class="col-md-4 mt-4">
                                    <button type="button" id="payaccentech" class="btn btn-success" target="_blank"
                                        onclick="window.location.href='https://watertax.nagarkaryavali.com/FrmWTConnSearch.aspx?@=AD65C7423AEA4530E3CB0528C8EFFFE4185BBCFBFA074578B362FC23AB6A7765'">Pay</button>
                                </div>

                            </div>
                        </div>
                    </div> --}}

                    {{-- <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data"> --}}
                    @csrf

                    <div class="card-header">
                        <h4 class="card-title">Add Details</h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">

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

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="address">Applicant's Full Address / अर्जदाराचा संपूर्ण पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="address" id="address" cols="30" rows="2" placeholder="Enter Address" required></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" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" type="text" placeholder="Enter Mobile Number" required>
                                <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" required>
                                <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" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" type="text" placeholder="Enter Aadhar Number" required>
                                <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" name="zone" id="zone" placeholder="Enter Zone" >
                                <span class="text-danger is-invalid zone_err"></span>
                            </div>

                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="house_no">House Number </label> {{-- <span class="text-danger">*</span> --}}
                                    <input type="number" class="form-control" id="house_no" name="house_no" placeholder="Enter House Number" >
                                    <span class="text-danger" id="house_no_error"></span>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="land_mark">Land Mark <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="land_mark" name="land_mark" placeholder="Enter Landmark" >
                                    <span class="text-danger" id="land_mark_error"></span>
                                </div>
                            </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="zone">Zone / झोन<span class="text-danger">*</span></label>
                                <select class="form-select" name="zone" id="zone" required>
                                    <option value="">Select Zone</option>
                                    @foreach ($zones as $zone)
                                        <option value="{{ $zone->name }}">{{ $zone->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid zone_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">Passing Year / उत्तीर्ण झाल्याचे वर्ष<span class="text-danger">*</span></label>
                                <input class="form-control" id="year_of_passing" name="year_of_passing" type="text" placeholder="Enter Year Of Passing" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="4" minlength="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">Have Experience / अनुभव आहे का ? <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="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="nodues_documents">Educational documents certificate and experience certificate / शैक्षणिक कागदपत्रांचे प्रमाणपत्र आणि अनुभव प्रमाणपत्र <span class="text-danger">*</span></label>
                                <input class="form-control" id="nodues_documents" name="nodues_documents" type="file" >
                                <span class="text-danger is-invalid nodues_documents_err"></span>
                            </div>

                             <div class="col-md-4">
                                <label class="col-form-label" for="resident_document">Resident Documents/राहणीसंबंधी दस्तऐवज </label>
                                <input class="form-control" id="resident_documents" name="resident_documents" type="file">
                                <span class="text-danger is-invalid resident_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>
                                    <span class="text-danger is-invalid is_correct_info_err"></span>
                                </div>
                                
                            </div> --}}
                          <label class="col-form-label" for="is_correct_info">Declaration / घोषणापत्र:</label>
<div class="col-md-12">
    <div class="form-check d-flex 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>
    <span class="text-danger mt-1 d-block is_correct_info_err"></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 Trade 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('Trade 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 validation messages
    const messages = {
        zone: 'Zone is Required',
        land_mark: 'Landmark is Required',
        training_institute_name: 'Training Institute is Required',
        year_of_passing: 'Year of Passing is Required',
        have_experience: 'Experience is Required',
        nodues_documents: 'Documents are Required',
        is_correct_info: 'Please Accept the Declaration'
    };

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

        // Remove previous errors
        form.querySelectorAll('.error-message').forEach(el => el.remove());
        form.querySelectorAll('.error-border').forEach(el => el.classList.remove('error-border'));

        // Temporarily remove 'required' from file input
        if (fileInput) fileInput.removeAttribute('required');

        let isValid = true;

        // 🔹 Loop through each custom message key
        Object.keys(messages).forEach(id => {
            const input = document.getElementById(id);
            if (input) {
                let value = (input.type === 'checkbox') ? input.checked : input.value.trim();
                if (!value) {
                    isValid = false;
                    input.classList.add('error-border');

                    // ✅ Special case for Declaration checkbox
                    if (id === 'is_correct_info') {
                        const span = document.querySelector('.is_correct_info_err');
                        if (span) {
                            span.textContent = messages[id];
                            span.style.color = 'red';
                            span.style.fontSize = '13px';
                            return; // Skip normal insertAdjacentElement
                        }
                    }

                    // Create and show inline error message for other fields
                    const error = document.createElement('div');
                    error.className = 'error-message';
                    error.style.color = 'red';
                    error.style.fontSize = '13px';
                    error.style.marginTop = '4px';
                    error.textContent = messages[id];
                    input.insertAdjacentElement('afterend', error);
                }
            }
        });

        // 🔹 Also validate normal HTML5 fields
        if (!form.checkValidity()) {
            form.reportValidity();
            isValid = false;
        }

        if (!isValid) {
            if (fileInput) fileInput.setAttribute('required', 'required');
            return;
        }

        // ✅ If all fields valid → show upload section
        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;

        // ✅ Prepare printable clone
        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 Trade 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);

        // ✅ Generate PDF
        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('Trade Plumber LicenseCertificate.pdf');
            saveBtn.style.display = 'none';
        }).finally(() => {
            if (fileInput) fileInput.setAttribute('required', 'required');
        });
    });
});
</script>





{{-- Add --}}
<script>
    $('#searchdetails').on('click', function(e) {
        e.preventDefault();

        let formData = {
            marchantid: $('#marchantid').val(),
            connection_no: $('#connection_no').val(),
            _token: $('input[name="_token"]').val()
        };

        $.ajax({
            url: '{{ route('fetch.water.details') }}',
            method: 'POST',
            data: formData,
            datatype: JSON,
            success: function(response) {
                console.log("Encrypted Data:", response.jsonData.encr_request);

                const decryptedData = JSON.parse(response.jsonData.encr_request); // Replace with actual decryption function

                console.log("Decrypted Data:", decryptedData['connectionDetails'].Water_Connection_Number);

                if (decryptedData && decryptedData['connectionDetails']) {
                    $('#Connection_Type').val(decryptedData['connectionDetails'].Connection_Type);
                    $('#House_Number').val(decryptedData['connectionDetails'].House_Number);
                    $('#Property_Owner_Name').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    $('#Full_Address_Of_The_Property').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    $('#Water_Connection_Size').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    $('#Water_Connection_Usage').val(decryptedData['connectionDetails'].Water_Connection_Usage);
                    $('#zone').val(decryptedData['connectionDetails'].Zone);
                    $('#Ward').val(decryptedData['connectionDetails'].Ward);
                    $('#OutstandingAmt').val(decryptedData['connectionDetails'].OutstandingAmt);
                    // $('#water_connection_no').val(decryptedData['connectionDetails'].Water_Connection_Number);
                    // $('#applicant_full_name').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    // $('#address').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    // // $('#address').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    // $('#house_no').val(decryptedData['connectionDetails'].Water_Connection_Usage);
                    // $('#owner_add').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    // $('#ward').val(decryptedData['connectionDetails'].Ward);
                } else {
                    console.error("connectionDetails is missing or undefined");
                }
            },

            error: function(xhr) {
                console.error(xhr.responseText);
            }
        });
    });


    $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('trade-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', () => {

    // --- Detect field type based on name/id/placeholder ---
    function detectFieldType(input) {
        const s = ((input.name || '') + ' ' + (input.id || '') + ' ' + (input.placeholder || '')).toLowerCase();
        if (/\baadhaar|\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|\balternet_email|\balternate_email|\bemail_id/.test(s)) return 'email';
        return null;
    }

    // --- Get associated 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 === '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 '';
        }
        return '';
    }

    // --- Validate a single field ---
    function validateField(input) {
        const type = detectFieldType(input);
        const required = input.hasAttribute('required');
        const value = (input.value || '').trim();

        // If type is recognized, validate format
        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 visible 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));
    });

    // Expose global function for other scripts
    window.validateAllFields = validateAllFields;

});
</script>


<script>
document.addEventListener('DOMContentLoaded', function () {
    const existingConInput = document.getElementById('house_no');

    if (existingConInput) {
        existingConInput.addEventListener('input', function (e) {
            // Remove any non-digit characters
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    }
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const existingConInput = document.getElementById('zone');

    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>




