<x-admin.layout>
    <x-slot name="title">New Taxation / नव्याने कर आकारणी</x-slot>
    <x-slot name="heading">New Taxation / नव्याने कर आकारणी</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 mb-2">
                                <label class="col-form-label" for="applicant_full_name">Applicant's Full Name /
                                    अर्जदाराचे संपूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_full_name" name="applicant_full_name"
                                    type="text" placeholder="Enter Applicant Full Name">
                                <span class="text-danger is-invalid applicant_full_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"></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="owner_name">Owner Name / मालकाचे नाव<span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="owner_name" name="owner_name" type="text"
                                    placeholder="Enter Owner Name">
                                <span class="text-danger is-invalid owner_name_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_mobile_no">Mobile Number / मोबाईल नंबर<span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_mobile_no" name="applicant_mobile_no"
                                    type="text" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10)"
                                    maxlength="10" minlength="10" placeholder="Enter Mobile Number">
                                <span class="text-danger is-invalid applicant_mobile_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">
                                <span class="text-danger is-invalid email_id_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="aadhar_no">Aadhaar Number / आधार क्रमांक <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="aadhar_no" name="aadhar_no" type="text"
                                    placeholder="Enter Aadhaar Card No" pattern="\d{12}"
                                    oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 12)" maxlength="12"
                                    minlength="12">
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="property_address">Property Address / मालमत्तेचा पत्ता
                                    <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="property_address" id="property_address" cols="30" rows="2"
                                    placeholder="Enter Property Address"></textarea>
                                <span class="text-danger is-invalid property_address_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="property_no">Property No / मालमत्ता क्र <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="property_no" name="property_no" type="text"
                                    placeholder="Enter Property Number">
                                <span class="text-danger is-invalid property_no_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="survey_number">Property Survey No / सर्व्हे
                                    क्र.</label>
                                <input class="form-control" id="survey_number" name="survey_number" type="text"
                                    placeholder="Enter Survey Number">
                                <span class="text-danger is-invalid survey_number_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 class="form-select" name="zone" id="zone">
                                        <option value="">Select Zone</option>
                                        @foreach ($zones as $zone)
                                        <option value="{{ $zone->name }}">{{ $zone->name }}</option>
                                        @endforeach
                                    </select>
                                    <span class="text-danger is-invalid zone_err"></span>
                                </div> --}}
                            {{-- <div class="col-md-4 mb-2">
                                <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">
                                    <option value="">Select Ward Area</option>
                                    @foreach ($wards as $ward)
                                    <option value="{{ $ward->name }}">{{ $ward->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_err"></span>
                            </div> --}}

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="property_usage">Property Usage / मालमत्ता वापर<span
                                        class="text-danger">*</span></label>
                                <select class="form-select" name="property_usage" id="property_usage">
                                    <option value="">Select Property Usage</option>
                                    @php
                                        $options = ['निवासी', 'बिगर निवासी', 'मिश्र'];
                                    @endphp

                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid property_usage_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="construction_type">Construction Type / बांधकाम
                                    प्रकार<span class="text-danger">*</span></label>
                                <select class="form-select" name="construction_type" id="construction_type">
                                    <option value="">Select Construction Type</option>
                                    @php
                                        $options = [
                                            'सिमेंट कॉँक्रिट संरचना',
                                            'सिमेंट / चुना / विटांच्या भिंती व स्ल्याब चे छत',
                                            'सिमेंट / चुना / विटांच्या भिंती व टीन / कवेलु चे छत',
                                            'मातीच्या भिंतीवर टीन / कवेलु चे छत',
                                            'खुला भूखंड',
                                            'इतर',
                                        ];
                                    @endphp
                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid construction_type_err"></span>
                            </div>
                            {{-- <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="is_construction_authorized">Is Construction Authorized ? / बांधकाम अधिकृत आहे का ?<span class="text-danger">*</span></label>
                                <select class="form-select" name="is_construction_authorized" id="is_construction_authorized">
                                    <option value="">Select Option</option>
                                    @php
                                        $options = ["Yes", "No"];
                                    @endphp
                                    @foreach ($options as $option)
                                    <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid is_construction_authorized_err"></span>
                            </div> --}}
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="is_there_water_connection">Is there a Water(Tap)
                                    Connection ? / पाणी (नळ) कनेक्शन आहे का ?<span class="text-danger">*</span></label>
                                <select class="form-select" name="is_there_water_connection"
                                    id="is_there_water_connection">
                                    <option value="">Select Option</option>
                                    @php
                                        $options = ['Yes', 'No'];
                                    @endphp
                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid is_there_water_connection_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="property_area">Property Area / मालमत्ता
                                    क्षेत्रफळ<span class="text-danger">*</span></label>
                                <input class="form-control" id="property_area" name="property_area" type="text"
                                    placeholder="Enter Property Area">
                                <span class="text-danger is-invalid property_area_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="certificate_of_no_duess">Upload Occupancy
                                    Certificate/ भोगवटा प्रमाणपत्र अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="certificate_of_no_duess"
                                    name="certificate_of_no_duess" type="file">
                                <span class="text-danger is-invalid certificate_of_no_duess_err"></span>
                            </div>
                            <div class="col-md-4 mb-2" 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>

                            <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 mb-4" 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() {
        let isValid = true;
        const addContainer = document.getElementById('addContainer');
        if (!addContainer) return;

        const messages = {
            applicant_full_name: 'Applicant name is required',
            applicant_full_address: 'Address is required',
            owner_name: 'Owner field is required',
            applicant_mobile_no: 'Mobile no. is required',
            email_id: 'Email is required',
            aadhar_no: 'This field is required',
            propno: 'This field is required',
            property_no: 'Property no. is required',
            property_owner_name: 'Owner name is required',
            property_address: 'Address is required',
            ward: 'This field is required',
            zone: 'This field is required',
            house_no: 'House no. is required',
            index_number: 'This field is required',
            property_usage: 'Property usage field is required',
            property_area: 'Property area is required',
            is_correct_info: 'Please accept the declaration',
            no_dues_documents: 'This field is required',
            date_of_commencement: 'This field is required',
            is_there_water_connection: 'This field is required',
            certificate_of_no_duess: 'This field is required',
            construction_type: 'This field is required',
        };

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

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

            // if (field) {
            //     if (!field.value.trim()) {
            //         isValid = false;
            //         field.classList.add('is-invalid');
            //         if (errorSpan) errorSpan.textContent = messages[fieldName];
            //     } else {
            //         field.classList.remove('is-invalid');
            //         if (errorSpan) errorSpan.textContent = '';
            //     }
            // }

            if (field) {
                const value = field.value.trim();

                if (!value) {
                    isValid = false;
                    field.classList.add('is-invalid');
                    if (errorSpan) errorSpan.textContent = messages[fieldName];
                    return;
                }

                if (fieldName === 'applicant_mobile_no') {
                    console.log
                    if (!/^\d{10}$/.test(value)) {
                        isValid = false;
                        field.classList.add('is-invalid');
                        if (errorSpan) errorSpan.textContent = 'Please enter valid mobile no.';
                        return;
                    }
                }

                if (fieldName === 'email_id') {
                    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailPattern.test(value)) {
                        isValid = false;
                        field.classList.add('is-invalid');
                        if (errorSpan) errorSpan.textContent = 'Please enter a valid email address.';
                        return;
                    }
                }

                if (fieldName === 'aadhar_no') {
                    if (!/^\d{12}$/.test(value)) {
                        isValid = false;
                        field.classList.add('is-invalid');
                        if (errorSpan) errorSpan.textContent = 'Please enter valid aadhaar no.';
                        return;
                    }
                }

                // Clear previous error if valid
                field.classList.remove('is-invalid');
                if (errorSpan) errorSpan.textContent = '';
            }
        });

        if (!isValid) return;

        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);
        const uploadSection = printContainerClone.querySelector('#upload_section');
        if (uploadSection) {
            uploadSection.remove();
        }
        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 = 'Newtaxation';
        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);

        addContainer.querySelectorAll('select').forEach(originalSelect => {
            const name = originalSelect.getAttribute('name');
            const clonedSelect = printContainerClone.querySelector(`[name="${name}"]`);
            if (clonedSelect) {
                const selectedOption = originalSelect.options[originalSelect.selectedIndex];
                const selectedText = selectedOption ? selectedOption.text : '';

                const replacement = document.createElement('span');
                replacement.textContent = selectedText || '—';
                replacement.style.display = 'inline-block';
                replacement.style.padding = '4px 8px';
                replacement.style.border = '1px solid #ccc';
                replacement.style.borderRadius = '4px';
                replacement.style.background = '#f9f9f9';
                replacement.style.minWidth = '100px';
                replacement.style.fontWeight = '500';

                clonedSelect.parentNode.replaceChild(replacement, clonedSelect);
            }
        });

        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('Newtaxation.pdf');
            document.getElementById('saveAndPrintBtn').style.display = 'none';
        });
    });
</script>


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

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('new-taxation.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $('#preloader').css('opacity', '0.5');
                $('#preloader').css('visibility', 'visible');
            },
            success: function(data) {
                $("#addSubmit").prop('disabled', false);
                if (!data.error)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        window.location.href = '{{ route('my-application') }}';
                    });
                else
                    swal("Error!", data.error, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            },
        });

    });
</script>

{{--
<script>
    document.addEventListener('DOMContentLoaded', function() {
        attachGlobalValidation('#addForm', '#saveAndPrintBtn', {
            containerId: 'addContainer',
            printTitle: 'Newtaxation',
        });
    });
</script>
<script>
    function displayFileName(input) {
        const fileNameDisplay = document.getElementById(input.id.replace('_pics', '_file_name'));
        if (input.files.length > 0) {
            // .name property only provides the file name, not the path
            fileNameDisplay.textContent = 'Selected: ' + input.files[0].name;
            fileNameDisplay.style.color = 'green';
        } else {
            fileNameDisplay.textContent = 'No file selected';
            fileNameDisplay.style.color = 'gray';
        }
    }
</script> --}}
