<x-admin.layout>
    <x-slot name="title"> Generation of Water Tax Bill / पाणी देयक तयार करणे</x-slot>
    <x-slot name="heading">Generation of Water Tax Bill / पाणी देयक तयार करणे</x-slot>
    <style>
.invalid-message {
    color: red;
    font-size: 13px;
    margin-top: 4px;
    display: block;
}
</style>
    <!-- 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">

                    <div class="card-body">
                        <div class="mb-3 row">
                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name">Applicant Full Name / अर्जदाराचे पूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_name" name="applicant_name" type="text" value="{{ $user->name }}" placeholder="Enter Applicant Name" required>
                                <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" id="address" name="address" type="text" placeholder="Enter Name Of New Owner" required>{{ $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_no">Applicant Mobile No / मोबाईल नंबर<span class="text-danger">*</span></label>
                                <input class="form-control" id="mobile_no" name="mobile_no" value="{{ $user->mobile }}" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10" type="text"
                                    placeholder="Enter Mobile Number" required>
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="email_id"> Applicant EmailID / ईमेल आयडी<span class="text-danger"></span></label>
                                <input class="form-control" id="email_id" name="email_id" type="email" placeholder="Enter Email" value="{{ $user->email }}" required>
                                <span class="text-danger is-invalid email_id_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="aadhar_no">Applicant Adhaar No / आधार क्रमांक <span class="text-danger">*</span></label>
                                <input class="form-control" id="aadhar_no" name="aadhar_no" value='{{ $user->aadhar_no }}' oninput="this.value = this.value.replace(/\D/g, '')" maxlength="12" minlength="12" type="text"
                                    placeholder="Enter Aadhar Card No" required>
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">

                            @csrf
                            <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="connection_no">Connection No<span class="text-danger">*</span></label>
                                <input class="form-control" id="connection_no" name="connection_no" type="text" placeholder="Enter Connection No" >
                                <span class="text-danger is-invalid connection_no_err"></span>
                            </div>

                            <button type="Search" class="btn btn-primary mt-2" id="searchdetails">Search</button>
                        </div>
                    </div>



                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title">Water Details</h4>
                        </div>
                        <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 Property 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="Connection_Type">Connection Type<span class="text-danger">*</span></label>
                                    <input class="form-control" name="Connection_Type" id="Connection_Type" type="text" placeholder="Enter Connection Type"  readonly>
                                    <span class="text-danger is-invalid Connection_Type_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Full_Address_Of_The_Property"> Full Address of Property/मालमत्तेचा पूर्ण पत्ता<span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="Full_Address_Of_The_Property" id="Full_Address_Of_The_Property" cols="30" rows="2" placeholder="Enter  Address"  readonly></textarea>
                                    <span class="text-danger is-invalid Full_Address_Of_The_Property_err"></span>
                                </div>

                                <div class="col-md-4">
                                    <label class="col-form-label" for="Water_Connection_Size">Water Connection Size<span class="text-danger">*</span></label>
                                    <input class="form-control" id="Water_Connection_Size" name="Water_Connection_Size" type="text" placeholder="Enter Water Connection Size"  readonly>
                                    <span class="text-danger is-invalid Water_Connection_Size_err"></span>
                                </div>
                                <div class="col-md-4">
                                    <label class="col-form-label" for="Water_Connection_Usage">Water Connection Usage <span class="text-danger">*</span></label>
                                    <input class="form-control" id="Water_Connection_Usage" name="Water_Connection_Usage" type="text" placeholder="Enter Water Connection Usage"  readonly>
                                    <span class="text-danger is-invalid Water_Connection_Usage_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>
                                <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="OutstandingAmt"> Total Outstanding Payable/ एकूण थकबाकी बिल भरले?<span class="text-danger">*</span></label>
                                    <input class="form-control" id="OutstandingAmt" name="OutstandingAmt" type="text"  readonly>
                                    <span class="text-danger is-invalid OutstandingAmt_err"></span>
                                </div>
                                <div class="col-md-4 mt-4">
                                    <button type="button" id="payaccentech" class="btn btn-success" target="_blank"
                                        onclick="window.location.href='https://watertax.nagarkaryavali.com/FrmWTConnSearch.aspx?@=AD65C7423AEA4530E3CB0528C8EFFFE4185BBCFBFA074578B362FC23AB6A7765'">Pay</button>
                                </div>

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

                    {{-- <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="card-header">
                                <h4 class="card-title">Connection Details
                                </h4>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="no_of_existing_con">Number Of Existing Water Connection / विद्यमान पाणी कनेक्शनची संख्या<span class="text-danger">*</span></label>
                                <input class="form-control" name="no_of_existing_con" id="no_of_existing_con" cols="30" rows="2" placeholder="Enter Number Of Existing Water Connection" >
                                <span class="text-danger is-invalid no_of_existing_con_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-control" for="house_no">House Number / घर नं <span class="text-danger">*</span></label>
                                <input class="form-control" id="house_no" name="house_no" type="text" placeholder="Enter House Number" >
                                <span class="text-danger is-invalid house_no_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-control" for="landmark">Landmark / जवळची खूण<span class="text-danger">*</span></label>
                                <input class="form-control" id="landmark" name="landmark" type="text" placeholder="Enter Landmark" >
                                <span class="text-danger is-invalid landmark_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label for="water_sub_usage" class="col-form-control">Water Sub Usage/पाणी उपवापर<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="water_sub_usage" id="water_sub_usage" placeholder="Enter Water Sub Usage" >
                                <span class="text-danger is-invalid water_sub_usage_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label for="billing_cycle" class="col-form-control">Billing Cycle/बिलिंग सायकल<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="billing_cycle" name="billing_cycle" placeholder="Enter Billing Cycle" >
                                <span class="text-danger is-invalid connection_billing_cycle"></span>
                            </div>



                             <div class="col-md-4" id="upload_section" style="display:none;">
                                
                                    <label class="col-form-label" for="application_documents">Upload Application In Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                                    <input class="form-control" id="application_documents" name="application_documents" type="file" >
                                    <span class="text-danger is-invalid application_documents_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" required 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. / वरील पुरविलेली सर्व माहिती ही अचूक असून, त्यात कुठल्याही प्रकारची तफावत आढळल्यास त्यास मी पूर्णतः जबाबदार
                                        असेन."
                                    </label>
                                </div>
                                <span class="text-danger is-invalid is_correct_info_err d-block mt-1"></span>
                            </div>

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

</x-admin.layout>

<script src="https://cdnjs.cloudflare.com/ajax/libs/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.addEventListener('DOMContentLoaded', function () {
    const saveBtn = document.getElementById('saveAndPrintBtn');
    const form = document.getElementById('addForm');
    const fileInput = document.getElementById('application_documents');

    if (!saveBtn || !form) return;

    // ✅ Validation messages
    const messages = {
        connection_no: 'Connection No is Required',
        property_owner_name: 'Property Owner is Required',
        Connection_Type: 'Connection is Required',
        Full_Address_Of_The_Property: 'Full Address is Required',
        Water_Connection_Size: 'Water Connection is Required',
        Water_Connection_Usage: 'Water Connection Usage is Required',
        zone: 'Zone is Required',
        Ward: 'Ward is Required',
        OutstandingAmt: 'Outstanding is Required',
        no_of_existing_con: 'No of existing is Required',
        house_no: 'House No is Required',
        landmark: 'Landmark is Required',
        water_sub_usage: 'Water Connection Usage is Required',
        billing_cycle: 'Billing Cycle is Required',
        is_correct_info: 'Please accept the Declaration'
    };

    saveBtn.addEventListener('click', function () {
        if (fileInput) fileInput.removeAttribute('required');

        let isValid = true;
        form.querySelectorAll('.invalid-message').forEach(el => el.remove());

        // 🔹 Validate required fields
        for (const [fieldName, message] of Object.entries(messages)) {
            const field = form.querySelector(`[name="${fieldName}"]`);
            if (!field) continue;

            let empty = false;
            if (field.type === 'checkbox') empty = !field.checked;
            else if (field.tagName === 'SELECT') empty = !field.value;
            else empty = !field.value.trim();

            if (empty) {
                isValid = false;

                // Special case for Declaration checkbox
                if (field.type === 'checkbox' && field.id === 'is_correct_info') {
                    const parent = field.closest('.col-md-12');
                    const existingError = parent.querySelector('.is_correct_info_err');

                    if (existingError) {
                        existingError.textContent = message;
                        existingError.style.display = 'block';
                    } else {
                        let msgEl = document.createElement('div');
                        msgEl.className = 'text-danger is_correct_info_err mt-1 invalid-message';
                        msgEl.style.fontSize = '13px';
                        msgEl.textContent = message;
                        parent.appendChild(msgEl);
                    }

                    // Remove message when user checks the box
                    field.addEventListener('change', () => {
                        const err = parent.querySelector('.is_correct_info_err');
                        if (err) err.style.display = 'none';
                    });
                } else {
                    // Default behavior for all other fields
                    let msgEl = document.createElement('div');
                    msgEl.className = 'invalid-message text-danger mt-1';
                    msgEl.style.fontSize = '13px';
                    msgEl.textContent = message;

                    const parent = field.closest('.form-group') || field.parentNode;
                    parent.appendChild(msgEl);

                    // Add red border
                    field.style.borderColor = 'red';

                    // Remove error on input/change
                    const clearError = () => {
                        field.style.borderColor = '';
                        if (msgEl) msgEl.remove();
                    };
                    field.addEventListener('input', clearError);
                    field.addEventListener('change', clearError);
                }
            } else {
                field.style.borderColor = '';
            }
        }

        // ❌ Stop if invalid
        if (!isValid) {
            if (fileInput) fileInput.setAttribute('required', 'required');
            const firstError = form.querySelector('.invalid-message');
            if (firstError) firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
            return;
        }

        // ✅ Show sections for PDF if hidden
        const uploadSection = document.getElementById('upload_section');
        if (uploadSection) uploadSection.style.display = 'block';

        const cardFooter = document.getElementById('card-footer');
        if (cardFooter) cardFooter.style.display = 'block';

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

        const printClone = addContainer.cloneNode(true);

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

        // Hide upload section in PDF
        printClone.querySelectorAll('#upload_section').forEach(el => el.style.display = 'none');

        // Remove buttons
        printClone.querySelectorAll('button').forEach(btn => btn.remove());

        // Style cards
        printClone.querySelectorAll('.card').forEach(card => {
            Object.assign(card.style, {
                background: 'white',
                boxShadow: 'none',
                border: '1px solid #ccc',
                marginBottom: '12px',
                padding: '12px'
            });
        });

        // Show selected hidden values
        printClone.querySelectorAll('.selected-value').forEach(div => div.classList.remove('d-none'));

        // ❌ Remove all validation messages and declaration error from PDF
        printClone.querySelectorAll('.invalid-message, .is_correct_info_err').forEach(el => el.remove());

        // Add heading
        const printTitle = document.createElement('h2');
        printTitle.style.cssText = 'text-align:center; margin-bottom:18px; font-size:18px;';
        printTitle.textContent = 'Generation of Water Tax Bill';
        printClone.insertBefore(printTitle, printClone.firstChild);

        // Hidden print container
        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(printClone);

        // 🧾 Generate PDF
        setTimeout(() => {
            html2canvas(printClone, {
                scrollY: -window.scrollY,
                backgroundColor: '#fff',
                scale: 1
            }).then(canvas => {
                const imgData = canvas.toDataURL('image/jpeg', 0.6);

                if (!window.jspdf || !window.jspdf.jsPDF) {
                    return alert('jsPDF library not loaded!');
                }

                const pdf = new window.jspdf.jsPDF('p', 'mm', 'a4');
                const margin = 10;

                pdf.addImage(
                    imgData, 'JPEG',
                    margin, margin,
                    pdf.internal.pageSize.getWidth() - margin * 2,
                    pdf.internal.pageSize.getHeight() - margin * 2
                );

                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('Generation of Water Tax BillCertificate.pdf');

                // Hide save button after save
                saveBtn.style.display = 'none';
            }).catch(err => {
                console.error('PDF generation failed:', err);
                alert('PDF generation failed. Check console for details.');
            });
        }, 100);
    });
});
</script>








{{-- Add --}}
<script>
    $('#searchdetails').on('click', function(e) {
        e.preventDefault();

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

        $.ajax({
            url: '{{ route('fetch.water.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); // Replace with actual decryption function

                console.log("Decrypted Data:", decryptedData['connectionDetails'].Water_Connection_Number);

                if (decryptedData && decryptedData['connectionDetails']) {
                    $('#Connection_Type').val(decryptedData['connectionDetails'].Connection_Type);
                    $('#House_Number').val(decryptedData['connectionDetails'].House_Number);
                    $('#property_owner_name').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    $('#Full_Address_Of_The_Property').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    $('#Water_Connection_Size').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    $('#Water_Connection_Usage').val(decryptedData['connectionDetails'].Water_Connection_Usage);
                    $('#zone').val(decryptedData['connectionDetails'].Zone);
                    $('#Ward').val(decryptedData['connectionDetails'].Ward);
                    $('#OutstandingAmt').val(decryptedData['connectionDetails'].OutstandingAmt);
                    // $('#city_serve_no').val(decryptedData['connectionDetails'].Water_Connection_Number);
                    // $('#property_no').val(decryptedData['connectionDetails'].Property_Owner_Name);
                    // $('#owner_full_add').val(decryptedData['connectionDetails'].Full_Address_Of_The_Property);
                    // $('#address').val(decryptedData['connectionDetails'].Water_Connection_Size);
                    // $('#water_connection').val(decryptedData['connectionDetails'].Water_Connection_Usage);
                    // $('#ward').val(decryptedData['connectionDetails'].Ward);
                } else {
                    console.error("connectionDetails is missing or undefined");
                }
            },

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


    $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('water-Tax-bill.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 () {
    const existingConInput = document.getElementById('no_of_existing_con');

    if (existingConInput) {
        existingConInput.addEventListener('input', function (e) {
            // Remove any non-digit characters
            this.value = this.value.replace(/[^0-9]/g, '');
        });
    }
});
</script>
