<x-admin.layout>
    <x-slot name="title">मलनिःसारण (Sewerage line) वाहिनी जोडणी ना हरकत दाखला</x-slot>
    <x-slot name="heading">No Objection certificate Sewerage Line System / मलनिःसारण व्यवस्थेचा नाहरकत दाखला</x-slot>

    <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">

                        {{--Applicant Details--}}
                        <h5 class="text-primary">Applicant Details / अर्जदाराची माहिती</h5>
                        <div class="mb-3 row">

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


                            <div class="col-md-4">
                               <label class="col-form-label" for="mobileno">Mobile Number / मोबाईल नंबर<span class="text-danger">*</span></label>
                               <input class="form-control" id="mobileno" name="mobileno" type="text" placeholder="Enter Mobile No. / मोबाईल नंबर भरा" maxlength="10" pattern="\d{10}"
                               title="Please enter exactly 10 digits" required inputmode="numeric" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10);" required>
                               <span class="text-danger is-invalid mobileno_err"></span>
                            </div>


                            <div class="col-md-4">
                                {{-- <label class="col-form-label" for="propertyno">S.NoH.No Property / सर्व्हे क्र/ हिस्सा क्र. /सि.टी. क्र.<span class="text-danger">*</span></label> --}}
                                <label class="col-form-label" for="propertyno">Survey No./Hissa No./C T No / सर्व्हे क्र/ हिस्सा क्र./सि.टी.क्र.<span class="text-danger">*</span></label>

                                <input class="form-control" id="propertyno" name="propertyno" type="text" placeholder="Enter Survey No./Hissa No./C T No / सर्व्हे क्र/ हिस्सा क्र./सि.टी.क्र." required>
                                <span class="text-danger is-invalid propertyno_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicantaddress">Applicant Full Address / अर्जदाराचा पूर्ण पत्ता<span class="text-danger">*</span></label>
                                {{-- <input class="form-control" id="applicantaddress" name="applicantaddress" type="text" placeholder="Enter Address / पत्ता भरा"> --}}
                                <textarea class="form-control" id="applicantaddress" name="applicantaddress" rows="3" placeholder="Enter Address / पत्ता भरा" required></textarea>
                                <span class="text-danger is-invalid applicantaddress_err"></span>
                            </div>


                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="tax_no">Property Tax Number/मालमत्ता कर क्रमांक<span class="text-danger">*</span></label>
                                <input class="form-control" name="tax_no" id="tax_no" placeholder="Enter Aadhaar Number">
                                <span class="text-danger is-invalid tax_no_err"></span>
                            </div> --}}


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


                        <h5 class="text-primary">Documents / कागदपत्रे</h5>
                        <div class="mb-3 row">
                            {{-- <div class="col-md-3">
                                <label class="col-form-label" for="application_doc">Application form downloaded in the prescribed format/ विहित नमुन्यात डाउनलोड केलेला अर्ज<span class="text-danger">*</span></label>
                                <input class="form-control" id="application_doc" name="application_doc" type="file" >
                                <span class="text-danger is-invalid application_doc_err"></span>
                            </div> --}}

                            <div class="col-md-3">
                                <label class="col-form-label" for="bill_doc">Uploaded Oc & Cc/अपलोड केलेले ओसी आणि सीसी<span class="text-danger"></span></label>
                                <input class="form-control" id="bill_doc" name="bill_doc" type="file">
                                <span class="text-danger is-invalid bill_doc_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label class="col-form-label" for="site_photo">Site photo / साइट फोटो<span class="text-danger"></span></label>
                                <input class="form-control" id="site_photo" name="site_photo" type="file">
                                <span class="text-danger is-invalid site_photo_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label class="col-form-label" for="blue_print">Blue print / ब्लू प्रिंट<span class="text-danger"></span></label>
                                <input class="form-control" id="blue_print" name="blue_print" type="file">
                                <span class="text-danger is-invalid blue_print_err"></span>
                            </div>

                            <div class="col-md-3">
                                <label class="col-form-label" for="other_document">Other relevant Documents / इतर संबंधित कागदपत्रे<span class="text-danger"></span></label>
                                <input class="form-control" id="other_document" name="other_document" type="file">
                                <span class="text-danger is-invalid other_document_err"></span>
                            </div>


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

                                

                        </div>

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

                    </div>

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

                </form>
            </div>
        </div>
    </div>

</x-admin.layout>

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



{{-- <script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function() {
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return;

    let isValid = true;

    const messages = {
        applicantname: 'Applicant Name is required',
        mobileno: 'Please enter 10 digit mobile no',
        propertyno: 'Survey No is required',
        applicantaddress: 'Applicant Address is required',
        ward_area: 'Enter Ward',
        is_correct_info: 'Please accept the declaration'
    };

    Object.keys(messages).forEach(fieldName => {
        const field = addContainer.querySelector(`[name="${fieldName}"]`);
        const errorSpan = addContainer.querySelector(`.${fieldName}_err`);

        if (!field) return;

        // Checkbox
        if (fieldName === 'is_correct_info') {
            if (!field.checked) {
                isValid = false;
                if (errorSpan) errorSpan.textContent = messages[fieldName];
            } else {
                if (errorSpan) errorSpan.textContent = '';
            }
            return;
        }

        // Mobile number validation
        if (fieldName === 'mobileno') {
            if (!/^\d{10}$/.test(field.value.trim())) {
                isValid = false;
                field.classList.add('is-invalid');
                if (errorSpan) errorSpan.textContent = messages[fieldName];
                field.scrollIntoView({ behavior: 'smooth', block: 'center' });
            } else {
                field.classList.remove('is-invalid');
                if (errorSpan) errorSpan.textContent = '';
            }
            return;
        }

        // Other fields
        if (!field.value.trim()) {
            isValid = false;
            field.classList.add('is-invalid');
            if (errorSpan) errorSpan.textContent = messages[fieldName];
            field.scrollIntoView({ behavior: 'smooth', block: 'center' });
        } else {
            field.classList.remove('is-invalid');
            if (errorSpan) errorSpan.textContent = '';
        }
    });

    if (!isValid) return;

    // Show upload section and footer (but upload field should not go to PDF)
    document.getElementById('upload_section').style.display = 'block';
    document.getElementById('card-footer').style.display = 'block';

    // Clone container for PDF
    const printContainerClone = addContainer.cloneNode(true);

    // Remove upload section from PDF
    const uploadSection = printContainerClone.querySelector('#upload_section');
    if (uploadSection) uploadSection.remove();

    // Styling for PDF
    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 = 'Sewerage line';
    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);
        pdf.save('Sewerage Noc.pdf');
        document.getElementById('saveAndPrintBtn').style.display = 'none';
    });
});
</script> --}}


<script>
document.getElementById('saveAndPrintBtn').addEventListener('click', function() {
    const addContainer = document.getElementById('addContainer');
    if (!addContainer) return;

    let isValid = true;

    const messages = {
        applicantname: 'Applicant Name is required',
        mobileno: 'Please enter 10 digit mobile no',
        propertyno: 'Survey No is required',
        applicantaddress: 'Applicant Address is required',
        ward_area: 'Enter Ward',
        is_correct_info: 'Please accept the declaration'
    };

    // ✅ Validation
    Object.keys(messages).forEach(fieldName => {
        const field = addContainer.querySelector(`[name="${fieldName}"]`);
        const errorSpan = addContainer.querySelector(`.${fieldName}_err`);

        if (!field) return;

        // Checkbox
        if (fieldName === 'is_correct_info') {
            if (!field.checked) {
                isValid = false;
                if (errorSpan) errorSpan.textContent = messages[fieldName];
            } else {
                if (errorSpan) errorSpan.textContent = '';
            }
            return;
        }

        // Mobile number validation
        if (fieldName === 'mobileno') {
            if (!/^\d{10}$/.test(field.value.trim())) {
                isValid = false;
                field.classList.add('is-invalid');
                if (errorSpan) errorSpan.textContent = messages[fieldName];
                field.scrollIntoView({ behavior: 'smooth', block: 'center' });
            } else {
                field.classList.remove('is-invalid');
                if (errorSpan) errorSpan.textContent = '';
            }
            return;
        }

        // Other fields
        if (!field.value.trim()) {
            isValid = false;
            field.classList.add('is-invalid');
            if (errorSpan) errorSpan.textContent = messages[fieldName];
            field.scrollIntoView({ behavior: 'smooth', block: 'center' });
        } else {
            field.classList.remove('is-invalid');
            if (errorSpan) errorSpan.textContent = '';
        }
    });

    if (!isValid) return;

    // ✅ Show upload section and footer (but hide in PDF)
    document.getElementById('upload_section').style.display = 'block';
    document.getElementById('card-footer').style.display = 'block';

    // ✅ Clone container for PDF
    const printContainerClone = addContainer.cloneNode(true);

    // ✅ Replace all <select> and file inputs with visible textbox-style divs (WARD FIX ✅)
    const originalSelectsAndFiles = addContainer.querySelectorAll('select, input[type="file"]');
    const clonedSelectsAndFiles = printContainerClone.querySelectorAll('select, input[type="file"]');

    clonedSelectsAndFiles.forEach((el, i) => {
        let displayText = '';

        const originalEl = originalSelectsAndFiles[i];
        if (!originalEl) return;

        if (originalEl.tagName.toLowerCase() === 'select') {
            const selectedOption = originalEl.options[originalEl.selectedIndex];
            displayText = selectedOption && selectedOption.text.trim() !== '-- Select Ward --'
                ? selectedOption.text
                : (originalEl.value.trim() || '');
        } 
        else if (originalEl.type === 'file') {
            displayText = Array.from(originalEl.files).map(f => f.name).join(', ') || '';
        }

        const div = document.createElement('div');
        div.textContent = displayText || '__________';

        Object.assign(div.style, {
            border: '1px solid #000',
            borderRadius: '5px',
            backgroundColor: '#f9f9f9',
            padding: '6px 10px',
            minHeight: '24px',
            width: '90%',
            fontSize: '15px',
            display: 'inline-block',
            marginTop: '4px'
        });

        el.parentNode.replaceChild(div, el);
    });

    // ❌ Remove upload section from PDF
    const uploadSection = printContainerClone.querySelector('#upload_section');
    if (uploadSection) uploadSection.remove();

    // ✅ Styling for PDF
    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';
    });

    // ✅ Add PDF title
    const printTitle = document.createElement('h2');
    printTitle.style.textAlign = 'center';
    printTitle.style.marginBottom = '18px';
    printTitle.style.fontSize = '18px';
    printTitle.textContent = 'Sewerage Line';
    printContainerClone.insertBefore(printTitle, printContainerClone.firstChild);

    // Remove buttons
    Array.from(printContainerClone.querySelectorAll('button')).forEach(btn => btn.remove());

    // Simplify card
    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';
    });

    // Hidden print area
    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);

    // ✅ Generate PDF
    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('Sewerage_NOC.pdf');
        document.getElementById('saveAndPrintBtn').style.display = 'none';
    }).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);


        // Clear previous errors
    $(".uploaded_applications_err").text('');

    // Client-side check for file
    var fileInput = $("#uploaded_applications")[0].files;
    if ($('#upload_section').is(':visible') && fileInput.length === 0) {
        $(".uploaded_applications_err").text("Please upload the file");
        $("#addSubmit").prop('disabled', false);
        return false;
    }

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


                     // Display server-side error inside the same span
                if(responseObject.responseJSON.errors.uploaded_applications){
                    $(".uploaded_applications_err").text(responseObject.responseJSON.errors.uploaded_applications[0]);
                }
                },
                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.getElementById("applicantname").addEventListener("input", function (e) {
    // सिर्फ letters (English + Marathi/Devanagari) और spaces allow करो
    this.value = this.value.replace(/[^A-Za-z\u0900-\u097F\s]/g, '');
});
</script>









