<x-admin.layout>
    <x-slot name="title">Granting permission for laying underground telecommunication ducts/भूमिगत दूरसंचार वाहिनी</x-slot>
    <x-slot name="heading">Granting permission for laying underground telecommunication ducts/भूमिगत दूरसंचार वाहिनी</x-slot>

    <!-- Add Form -->
    <div class="row" id="addContainer">
        <div class="col-sm-12">
            <div class="card">
                <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                    @csrf

                    <div class="card-header">
                        <h4 class="card-title">Add Details</h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">
                           <div class="col-md-4">
    <label class="col-form-label" for="f_name">
        Applicant's Full Name / अर्जदाराचे संपूर्ण नाव
        <span class="text-danger">*</span>
    </label>
    <input class="form-control" id="f_name" name="f_name" type="text"
        placeholder="Enter Full Name" required
        onkeypress="return onlyLetters(event)">
    <span class="text-danger is-invalid f_name_err"></span>
</div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="m_name">Applicant Type ( Indivisual/Company) / अर्ज प्रकार (वैयक्तिक / कंपनी) <span class="text-danger">*</span></label>
                                <input class="form-control" id="m_name" name="m_name" type="text" placeholder="Enter Applicant Type" required>
                                <span class="text-danger is-invalid m_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="l_name">Applicant's Full Address / अर्जदाराचा संपूर्ण पत्ता  <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="l_name" name="l_name" type="text" placeholder="Enter Full address" required></textarea>
                                <span class="text-danger is-invalid l_name_err"></span>
                            </div>
                            <div class="col-md-3">
                                <label class="col-form-label" for="ward_area">Ward Type<span class="text-danger">*</span></label>
                                <select class="form-select" name="ward_area" id="ward_area" required>
                                    <option value="">Select Ward</option>
                                    @foreach ($options as $ward)
                                        <option value="{{ $ward->id }}">{{ $ward->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_err"></span>
                            </div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="mobile_num">Mobile Number<span class="text-danger">*</span></label>
                                <input class="form-control" id="mobile_num" name="mobile_num" type="text" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Mobile Number" required>
                                <span class="text-danger is-invalid mobile_num_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="email">Email Id<span class="text-danger">*</span></label>
                                <input class="form-control" id="email" name="email" type="email" placeholder="Enter Name of Company" required>
                                <span class="text-danger is-invalid email_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="aadhar_num">Aadhar Number<span class="text-danger">*</span></label>
                                <input class="form-control" id="aadhar_num" name="aadhar_num" type="text" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" placeholder="Enter Aadhar  Card Number" required>
                                <span class="text-danger is-invalid aadhar_num_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="property_num">Name Of Company<span class="text-danger">*</span></label>
                                <input class="form-control" id="property_num" name="property_num" type="text" placeholder="Enter Name OF ComPany" required>
                                <span class="text-danger is-invalid property_num_err"></span>
                            </div>



                            <div class="col-md-6">
                                <label class="col-form-label" for="address">Address of the Road for cutting / रस्ता खोदण्याच्या ठिकाणाचा पत्ता <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-3">
                                <label class="col-form-label" for="road_type">रस्त्याचे प्रकार<span class="text-danger">*</span></label>
                                <select class="form-select" name="road_type" id="road_type" required>
                                    <option value="" disabled selected> -- Select -- </option>
                                   @foreach ($roadtype as $road)
                                    <option value="{{ $road->id }}">{{ $road->road_type }}</option>
                                   @endforeach
                                </select>
                                <span class="text-danger is-invalid road_type_err"></span>
                                <div class="selected-value d-none" id="road_type"></div>

                            </div> --}}

                             {{-- <div class="col-md-3">
                                <label class="col-form-label" for="road_cutting_purpose">Purpose of Road Cutting / रस्ता खोदण्याचे कारण <span class="text-danger">*</span></label>
                                <select name="road_cutting_purpose" id="road_cutting_purpose" placeholder="Select Purpose of Road Cutting" class="form-select" required>
                                        <option value="">Select Road Purpose</option>
                                        <option value="Faults">Faults</option>
                                        <option value="Cable Shifting">Cable Shifting</option>
                                        <option value="New Connection">New Connection</option>
                                        <option value="Optical Fibre">Optical Fibre</option>
                                        <option value="New Cable Laying">New Cable Laying</option>
                                        <option value="Gas pipeline connection">Gas pipeline connection</option>
                                        <option value="any other">any other</option>
                                    </select>
                                    <span class="text-danger is-invalid road_cutting_purpose_err"></span>
                                     <div class="selected-value d-none" id="road_cutting_purpose"></div>
                            </div> --}}


                            <div class="col-md-3">
    <label class="col-form-label" for="road_cutting_purpose">
        Purpose of Road Cutting / रस्ता खोदण्याचे कारण <span class="text-danger">*</span>
    </label>
    <select name="road_cutting_purpose" id="road_cutting_purpose" class="form-select" required>
        <option value="">Select Road Purpose</option>
        <option value="Faults">Faults</option>
        <option value="Cable Shifting">Cable Shifting</option>
        <option value="New Connection">New Connection</option>
        <option value="Optical Fibre">Optical Fibre</option>
        <option value="New Cable Laying">New Cable Laying</option>
        <option value="Gas pipeline connection">Gas pipeline connection</option>
        <option value="any other">any other</option>
    </select>
    <span class="text-danger is-invalid road_cutting_purpose_err"></span>

    <!-- ✅ Fix duplicate ID here -->
    <div class="selected-value d-none" id="road_cutting_purpose_text"></div>
</div>


                            



                            <div class="col-md-3">
                                <label class="col-form-label" for="locationame">Name Of Locations<span class="text-danger">*</span></label>
                                <input class="form-control" id="locationame" name="locationame" type="text" placeholder="Name Of Location" required>
                                <span class="text-danger is-invalid locationame_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label class="col-form-label" for="no_duct">Number of duct/नलिकांची संख्या<span class="text-danger">*</span></label>
                                <input class="form-control" id="no_duct" name="no_duct" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Length" required>
                                <span class="text-danger is-invalid no_duct_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label class="col-form-label" for="no_chamber">number of chamber /चेंबरची संख्या<span class="text-danger">*</span></label>
                                <input class="form-control" id="no_chamber" name="no_chamber" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Length" required>
                                <span class="text-danger is-invalid no_chamber_err"></span>
                            </div>

                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="length_road">रस्त्याची लांबी (मीटर)<span class="text-danger">*</span></label>
                                <input class="form-control" id="length_road" name="length_road" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Length" required>
                                <span class="text-danger is-invalid length_road_err"></span>
                            </div> --}}

                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="width_road">रस्त्याची रुंदी (मीटर)<span class="text-danger">*</span></label>
                                <input class="form-control" id="width_road" name="width_road" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Width" required>
                                <span class="text-danger is-invalid width_road_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label class="col-form-label" for="length_width">रस्त्याची लांबीरुंदी (चो. मीटर)<span class="text-danger">*</span></label>
                                <input class="form-control" id="length_width" name="length_width" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Length & Width" required>
                                <span class="text-danger is-invalid length_width_err"></span>
                            </div> --}}

                            <div class="col-md-3">
                                <label class="col-form-label" for="digging_size">खोदण्याचे आकार (मीटर)<span class="text-danger">*</span></label>
                                <input class="form-control" id="digging_size" name="digging_size" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter Digging size" required>
                                <span class="text-danger is-invalid digging_size_err"></span>
                            </div>

                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="start_point">खोदाईचा प्रारंभिक बिंदु <span class="text-danger">*</span></label>
                                <input class="form-control" id="start_point" name="start_point" type="text" placeholder="Enter Starting Point" required>
                                <span class="text-danger is-invalid start_point_err"></span>
                            </div> --}}

                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="end_point">खोदाईचा अंतिम बिंदूः <span class="text-danger">*</span></label>
                                <input class="form-control" id="end_point" name="end_point" type="text"  placeholder="Enter Ending Point" required>
                                <span class="text-danger is-invalid end_point_err"></span>
                            </div> --}}


                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="latitude">अक्षांश<span class="text-danger">*</span></label>
                                <input class="form-control" id="latitude" name="latitude" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter latitude" required>
                                <span class="text-danger is-invalid latitude_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label class="col-form-label" for="longitude">रेखांश<span class="text-danger">*</span></label>
                                <input class="form-control" id="longitude" name="longitude" type="number" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" placeholder="Enter longitude" required>
                                <span class="text-danger is-invalid longitude_err"></span>
                            </div> --}}


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

                              <table class="table table-bordered mt-2" id="roadTable">
                                <thead style="background-color: #eff2f7;">
                                    <tr>
                                        <th>Road Type</th>
                                        <th>Start Point</th>
                                        <th>End Point</th>
                                        <th>Length (m)</th>
                                        <th>Defect Liability</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="roadTableBody">
                                    <tr>
                                        <td>
                                            <select name="roadtype[]" class="form-select" >
                                                <option value="">Select Road Type</option>
                                                @foreach ($roadtype as $option)
                                                    <option value="{{ $option->id }}">{{ $option->road_type }}</option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text" name="startpoint[]" class="form-control" placeholder="Enter Start Point">
                                        </td>
                                        <td>
                                            <input type="text" name="endpoint[]" class="form-control" placeholder="Enter End Point" >
                                        </td>
                                        <td>
                                            <input type="number" name="road_length[]" class="form-control" placeholder="Enter Length" >
                                        </td>
                                        <td>
                                            <select name="defect_factor[]" class="form-select" >
                                                <option value="">Select Defect Liability</option>
                                                @foreach ($multifactor as $option)
                                                    <option value="{{ $option->id }}">{{ $option->item }}</option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-danger removeRow">Delete</button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>

                            <button type="button" class="btn btn-primary" id="addmore" style="width: 10%;">Add More</button>
                            <div class="row">
                             <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="government_docs">Documents prescribed by the government/ शासनाने  विहित केलेली कागदपत्रे <span class="text-danger">*</span></label>
                                    <input class="form-control" id="government_docs"  accept=".pdf, image/*" name="government_docs" type="file" required>
                                    <span class="text-danger is-invalid government_docs_err"></span>
                                </div>

                                 <div class="col-md-4 mb-2">
                                    
                                   <label class="col-form-label" for="outstanding_docs">
                                        Upload Map / नकाशा अपलोड करा <span class="text-danger">*</span>
                                    </label>

                                    <input class="form-control" id="outstanding_docs"  accept=".pdf, image/*" name="outstanding_docs" type="file" required>
                                    <span class="text-danger is-invalid outstanding_docs_err"></span>
                                </div>

                                 <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="tax_docs">Tax clearance/ टॅक्स क्लिअरन्स<span class="text-danger">*</span></label>
                                    <input class="form-control" id="tax_docs" name="tax_docs"  accept=".pdf, image/*" type="file" required>
                                    <span class="text-danger is-invalid tax_docs_err"></span>
                                </div>


                                 <div class="col-md-4 mb-2">
                                   <label class="col-form-label" for="tax_docs">
                                        GPS Photo / जीपीएस फोटो अपलोड करा <span class="text-danger">*</span>
                                    </label>
                                    <input class="form-control" id="gps_docs" name="gps_docs"  accept=".pdf, image/*" type="file" required>
                                    <span class="text-danger is-invalid gps_docs_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. <br> वरील पुरविलेली सर्व माहिती ही अचूक असून, त्यात कुठल्याही प्रकारची तफावत आढळल्यास त्यास मी पूर्णतः जबाबदार
                                        असेन."
                                    </label>
                                </div>
                                <span class="text-danger is-invalid 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>
    $(document).ready(function () {
          function toggleDeleteButtons() {
        const totalRows = $("#roadTableBody tr").length;

        if (totalRows <= 1) {
            $(".removeRow").prop("disabled", true);
        } else {
            $(".removeRow").prop("disabled", false);
        }
    }
        $('#addmore').click(function () {
            const newRow = `
                <tr>
                    <td>
                        <select name="roadtype[]" class="form-select" >
                            <option value="">Select Road Type</option>
                            @foreach ($roadtype as $option)
                                <option value="{{ $option->id }}">{{ $option->road_type }}</option>
                            @endforeach
                        </select>
                    </td>
                    <td>
                        <input type="text" name="startpoint[]" class="form-control" placeholder="Enter Start Point" >
                    </td>
                    <td>
                        <input type="text" name="endpoint[]" class="form-control" placeholder="Enter End Point" >
                    </td>
                    <td>
                        <input type="number" name="road_length[]" class="form-control" placeholder="Enter Length" >
                    </td>
                    <td>
                        <select name="defect_factor[]" class="form-select" >
                            <option value="">Select Defect Liability</option>
                            @foreach ($multifactor as $option)
                                <option value="{{ $option->id }}">{{ $option->item }}</option>
                            @endforeach
                        </select>
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger removeRow">Delete</button>
                    </td>
                </tr>
            `;
            $('#roadTableBody').append(newRow);
        });

        $('#roadTable').on('click', '.removeRow', function () {
            $(this).closest('tr').remove();
            toggleDeleteButtons(); 
        });
         toggleDeleteButtons();
    });
</script>

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

     
        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;
        const printContainerClone = addContainer.cloneNode(true);
        printContainerClone.style.fontSize = '16px';
        printContainerClone.style.lineHeight = '1.4';
        printContainerClone.style.padding = '20px';
        printContainerClone.style.margin = '0 auto';
        printContainerClone.style.background = '#fff';
        printContainerClone.style.width = '210mm';
        printContainerClone.style.minHeight = '297mm';
        printContainerClone.style.boxSizing = 'border-box';
        Array.from(printContainerClone.querySelectorAll('*')).forEach(el => {
            el.style.fontSize = '16px';
            el.style.margin = '4px 0';
        });
        const printTitle = document.createElement('h2');
        printTitle.style.textAlign = 'center';
        printTitle.style.marginBottom = '18px';
        printTitle.style.fontSize = '18px';
        printTitle.textContent = 'Granting permission for laying underground telecommunication ducts';
        printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);
        Array.from(printContainerClone.querySelectorAll('button')).forEach(btn => btn.remove());
        Array.from(printContainerClone.querySelectorAll('.card')).forEach(card => {
            card.style.background = 'white';
            card.style.boxShadow = 'none';
            card.style.border = '1px solid #ccc';
            card.style.marginBottom = '12px';
            card.style.padding = '12px';
        });
       

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

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

    function updateSelectedValue(selectId) {
        var select = document.getElementById(selectId);
        var selectedText = select.options[select.selectedIndex] ? select.options[select.selectedIndex].text : '';
        var selectedDiv = document.getElementById(selectId + '_selected');
       
        selectedDiv.textContent = 'Selected: ' + selectedText;
        selectedDiv.classList.remove('d-none');
    }

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

    updateSelectedValue('ward');
</script> --}}


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

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

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

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

        let isValid = true;

        const messages = {
            f_name: 'Applicant First Name is Required',
            m_name: 'Applicant Middle Name is Required',
            l_name: 'Applicant Last Name is Required',
            ward_area: 'Ward Area is Required',
            mobile_num: 'Mobile No is Required',
            email: 'Email is Required',
            aadhar_num: 'Aadhar No is Required',
            property_num: 'Property No is Required',
            address: 'Address is Required',
            road_cutting_purpose: 'Road cutting purpose is Required',
            locationame: 'Location is Required',
            no_duct: 'No of Duct is required',
            no_chamber: 'No of chamber is required',
            digging_size: 'Digging size is required',
            government_docs: 'Government Documents is Required',
            outstanding_docs: 'Outstanding Documents is Required',
            tax_docs: 'Tax Documents is Required',
            gps_docs: 'GPS Documents is Required',
            is_correct_info: 'Please accept the declaration',
           // upload_prescribed_formats: 'Upload prescribed format is Required'
        };

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

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

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

            if(!hasError && id==='mobile_num' && !/^\d{10}$/.test(field.value.trim())){
                hasError=true; customMsg='Enter valid 10-digit mobile number';
            }

            if(!hasError && id==='aadhar_num' && !/^\d{12}$/.test(field.value.trim())){
                hasError=true; customMsg='Please enter 12-digit Aadhaar number';
            }

            if(!hasError && id==='email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(field.value.trim())){
                hasError=true; customMsg='Enter valid email';
            }

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

        if(!isValid) return; // stop if validation fails

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

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

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

        // Add PDF title
        const title=document.createElement('h2');
        title.style.textAlign='center';
        title.style.marginBottom='18px';
        title.textContent='Granting permission for laying underground telecommunication ducts';
        clone.insertBefore(title, clone.firstChild);

        // Remove buttons & style cards
        Array.from(clone.querySelectorAll('button')).forEach(btn=>btn.remove());
        Array.from(clone.querySelectorAll('.card')).forEach(card=>{
            card.style.background='white';
            card.style.boxShadow='none';
            card.style.border='1px solid #ccc';
            card.style.marginBottom='12px';
            card.style.padding='12px';
        });

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

        // Generate PDF using async/await
        try{
            const canvas = await html2canvas(clone, {scrollY:-window.scrollY, backgroundColor:'#fff', useCORS:true});
            const imgData = canvas.toDataURL('image/jpeg', 1.0);
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF('p','mm','a4');
            const margin = 10;
            const pdfWidth = pdf.internal.pageSize.getWidth() - margin*2;
            const pdfHeight = pdf.internal.pageSize.getHeight() - margin*2;
            pdf.addImage(imgData,'JPEG',margin,margin,pdfWidth,pdfHeight);
            pdf.save('Grantingpermission.pdf');
        }catch(err){
            console.error(err);
            alert('PDF generation failed');
        }

    });

});
</script> --}}

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

    // ✅ Function to remove unwanted random strings, IDs, or attributes
    function removeRandomIDs(root) {
        const badPattern = /(ydHCLjrLCY0jd16V4odIBVWM6mrPHAe2caWbYpyC|wHOIRWmRGdp3exAQIfNdlEsjSy5MeaOMD9y474g4|w[A-Za-z0-9]{20,})/;

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

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

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

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

    removeRandomIDs(document.body);

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

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

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

        let isValid = true;
        let firstErrorEl = null;

        const messages = {
            f_name: 'Applicant Name is Required',
            m_name: 'Applicant Type is Required',
            l_name: 'Applicant Full Address is Required',
            ward_area: 'Ward Type is Required',
            mobile_num: 'Mobile No is Required',
            email: 'Email is Required',
            aadhar_num: 'Aadhar No is Required',
            property_num: 'Name of Company is Required',
            address: 'Address is Required',
            road_cutting_purpose: 'Road cutting purpose is Required',
            locationame: 'Location is Required',
            no_duct: 'No of Duct is required',
            no_chamber: 'No of chamber is required',
            digging_size: 'Digging size is required',
            government_docs: 'Government Documents is Required',
            outstanding_docs: 'Upload Map is Required',
            tax_docs: 'Tax Documents is Required',
            gps_docs: 'GPS Documents is Required',
            is_correct_info: 'Please accept the declaration',
        };

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

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

            if (field.type === 'checkbox') hasError = !field.checked;
            else if (field.type === 'file') hasError = field.files.length === 0 && !field.getAttribute('data-db-value');
            else hasError = !field.value.trim();

            if (!hasError && id === 'mobile_num' && !/^\d{10}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid 10-digit mobile number';
            }

            if (!hasError && id === 'aadhar_num' && !/^\d{12}$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Please enter 12-digit Aadhaar number';
            }

            if (!hasError && id === 'email' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(field.value.trim())) {
                hasError = true;
                customMsg = 'Enter valid email';
            }

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

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

        // ✅ Show upload section after print
        const uploadSection = document.getElementById('upload_section');
        if (uploadSection) uploadSection.style.display = 'block';

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

        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return alert('Content container not found!');
        const printContainerClone = addContainer.cloneNode(true);

        const uploadSectionClone = printContainerClone.querySelector('#upload_section');
        if (uploadSectionClone) uploadSectionClone.remove();

        // ✅ Replace dropdowns with selected values (textbox look)
        const originalSelects = form.querySelectorAll('select');
        const cloneSelects = printContainerClone.querySelectorAll('select');
        cloneSelects.forEach((cloneSelect, i) => {
            const originalSelect = originalSelects[i];
            let selectedText = '';
            if (originalSelect) {
                const selectedOption = originalSelect.options[originalSelect.selectedIndex];
                selectedText = selectedOption ? selectedOption.text : '';
            }
            if (!selectedText && originalSelect?.value) {
                const opt = Array.from(originalSelect.options).find(opt => opt.value == originalSelect.value);
                selectedText = opt ? opt.text : originalSelect.value;
            }

            const displayDiv = document.createElement('div');
            displayDiv.textContent = selectedText || '';
            Object.assign(displayDiv.style, {
                fontSize: '16px',
                margin: '4px 0',
                padding: '6px 10px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: '#fff',
                minHeight: '30px',
                display: selectedText ? 'flex' : 'none',
                alignItems: 'center'
            });
            cloneSelect.parentNode.replaceChild(displayDiv, cloneSelect);
        });

        // ✅ Replace inputs and textareas with textbox look (hide empty)
        printContainerClone.querySelectorAll('input, textarea').forEach(el => {
            const fileFields = ['government_docs', 'outstanding_docs', 'tax_docs', 'gps_docs'];
            if (fileFields.includes(el.id)) {
                const fileDiv = document.createElement('div');
                Object.assign(fileDiv.style, {
                    fontSize: '16px',
                    marginTop: '4px',
                    padding: '6px 10px',
                    border: '1px solid #ccc',
                    borderRadius: '4px',
                    backgroundColor: '#fff',
                    minHeight: '60px',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'flex-start'
                });

                const dbValue = el.getAttribute('data-db-value');
                if (dbValue) {
                    const span = document.createElement('div');
                    span.textContent = dbValue;
                    fileDiv.appendChild(span);

                    const ext = dbValue.split('.').pop().toLowerCase();
                    if (['jpg', 'jpeg', 'png', 'gif'].includes(ext)) {
                        const img = document.createElement('img');
                        img.src = '/' + dbValue;
                        img.style.maxWidth = '100%';
                        img.style.marginTop = '6px';
                        fileDiv.appendChild(img);
                    }
                } else if (el.files && el.files.length > 0) {
                    const file = el.files[0];
                    const span = document.createElement('div');
                    span.textContent = file.name;
                    fileDiv.appendChild(span);
                } else {
                    fileDiv.style.display = 'none';
                }

                el.parentNode.replaceChild(fileDiv, el);
                return;
            }

            const valueText = el.value.trim();
            const div = document.createElement('div');
            if (valueText) {
                div.textContent = valueText;
                Object.assign(div.style, {
                    fontSize: '16px',
                    margin: '4px 0',
                    padding: '6px 10px',
                    border: '1px solid #ccc',
                    borderRadius: '4px',
                    backgroundColor: '#fff',
                    minHeight: '30px',
                    display: 'flex',
                    alignItems: 'center'
                });
            } else {
                div.style.display = 'none'; // ✅ hide empty boxes
            }
            el.parentNode.replaceChild(div, el);
        });

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

        const printTitle = document.createElement('h2');
        printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
        printTitle.textContent = 'Granting permission for laying underground telecommunication ducts';
        printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);

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

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

        printContainer.innerHTML = '';
        printContainer.appendChild(printContainerClone);
        removeRandomIDs(printContainerClone);

        // Remove leftover empty boxes completely (above Add Details, etc.)
        printContainerClone.querySelectorAll('div').forEach(div => {
            if (!div.textContent.trim() && div.childElementCount === 0) {
                div.remove();
            }
        });

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

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

        var formdata = new FormData(this);
        formdata.append('_token', '{{ csrf_token() }}');
        $.ajax({
            url: '{{ route('grant-telecome.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).ready(function () {

    $("#addForm").on("submit", function (e) {

        e.preventDefault();  // Stop the default submit

        let isValid = true;

        // -------------------------
        // VALIDATE FILE IF VISIBLE
        // -------------------------
        if ($("#upload_section").is(":visible")) {

            let fileVal = $("#upload_prescribed_formats").val();

            if (!fileVal) {
                isValid = false;
                $(".upload_prescribed_formats_err").text("This field is required.");
                $("#upload_prescribed_formats").addClass("is-invalid");
            } else {
                $(".upload_prescribed_formats_err").text("");
                $("#upload_prescribed_formats").removeClass("is-invalid");
            }
        }

        // If any validation failed → STOP HERE ❌
        if (!isValid) {
            return false;
        }

        // -------------------------
        // AJAX SUBMISSION (ONLY IF VALID)
        // -------------------------

        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        formdata.append('_token', '{{ csrf_token() }}');
        $.ajax({
            url: '{{ route('grant-telecome.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $('#preloader').css('opacity', '0.5');
                $('#preloader').css('visibility', 'visible');
            },
            success: function(data) {
                $("#addSubmit").prop('disabled', false);

                if (!data.error) {
                    swal("Successful!", data.success, "success")
                        .then(() => {
                            window.location.href = '{{ route('my-application') }}';
                        });
                } else {
                    swal("Error!", data.error, "error");
                }
            },
            statusCode: {
                422: function(response) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(response.responseJSON.errors);
                },
                500: function() {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            }
        });

    });

});
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const fileInputs = [
        { id: 'government_docs', errClass: '.government_docs_err' },
        { id: 'outstanding_docs', errClass: '.outstanding_docs_err' },
        { id: 'tax_docs', errClass: '.tax_docs_err' },
        { id: 'gps_docs', errClass: '.gps_docs_err' }
    ];

    fileInputs.forEach(inputInfo => {
        const inputEl = document.getElementById(inputInfo.id);
        const errEl = document.querySelector(inputInfo.errClass);

        if (inputEl) {
            inputEl.addEventListener('change', function () {
                errEl.textContent = ''; // Reset error message
                const file = this.files[0];
                if (!file) return;

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

                // ✅ Check file type
                if (!allowedTypes.includes(file.type)) {
                    errEl.textContent = 'Only PDF or Image files are allowed.';
                    this.value = '';
                    return;
                }

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

<script>
function onlyLetters(evt) {
    const charCode = evt.which ? evt.which : evt.keyCode;
    const char = String.fromCharCode(charCode);
    const regex = /^[a-zA-Z\s]+$/;

    // Allow Backspace, Tab, Delete, Arrow keys
    if ([8, 9, 37, 39, 46].includes(charCode)) return true;

    // Block anything other than letters or space
    if (!regex.test(char)) {
        evt.preventDefault();
        return false;
    }
    return true;
}
</script>


