<x-admin.layout>
    <x-slot name="title">No Dues Certificate (Property) / थकबाकी नसल्याचा दाखला देणे</x-slot>
    <x-slot name="heading">No Dues Certificate (Property) / थकबाकी नसल्याचा दाखला देणे</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">Details</h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">
                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name_eng">Applicant Full Name / अर्जदाराचे
                                    पूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_name_eng" name="applicant_name_eng"
                                    type="text" value="{{ $user->name }}" required readonly>
                                <span class="text-danger is-invalid applicant_name_eng_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name_mar">Applicant Full Address /
                                    अर्जदाराचा पूर्ण पत्ता<span class="text-danger">*</span></label>
                                <textarea class="form-control" id="applicant_name_mar" name="applicant_name_mar" type="text"
                                    placeholder="Enter Applicant Name" required readonly>{{ $user->address }}</textarea>
                                <span class="text-danger is-invalid applicant_name_mar_err"></span>
                            </div>

                            <div class="col-md-4">
                                <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"
                                    value="{{ $user->mobile }}" oninput="this.value = this.value.replace(/\D/g, '')"
                                    maxlength="10" minlength="10" type="text" placeholder="Enter Mobile Number"
                                    required 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_id">Email ID / ई-मेल आयडी</label>
                                <input class="form-control" id="email_id" name="email_id" type="email"
                                    value="{{ $user->email }}" placeholder="Enter Email" required readonly>
                                <span class="text-danger is-invalid email_id_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="aadhar_no">Aadhar Number / आधार क्रमांक</label>
                                <input class="form-control" id="aadhar_no"
                                    oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12"
                                    type="text" name="aadhar_no" placeholder="Enter Aadhar Card No">
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <div class="card">
                @csrf
                <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="propno">Property No<span
                                class="text-danger">*</span></label>
                        <input class="form-control" id="propno" name="propno" type="text"
                            placeholder="Enter Property No">
                        <span class="text-danger is-invalid propno_err"></span>
                    </div>
                </div>
                <button type="Search" style="margin-left: 12px;" class="btn btn-primary w-25"
                    id="searchdetails">Search</button>
                <br>
            </div>

            <div class="card">
                <br>
                <div class="card-header">
                    <h4 class="card-title">Property Details</h4>
                </div>
                <div class="card-body">
                    <div class="mb-3 row">
                        <div class="col-md-4">
                            <label class="col-form-label" for="owner_name">owner name/मालकाचे नाव<span
                                    class="text-danger">*</span></label>
                            <input class="form-control" name="owner_name" id="owner_name" cols="30"
                                rows="2" placeholder="Enter Property Address" required readonly>
                            <span class="text-danger is-invalid owner_name_err"></span>
                        </div>
                        <div class="col-md-4">
                            <label class="col-form-label" for="owner_full_add">owner full address/मालकाचा पूर्ण
                                पत्ता<span class="text-danger">*</span></label>
                            <input class="form-control" name="owner_full_add" id="owner_full_add" cols="30"
                                rows="2" placeholder="Enter Property Address" required readonly>
                            <span class="text-danger is-invalid owner_full_add_err"></span>
                        </div>
                        <div class="col-md-4">
                            <label class="col-form-label" for="property_address">Property Number/मालमत्ता क्रमांक<span
                                    class="text-danger">*</span></label>
                            <input class="form-control" name="property_address" id="property_address" cols="30"
                                rows="2" placeholder="Enter Property Address" required readonly>
                            <span class="text-danger is-invalid property_address_err"></span>
                        </div>
                        <div class="col-md-4">
                            <label class="col-form-label" for="property_no">Property Area<span
                                    class="text-danger">*</span></label>
                            <input class="form-control" name="property_no" id="property_no" required readonly>
                            <span class="text-danger is-invalid property_no_err"></span>
                        </div>
                        <div class="col-md-4">
                            <label class="col-form-label" for="index_number">Flat_Number<span
                                    class="text-danger">*</span></label>
                            <input class="form-control" name="index_number" id="index_number" required readonly>
                            <span class="text-danger is-invalid index_number"></span>
                        </div>
                        <div class="col-md-4">
                            <label class="col-form-label" for="ward">Ward / प्रभाग<span
                                    class="text-danger">*</span></label>
                            <input class="form-control" name="ward" id="ward" required 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" required 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="uploaded_application">
                                Total Outstanding Payable / एकूण देय थकबाकी? <span class="text-danger">*</span>
                            </label>
                            <input class="form-control" name="uploaded_application" id="uploaded_application"
                                required readonly>
                            <span class="text-danger is-invalid uploaded_applications_err"></span>
                            <div class="selected-value d-none" id="uploaded_application"></div>
                        </div>
                        <div class="col-md-4 mt-4">
                            <button type="button" id="payaccentech" class="btn btn-success" target="_blank"
                                onclick="payNow()">Pay</button>
                        </div>

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

            <div class="card">
                <div class="card-body">
                    <div class="mb-3 row">

                        <div class="col-md-4">
                            <label class="col-form-label" for="annual_period">वार्षिक कालावधी <span
                                    class="text-danger">*</span></label>
                            <select class="form-control" id="annual_period" name="annual_period" required>
                                <option value="">Enter Annual Period</option>
                                <option value="2003-2004">2003-2004</option>
                                <option value="2004-2005">2004-2005</option>
                                <option value="2005-2006">2005-2006</option>
                                <option value="2006-2007">2006-2007</option>
                                <option value="2007-2008">2007-2008</option>
                                <option value="2008-2009">2008-2009</option>
                                <option value="2009-2010">2009-2010</option>
                                <option value="2010-2011">2010-2011</option>
                                <option value="2011-2012">2011-2012</option>
                                <option value="2012-2013">2012-2013</option>
                                <option value="2013-2014">2013-2014</option>
                                <option value="2014-2015">2014-2015</option>
                                <option value="2015-2016">2015-2016</option>
                                <option value="2016-2017">2016-2017</option>
                                <option value="2017-2018">2017-2018</option>
                                <option value="2018-2019">2018-2019</option>
                                <option value="2019-2020">2019-2020</option>
                                <option value="2020-2021">2020-2021</option>
                                <option value="2021-2022">2021-2022</option>
                                <option value="2022-2023">2022-2023</option>
                                <option value="2023-2024">2023-2024</option>
                                <option value="2024-2025">2024-2025</option>
                                <option value="2025-2026">2025-2026</option>

                            </select>
                            <span class="text-danger is-invalid annual_period_err"></span>
                        </div>


                        {{-- <div class="col-md-4">
                            <label for="col-form-label" class="receipt_docs">Uplooad document Reciept/दस्तऐवजाची पावती अपलोड करा</label><span class="text-danger">*</span></label>
                            <input type="file" class="form-control" name="receipt_docs" placeholder="Enter file" required>
                            <span class="text-danger is-invalid receipt_docs_err"></span>
                        </div> --}}
                        <div class="col-md-6" id="upload_section" style="display:none;">
                            <label class="col-form-label" for="prescribed_docs">Upload Application In Prescribed
                                Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                            <input class="form-control" id="prescribed_docs" name="prescribed_docs" type="file">
                            <span class="text-danger is-invalid prescribed_docs_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" 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> वरील पुरविलेली सर्व माहिती ही अचूक असून, त्यात कुठल्याही
                                    प्रकारची तफावत आढळल्यास त्यास मी पूर्णतः जबाबदार असेन."<br>
                                    Download this form and upload with your Signature
                                </label>
                            </div>
                            <span class="text-danger is-invalid is_correct_info_err"></span>
                        </div>

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

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

        $.ajax({
            url: '{{ route('fetch.propertynodue.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']) {
                    $('#owner_name').val(decryptedData['property_Details'].Owner_Name);
                    $('#owner_full_add').val(decryptedData['property_Details'].Property_Address);
                    $('#new_owner_name').val(decryptedData['property_Details']
                        .Full_Address_Of_The_Property);
                    $('#address').val(decryptedData['property_Details'].Water_Connection_Size);
                    $('#ward').val(decryptedData['property_Details'].Ward);
                    $('#owner_add').val(decryptedData['property_Details'].Property_Owner_Name);
                    $('#property_address').val(decryptedData['property_Details'].Property_No);
                    $('#property_no').val(decryptedData['property_Details'].Property_Area);
                    $('#index_number').val(decryptedData['property_Details'].Flat_Number);
                    $('#zone').val(decryptedData['property_Details'].Zone);
                    $('#uploaded_application').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($('#uploaded_application').val());
                    const savePrintBtn = document.getElementById('saveAndPrintBtn');
                    const paybtn = document.getElementById('payaccentech');

                    if (uploadedValue === 0) {
                        savePrintBtn.style.display = 'block';
                        paybtn.style.display = 'none';
                    } else {
                        savePrintBtn.style.display = 'none';
                        paybtn.style.display = 'block';
                    }

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

            error: function(xhr) {
                console.error(xhr.responseText);
            }
        });
    });
</script>

<script>

    function payNow() {
        var propNo = document.getElementById("propno").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.');
        }
    }


    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 = 'No Dues Certificate (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');
        });

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

        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('no-dues-certificate-form.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('no-dues.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>
