<x-admin.layout>
    <x-slot name="title">Road Cutting Permission / रस्ते खोदणे परवानगी </x-slot>
    <x-slot name="heading">Road Cutting Permission / रस्ते खोदणे परवानगी </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 Road Cutting Permission / रस्ते खोदणे परवानगी </h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">

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

                            <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="applicant_type">
                                        Applicant Type (Individual/Company) / अर्ज प्रकार (वैयक्तिक / कंपनी)
                                        <span class="text-danger">*</span>
                                    </label>
                                    <input class="form-control" id="applicant_type" name="applicant_type" type="text"
                                        placeholder="Enter Applicant Type" required
                                        oninput="this.value = this.value.replace(/[^A-Za-z\s]/g, '')">
                                    <span class="text-danger is-invalid applicant_type_err"></span>
                            </div>



                            {{-- <div class="col-md-4 mb-2">
                                <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" pattern="^[A-Za-zअ-हऀ-ॿ\s]+$" title="Only letters and spaces are allowed. No numbers or special characters." onkeypress="return isLetterOrSpace(event)" placeholder="Enter Applicant Name" required>
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div> --}}
                            <div class="col-md-4 mb-2">
                                <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 Name" required
                                    pattern="^[A-Za-zअ-हऀ-ॿ\s]+$"
                                    title="Only letters and spaces are allowed. No numbers or special characters."
                                    oninput="this.value = this.value.replace(/[^A-Za-zअ-हऀ-ॿ\s]/g, '')">
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_full_address">Applicant's Full Address / अर्जदाराचा संपूर्ण पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="applicant_full_address" id="applicant_full_address" cols="30" rows="2" placeholder="Enter Applicant Address" required></textarea>
                                <span class="text-danger is-invalid applicant_full_address_err"></span>
                            </div>

                            {{-- <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="zone">Zone <span class="text-danger">*</span></label>
                                    <select name="zone" id="zone" class="form-select">
                                        <option value="">Select Zone</option>
                                        @php
                                            $options = ["Prabhag1", "Prabhag2", "Prabhag3", "Prabhag4", "Prabhag5", "Prabhag6"];
                                        @endphp
                                        @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid zone_err"></span>
                                </div> --}}

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

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="company_name">Name of Company / कंपनीचे नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="company_name" name="company_name" type="text" placeholder="Enter Company Name" required>
                                <span class="text-danger is-invalid company_name_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="designation">Designation / पद</label>
                                <input class="form-control" id="designation" name="designation" type="text" placeholder="Enter Designation">
                                <span class="text-danger is-invalid designation_err"></span>
                            </div>

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

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="aadhar_no">Aadhar Number / आधार क्रमांक</label>
                                <input class="form-control" id="aadhar_no" name="aadhar_no" type="number" onkeypress="return isNumberKey(event)" oninput="limitAadharLength(this)" placeholder="Enter Aadhar Card No">
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <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 mb-2">
                                <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-4 mb-2">
                                <label class="col-form-label" for="no_of_location">Name of Locations / ठिकाणांची नावे <span class="text-danger">*</span></label>
                                <input class="form-control" id="no_of_location" name="no_of_location" type="text" placeholder="Enter Name of Locations" required>
                                <span class="text-danger is-invalid no_of_location_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="road_cutting_address">Address of the Road for cutting / रस्ता खोदण्याच्या ठिकाणाचा पत्ता <span class="text-danger">*</span></label>
                                <input class="form-control" id="road_cutting_address" name="road_cutting_address" type="text" placeholder="Enter road cutting address " required>
                                <span class="text-danger is-invalid road_cutting_address_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="location_size">Size in MM for each location / आकार (मी.मी) मध्ये<span class="text-danger">*</span> </label>
                                <input class="form-control" id="location_size" name="location_size" type="number" placeholder="Enter Size in MM for each location">
                                <span class="text-danger is-invalid location_size_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <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" placeholder="Enter Number Of Duct">
                                <span class="text-danger is-invalid no_duct_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <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" placeholder="Enter Number Of Chamber">
                                <span class="text-danger is-invalid no_chamber_err"></span>
                            </div>




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

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_gov_instructed_docs">Upload Map / नकाशा<span class="text-danger">*</span></label>
                                <input class="form-control" id="upload_gov_instructed_docs" accept=".pdf, image/*" name="upload_gov_instructed_docs" accept=".pdf, image/*" type="file" required>
                                <span class="text-danger is-invalid upload_gov_instructed_docs_err"></span>
                                <div class="selected-value d-none" id="upload_gov_instructed_docs"></div>
                            </div>


                             <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_related_docs">Related Documents / संबंधित दस्तऐवज <span class="text-danger">*</span></label>
                                <input class="form-control" id="upload_related_docs" accept=".pdf, image/*" name="upload_related_docs" accept=".pdf, image/*" type="file" required>
                                <span class="text-danger is-invalid upload_related_docs_err"></span>
                                <div class="selected-value d-none" id="upload_related_docs"></div>
                            </div>

                             <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_gps_docs">GPS Photo / जीपीएस फोटो <span class="text-danger">*</span></label>
                                <input class="form-control" id="upload_gps_docs" name="upload_gps_docs" accept=".pdf, image/*" type="file" required>
                                <span class="text-danger is-invalid upload_gps_docs_err"></span>
                                <div class="selected-value d-none" id="upload_gps_docs"></div>
                            </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>

                            <br>
                            <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 one--</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>


                            <label class="col-form-label" for="is_correct_info">Declaration / घोषणापत्र <span class="text-danger">*</span></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 src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>


{{-- <script>
    $(document).ready(function () {
        $('#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();
        });
    });
</script> --}}
<script>
    $(document).ready(function () {

        // 🔹 Function to enable/disable delete buttons
        function toggleDeleteButtons() {
            const totalRows = $("#roadTableBody tr").length;

            if (totalRows <= 1) {
                $(".removeRow").prop("disabled", true);
            } else {
                $(".removeRow").prop("disabled", false);
            }

            
        }

        // 🔹 Add More Button
        $('#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);
            toggleDeleteButtons(); // row add होने पर check
        });

        // 🔹 Delete Row Button
        $('#roadTable').on('click', '.removeRow', function () {
            $(this).closest('tr').remove();
            toggleDeleteButtons(); // row delete होने पर check
        });

        // 🔹 On page load
        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 = 'Road cutting permission';
        printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);
        Array.from(printContainerClone.querySelectorAll('button')).forEach(btn => btn.remove());
        Array.from(printContainerClone.querySelectorAll('.card')).forEach(card => {
            card.style.background = 'white';
            card.style.boxShadow = 'none';
            card.style.border = '1px solid #ccc';
            card.style.marginBottom = '12px';
            card.style.padding = '12px';
        });
       
        Array.from(printContainerClone.querySelectorAll('input[type="checkbox"]')).forEach(checkbox => {
            const info = document.createElement('div');
            info.textContent = checkbox.checked ? 'Checked' : 'Not checked';
            checkbox.parentNode.appendChild(info);
            checkbox.style.display = 'none';
        });
        let printContainer = document.getElementById('printContainer');
        if (!printContainer) {
            printContainer = document.createElement('div');
            printContainer.id = 'printContainer';
            printContainer.style.position = 'fixed';
            printContainer.style.left = '-9999px';
            document.body.appendChild(printContainer);
        }
        printContainer.innerHTML = '';
        printContainer.appendChild(printContainerClone);
        html2canvas(printContainerClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1,
            useCORS: true,
            allowTaint: true,
            logging: false
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            const {
                jsPDF
            } = window.jspdf;
            const pdf = new jsPDF('p', 'mm', 'a4');
            const pageWidth = pdf.internal.pageSize.getWidth();
            const pageHeight = pdf.internal.pageSize.getHeight();
            const margin = 10;
            const pdfWidth = pageWidth - margin * 2;
            const pdfHeight = pageHeight - margin * 2;
            pdf.addImage(imgData, 'JPEG', margin, margin, pdfWidth, pdfHeight);
            const pdfBlob = pdf.output('blob');
            if (pdfBlob.size > 2 * 1024 * 1024) {
                alert('Warning: PDF size is greater than 2 MB. Please reduce content or try again.');
            }
            pdf.save('RoadCuttingPermission.pdf');
            document.getElementById('saveAndPrintBtn').style.display = 'none';
        });
    });
</script> --}}




{{-- <script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    // ✅ Validation messages
    const messages = {
        applicant_type: 'Applicant Type is Required',
        applicant_name: 'Applicant Name is Required',
        applicant_full_address: 'Applicant address is Required',
        ward_area: 'Ward Area is Required',
        mobile_no: 'Mobile No is Required',
        aadhar_no: 'Aadhar No is Required',
        email_id: 'Email is Required',
        road_cutting_purpose: 'Road cutting purpose is Required',
        no_of_location: 'No of location is Required',
        road_cutting_address: 'Road cutting address is Required',
        no_duct: 'No duct is Required',
        upload_gov_instructed_docs: 'Upload Documents are Required',
        upload_related_docs: 'Documents are Required',
        upload_gps_docs: 'GPS documents are Required',
        is_correct_info: 'Please accept the declaration',
    };

    let isValid = true;

    // ✅ Clear old error messages
    document.querySelectorAll('.is-invalid').forEach(el => el.textContent = '');

    // ✅ Check each field
    for (const [id, message] of Object.entries(messages)) {
        const field = document.getElementById(id);
        if (!field) continue;

        let hasError = false;
        let customMessage = message;

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

        // ✅ Strict Mobile Validation
        if (!hasError && id === 'mobile_no') {
            const mobile = field.value.trim();
            const mobileRegex = /^[0-9]{10}$/;
            if (!mobileRegex.test(mobile)) {
                hasError = true;
                customMessage = 'Please enter 10 digit mobile number';
            }
        }

        // ✅ Strict Aadhaar Validation
        if (!hasError && id === 'aadhar_no') {
            const aadhar = field.value.trim();
            const aadharRegex = /^[0-9]{12}$/;
            if (!aadharRegex.test(aadhar)) {
                hasError = true;
                customMessage = 'Please enter 12 digit Aadhaar number';
            }
        }

        // ✅ Strict Email Validation
        if (!hasError && id === 'email_id') {
            const email = field.value.trim();
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                hasError = true;
                customMessage = 'Please enter valid email id';
            }
        }

        // ✅ Display error
        if (hasError) {
            isValid = false;
            const errSpan = document.querySelector(`.${id}_err`);
            if (errSpan) errSpan.textContent = customMessage;
        }
    }

    // ❌ Stop if invalid — no PDF, no save
    if (!isValid) return;

    // ✅ Proceed with PDF generation only if all valid
    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 = 'Road Cutting Permission';
    printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);

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

    Array.from(printContainerClone.querySelectorAll('input[type="checkbox"]')).forEach(checkbox => {
        const info = document.createElement('div');
        info.textContent = checkbox.checked ? 'Checked' : 'Not checked';
        checkbox.parentNode.appendChild(info);
        checkbox.style.display = 'none';
    });

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

    html2canvas(printContainerClone, {
        scrollY: -window.scrollY,
        backgroundColor: '#fff',
        scale: 1,
        useCORS: true,
        allowTaint: true,
        logging: false
    }).then(canvas => {
        const imgData = canvas.toDataURL('image/jpeg', 0.6);
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF('p', 'mm', 'a4');
        const pageWidth = pdf.internal.pageSize.getWidth();
        const pageHeight = pdf.internal.pageSize.getHeight();
        const margin = 10;
        const pdfWidth = pageWidth - margin * 2;
        const pdfHeight = pageHeight - margin * 2;

        pdf.addImage(imgData, 'JPEG', margin, margin, pdfWidth, pdfHeight);
        pdf.save('RoadCuttingPermission.pdf');

        // ✅ After PDF generation
        document.getElementById('saveAndPrintBtn').style.display = 'none';
        document.getElementById('upload_section').style.display = 'block';
        document.getElementById('card-footer').style.display = 'block';
    });
});
</script> --}}


<script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function () {
    const form = document.getElementById('addForm');
    if (!form) return alert('Form not found!');

    // ✅ Validation messages
    const messages = {
        applicant_type: 'Applicant Type is Required',
        applicant_name: 'Applicant Name is Required',
        applicant_full_address: 'Applicant address is Required',
        ward_area: 'Ward Area is Required',
        mobile_no: 'Mobile No is Required',
        aadhar_no: 'Aadhar No is Required',
        email_id: 'Email is Required',
        road_cutting_purpose: 'Road cutting purpose is Required',
        no_of_location: 'Name of location is Required',
        no_chamber: 'Number of Chamber is Required',
        road_cutting_address: 'Road cutting address is Required',
        location_size: 'Location Size is Required',
        no_duct: 'Number of  duct is Required',
        upload_gov_instructed_docs: 'Upload Documents are Required',
        upload_related_docs: 'Documents are Required',
        upload_gps_docs: 'GPS documents are Required',
        is_correct_info: 'Please accept the declaration',
        company_name:'Company Name is Required',
    };

    let isValid = true;
    let firstErrorEl = null;

    // ✅ Clear old error messages
    document.querySelectorAll('.is-invalid').forEach(el => el.textContent = '');

    // ✅ Validate each field
    for (const [id, message] of Object.entries(messages)) {
        const field = document.getElementById(id);
        if (!field) continue;

        let hasError = false;
        let customMessage = message;

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

       
        if (!hasError && id === 'mobile_no') {
            const mobileRegex = /^[0-9]{10}$/;
            if (!mobileRegex.test(field.value.trim())) {
                hasError = true;
                customMessage = 'Please enter 10 digit mobile number';
            }
        }

        
        if (!hasError && id === 'aadhar_no') {
            const aadharRegex = /^[0-9]{12}$/;
            if (!aadharRegex.test(field.value.trim())) {
                hasError = true;
                customMessage = 'Please enter 12 digit Aadhaar number';
            }
        }

       
        if (!hasError && id === 'email_id') {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(field.value.trim())) {
                hasError = true;
                customMessage = 'Please enter valid email id';
            }
        }

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

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

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

    const printContainerClone = addContainer.cloneNode(true);

   
    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: 'flex',
            alignItems: 'center'
        });

        cloneSelect.parentNode.replaceChild(displayDiv, cloneSelect);
    });

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

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

    // ✅ Add title
    const printTitle = document.createElement('h2');
    printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
    printTitle.textContent = 'Road Cutting Permission';
    printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);

    // ✅ Clean unnecessary buttons and decorations
    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);

    
    setTimeout(() => {
        html2canvas(printContainerClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1
        }).then(canvas => {
            const imgData = canvas.toDataURL('image/jpeg', 0.6);
            if (!window.jspdf || !window.jspdf.jsPDF) return alert('jsPDF not loaded!');

            const pdf = new window.jspdf.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('RoadCuttingPermission.pdf');

            document.getElementById('saveAndPrintBtn').style.display = 'none';
            document.getElementById('upload_section').style.display = 'block';
            document.getElementById('card-footer').style.display = 'block';
        }).catch(err => {
            console.error('PDF generation failed:', err);
            alert('PDF generation failed. Check console.');
        });
    }, 100);
});
</script>
























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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('construction-road-cutting.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.error2)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        window.location.href = '{{ route('my-application') }}';
                    });
                else
                    swal("Error!", data.error2, "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>
<!--applicant name-->
<script>
    function isLetterOrSpace(e) {
        const char = String.fromCharCode(e.which || e.keyCode);
        const regex = /^[A-Za-zअ-हऀ-ॿ\s]+$/;
        return regex.test(char);
    }
</script>

<!--adhar card no validation-->
<script>
    function isNumberKey(evt) {
        var charCode = evt.which ? evt.which : evt.keyCode;

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


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


<script>
document.addEventListener('DOMContentLoaded', function () {
    const fileInputs = [
        { id: 'upload_gov_instructed_docs', errClass: '.upload_gov_instructed_docs_err' },
        { id: 'upload_related_docs', errClass: '.upload_related_docs_err' },
        { id: 'upload_gps_docs', errClass: '.upload_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
                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

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

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




