<x-admin.layout>
    <x-slot name="title">Tax Assessment On Demolishing And Reconstruction Of The property/ मालमत्ता पाडणे व पुनः बांधणी
        कर आकारणी</x-slot>
    <x-slot name="heading">Tax Assessment On Demolishing And Reconstruction Of The property/मालमत्ता पाडणे व पुनः बांधणी
        कर आकारणी</x-slot>

    <!-- Add Form -->
    <div class="row" id="addContainer">
        <div class="col-sm-12">
            <div class="card p-3">
                <form class="theme-form" name="addForm" id="addForm" enctype="multipart/form-data">
                    @csrf
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title">Applicant Details</h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-3 row">
                                <div class="col-md-4">
                                    <label class="col-form-label" for="f_name">Applicant Name <span
                                            class="text-danger">*</span></label>
                                    <input class="form-control" id="f_name" name="f_name" type="text"
                                        value="{{ $user->name }}" placeholder="Enter First Name" readonly>
                                    <span class="text-danger is-invalid applicant_name_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="address">Applicant Full Address<span
                                            class="text-danger">*</span></label>
                                    <textarea class="form-control" name="address" id="address" cols="30" rows="2" placeholder="Enter Address"
                                        readonly> {{ $user->address }}</textarea>
                                    <span class="text-danger is-invalid address_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="mobile_num">Mobile Number<span
                                            class="text-danger">*</span></label>
                                    <input class="form-control" id="mobile_num" name="mobile_num" type="text"
                                        value="{{ $user->mobile }}" oninput="this.value = this.value.replace(/\D/g, '')"
                                        maxlength="10" minlength="10" placeholder="Enter Mobile Number" readonly>
                                    <span class="text-danger is-invalid applicant_mobile_no_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="email">Email<span
                                            class="text-danger">*</span></label>
                                    <input class="form-control" id="email" name="email" type="email"
                                        value="{{ $user->email }}" placeholder="Enter Email" readonly>
                                    <span class="text-danger is-invalid email_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="aadhar_num">Aadhar Card No</label>
                                    <input class="form-control" id="aadhar_num" name="aadhar_num" type="text"
                                        oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12"
                                        minlength="12" value="{{ $user->aadhar_no ?? '' }}"
                                        placeholder="Enter Aadhar  Card Number" readonly>
                                    <span class="text-danger is-invalid applicant_mobile_no_err"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="col-md-4">
                                <input class="form-control" id="marchantid" name="marchantid" type="hidden"
                                    value="MBMCCORE">
                                <span class="text-danger is-invalid marchantid_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="property_number">Property No<span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="property_number" name="property_number" type="text"
                                    placeholder="Enter Property Number">
                                <span class="text-danger is-invalid property_number_err"></span>
                            </div>
                        </div>
                        <button type="Search" style="margin-left: 14px;" class="btn btn-primary w-25"
                            id="searchdetails">Search</button>
                        <br>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <div class="mb-3 row">
                                <div class="col-md-4">
                                    <label class="col-form-label" for="property_owner_name">Property Owner Name /
                                        मालमत्ता मालकाचे नाव <span class="text-danger">*</span></label>
                                    <input class="form-control" id="property_owner_name" name="property_owner_name"
                                        type="text" placeholder="Enter Owner Name" readonly>
                                    <span class="text-danger is-invalid property_owner_name_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="property_address">Property Address / मालमत्ता
                                        पत्ता <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="property_address" name="property_address" rows="2"
                                        placeholder="Enter Property Address" readonly></textarea>
                                    <span class="text-danger is-invalid property_address_err"></span>
                                </div>

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

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

                                <input type="hidden" id="warddata" name="ward_area">

                                <div class="col-md-4">
                                    <label class="col-form-label" for="survey_number">Property Survey Number /
                                        मालमत्ता सर्व्हे नंबर</label>
                                    <input class="form-control" id="survey_number" name="survey_number"
                                        type="text" placeholder="Enter Survey Number" readonly>
                                    <span class="text-danger is-invalid survey_number_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="m_name">Flat Number <span
                                            class="text-danger">*</span></label>
                                    <input class="form-control" id="m_name" name="m_name" type="text"
                                        placeholder="Enter Middle Name" readonly>
                                    <span class="text-danger is-invalid m_name_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="property_area">Property Area (sq. mtr) /
                                        मालमत्ता क्षेत्रफळ (स्के. मी)</label>
                                    <input class="form-control" id="property_area" name="property_area"
                                        type="number" step="0.01" placeholder="Enter Area in sq. mtr" readonly>
                                    <span class="text-danger is-invalid property_area_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="property_usage">Property Usage / मालमत्ता
                                        वापर <span class="text-danger">*</span></label>
                                    <input class="form-control" id="property_usage" name="property_usage"
                                        type="text" placeholder="Enter Usage Type" readonly>
                                    <span class="text-danger is-invalid property_usage_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="l_name">Total Outstanding Payable / एकूण देय
                                        थकबाकी?</label>
                                    <input class="form-control" id="l_name" name="l_name" type="text"
                                        placeholder="Outstanding Amount" readonly>
                                    <span class="text-danger is-invalid l_name_err"></span>
                                </div>

                                <div class="col-md-4 mt-4">
                                    <button type="button" id="payaccentech" class="btn btn-success d-none"
                                        target="_blank" onclick="payNow()">Pay</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- <div class="col-md-4">
                                                <label class="col-form-label" for="marathi_f_name">प्रथम नाव (मराठी) <span class="text-danger">*</span></label>
                                                <input class="form-control" id="marathi_f_name" name="marathi_f_name" type="text" placeholder="नाव प्रविष्ट करा प्रथम" required>
                                                <span class="text-danger is-invalid applicant_name_err"></span>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="col-form-label" for="marathi_m_name">मधले नाव (मराठी)<span class="text-danger">*</span></label>
                                                <input class="form-control" id="marathi_m_name" name="marathi_m_name" type="text" placeholder="प्रविष्ट करा मधले नाव" required>
                                                <span class="text-danger is-invalid applicant_name_err"></span>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="col-form-label" for="marathi_l_name">आडनाव (मराठी) <span class="text-danger">*</span></label>
                                                <input class="form-control" id="marathi_l_name" name="marathi_l_name" type="text" placeholder="आडनाव प्रविष्ट करा" required>
                                                <span class="text-danger is-invalid applicant_name_err"></span>
                                            </div> --}}
                    {{-- <div class="col-md-5">
                                    <label class="col-form-label" for="marathi_address"> पत्ता (मराठी) <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="marathi_address" id="marathi_address" cols="30" rows="2" placeholder="पत्ता" required></textarea>
                                    <span class="text-danger is-invalid applicant_full_address_err"></span>
                                </div>
                                <div class="col-md-5">
                                    <label class="col-form-label" for="purpose">Purpose <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="purpose" id="purpose" cols="30" rows="2" placeholder="Enter purpose" required></textarea>
                                    <span class="text-danger is-invalid applicant_full_address_err"></span>
                                </div> --}}
                    {{-- <div class="col-md-4">
                            <label class="col-form-label" for="construction_type">Construction Type / बांधकाम प्रकार</label>
                            <input class="form-control" id="construction_type" name="construction_type" type="text" placeholder="Enter Construction Type">
                        </div> --}}
                    {{-- <div class="col-md-4">
                            <label class="col-form-label" for="is_authorized_construction">Is Construction Authorized? / बांधकाम अधिकृत आहे का?</label>
                            <select class="form-select" id="is_authorized_construction" name="is_authorized_construction">
                                <option value="">Select</option>
                                <option value="yes">Yes / होय</option>
                                <option value="no">No / नाही</option>
                            </select>
                        </div> --}}
                    {{-- <div class="col-md-4">
                            <label class="col-form-label" for="has_water_connection">Is there a Water (Tap) Connection? / पाणी (नळ) कनेक्शन आहे का?</label>
                        <select class="form-select" id="has_water_connection" name="has_water_connection">
                            <option value="">Select</option>
                            <option value="yes">Yes / होय</option>
                            <option value="no">No / नाही</option>
                        </select>
                    </div>--}}

                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title">Add Details</h4>
                        </div>
                        <div class="card-body">
                            <div class="mb-3 row">
                                <div class="col-md-4">
                                    <label class="col-form-label" for="no_dues_certificate">Upload Certificate Of No
                                        Dues / थकबाकी नसल्याचा दाखला अपलोड करा <span class="text-danger">*</span>
                                    </label>
                                    <input type="file" class="form-control" name="no_dues_certificate"
                                        id="no_dues_certificate" accept=".pdf,.doc,.docx,.jpg,.png">
                                    <span class="text-danger is-invalid no_dues_certificate_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="marathi_purpose"> Purpose / उद्देश (मराठी)
                                        <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="marathi_purpose" id="marathi_purpose" rows="2"
                                        placeholder="Enter Purpose"></textarea>
                                    <span class="text-danger is-invalid marathi_purpose_err"></span>
                                </div>
                                <div class="col-md-4" id="upload_section" style="display:none;">
                                    <label class="col-form-label" for="application_file">Upload Application In
                                        Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span
                                            class="text-danger">*</span></label>
                                    <input type="file" class="form-control" name="application_file"
                                        id="application_file" accept=".pdf,.doc,.docx,.jpg,.png">
                                    <span class="text-danger is-invalid application_file_err"></span>
                                </div>
                            </div>
                        </div>
                    </div>

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

                    <div class="form-group d-flex justify-content-center my-3" style="text-align: center;">
                        <button type="button" id="saveAndPrintBtn" class="btn btn-success my-3">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>
    $('#searchdetails').on('click', function(e) {
        e.preventDefault();

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

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

                const decryptedData = JSON.parse(response.jsonData.encr_request);


                if (decryptedData && decryptedData['property_Details']) {
                    $('#property_owner_name').val(decryptedData['property_Details'].Owner_Name);
                    $('#property_address').val(decryptedData['property_Details'].Property_Address);
                    $('#new_owner_name').val(decryptedData['property_Details']
                        .Full_Address_Of_The_Property);
                    $('#ward').val(decryptedData['property_Details'].Ward);
                    $('#survey_number').val(decryptedData['property_Details'].Property_Survey_No);
                    $('#property_area').val(decryptedData['property_Details'].Property_Area);
                    $('#m_name').val(decryptedData['property_Details'].Flat_Number);
                    $('#zone').val(decryptedData['property_Details'].Zone);
                    $('#property_usage').val(decryptedData['property_Details'].Property_Usage);
                    $('#l_name').val(decryptedData['property_Details'].OutstandingAmt);

                    const fullZone = decryptedData['property_Details'].Zone;
                    const zoneCode = fullZone.charAt(0);
                    const wardNumber = decryptedData['property_Details'].Ward.toString();
                    const sectorCode = wardNumber.length === 1 ? '0' + wardNumber : wardNumber;

                    const finalCode = zoneCode + sectorCode;

                    $('#warddata').val(finalCode);

                    const uploadedValue = parseInt($('#l_name').val());
                    const savePrintBtn = document.getElementById('saveAndPrintBtn');
                    const paybtn = document.getElementById('payaccentech');

                    if (uploadedValue === 0) {
                        savePrintBtn.style.display = 'block';
                        paybtn.style.display = 'none';
                    } else {
                        $('#payaccentech').removeClass('d-none');
                        savePrintBtn.style.display = 'none';
                        paybtn.style.display = 'block';
                    }

                } else {
                    console.error("connectionDetails is missing or undefined");
                }
            },

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

    function payNow() {
        var propNo = document.getElementById("property_no").value;
        if (propNo) {
            var url = 'https://pg.mbmc.gov.in/PropSearch.aspx?PTN=' + propNo;
            window.location.href = url;
        } else {
            alert('Please enter a property number.');
        }
    }
</script>

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

        const messages = {
            f_name: 'This field is required',
            m_name: 'This field is required',
            l_name: 'This field is required',
            address: 'This field is required',
            mobile_num: 'This field is required',
            email: 'This field is required',
            property_number: 'This field is required',
            property_owner_name: 'This field is required',
            property_address: 'This field is required',
            ward: 'This field is required',
            zone: 'This field is required',
            property_area: 'This field is required',
            property_usage: 'This field is required',
            marathi_purpose: 'This field is required',
            no_dues_certificate: 'This field is required',
            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 (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 (!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 = 'Demolishing Property';
        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="file"]')).forEach(input => {
            const parent = input.parentNode;
            const fileName = input.files && input.files.length > 0 ? input.files[0].name :
                'No file chosen';
            const fileInfo = document.createElement('div');
            fileInfo.textContent = 'Selected file: ' + fileName;
            parent.appendChild(fileInfo);
            input.style.display = 'none';
        });

        Array.from(printContainerClone.querySelectorAll('select')).forEach(select => {
            const selected = select.options[select.selectedIndex];
            const info = document.createElement('div');
            info.textContent = 'Selected: ' + (selected ? selected.text : '');
            select.parentNode.appendChild(info);
            select.style.display = 'none';
        });

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

        const note = document.createElement('div');
        note.textContent = 'Download this form and upload with your Signature.';
        note.style.fontSize = '14px';
        note.style.fontWeight = 'bold';
        note.style.textAlign = 'center';
        note.style.marginTop = '30px';
        note.style.borderTop = '1px solid #ccc';
        note.style.paddingTop = '10px';
        note.style.color = '#333';
        printContainerClone.appendChild(note);

        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('demolishing-property.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('demolishingproperty.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>
