<x-admin.layout>
    <x-slot name="title">Owners Name change/ Partner name of nursing homes under the Maharashtra Nursing Homes
        Registration Act, 1949
        /महाराष्ट्र शुश्रूषा-गृह नोंदणी अधिनियम 1949 अंतर्गत शुश्रूषा-गृह परवानाचे परवानाधारक/भगिधारीचे नाव
        बदलणे</x-slot>
    <x-slot name="heading">Owners Name change/ Partner name of nursing homes under the Maharashtra Nursing Homes
        Registration Act, 1949
        /महाराष्ट्र शुश्रूषा-गृह नोंदणी अधिनियम 1949 अंतर्गत शुश्रूषा-गृह परवानाचे परवानाधारक/भगिधारीचे नाव
        बदलणे</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="col-md-4">
                                <label class="col-form-label" for="zone">Zone Id / झोन<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="mb-3 row">

                            <div class="col-md-4">
                                <label class="col-form-label" for="f_name">First Name <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="f_name" name="f_name" type="text"
                                    placeholder="Enter First Name">
                                <span class="text-danger is-invalid f_name_err"></span>
                            </div>

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

                            <div class="col-md-4">
                                <label class="col-form-label" for="l_name">Last Name <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="l_name" name="l_name" type="text"
                                    placeholder="Enter Last Name">
                                <span class="text-danger is-invalid l_name_err"></span>
                            </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="नाव प्रविष्ट करा प्रथम">
                                <span class="text-danger is-invalid marathi_f_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="प्रविष्ट करा मधले नाव">
                                <span class="text-danger is-invalid marathi_m_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="आडनाव प्रविष्ट करा">
                                <span class="text-danger is-invalid marathi_l_name_err"></span>
                            </div>


                            <div class="col-md-4">
                                <label class="col-form-label" for="mobile_num">Mobile Number</label>
                                <input class="form-control" id="mobile_num" name="mobile_num" type="text"
                                    oninput="this.value = this.value.replace(/\D/g, '')" maxlength="10" minlength="10"
                                    placeholder="Enter Mobile Number">
                                <span class="text-danger is-invalid mobile_num_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"
                                    placeholder="Enter Aadhar  Card Number">
                                <span class="text-danger is-invalid aadhar_num_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"
                                    placeholder="Enter Email">
                                <span class="text-danger is-invalid email_err"></span>
                            </div>
                            <div class="col-md-5">
                                <label class="col-form-label" for="address"> Address <span
                                        class="text-danger">*</span></label>
                                <textarea class="form-control" name="address" id="address" cols="30" rows="2"
                                    placeholder="Enter Address"></textarea>
                                <span class="text-danger is-invalid address_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="पत्ता"></textarea>
                                <span class="text-danger is-invalid marathi_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"></textarea>
                                <span class="text-danger is-invalid purpose_err"></span>
                            </div>

                            <div class="col-md-5">
                                <label class="col-form-label" for="marathi_purpose">उद्देश (मराठी) <span
                                        class="text-danger">*</span></label>
                                <textarea class="form-control" name="marathi_purpose" id="marathi_purpose" cols="30" rows="2"
                                    placeholder="उद्देश"></textarea>
                                <span class="text-danger is-invalid marathi_purpose_err"></span>
                            </div>

                            <div class="col-md-4 mb-2" id="upload_section" style="display:none;">
                                <label class="col-form-label" for="prescribed_formats">Upload Application In
                                    Prescribed
                                    Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="prescribed_formats" name="prescribed_formats"
                                    type="file">
                                <span class="text-danger is-invalid prescribed_formats_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-3" 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>
    const validationRules = {
        'f_name': {
            required: true,
            message: "Please enter first name.",
            pattern: /^[A-Za-zअ-हऀ-ॿ\s]+$/,
            patternMessage: "Only letters and spaces are allowed."
        },
        'm_name': {
            required: true,
            message: "Please enter middle name.",
            pattern: /^[A-Za-zअ-हऀ-ॿ\s]+$/,
            patternMessage: "Only letters and spaces are allowed."
        },
        'l_name': {
            required: true,
            message: "Please enter last name.",
            pattern: /^[A-Za-zअ-हऀ-ॿ\s]+$/,
            patternMessage: "Only letters and spaces are allowed."
        },
        'marathi_f_name': {
            required: true,
            message: "कृपया प्रथम नाव प्रविष्ट करा."
        },
        'marathi_m_name': {
            required: true,
            message: "कृपया मधले नाव प्रविष्ट करा."
        },
        'marathi_l_name': {
            required: true,
            message: "कृपया आडनाव प्रविष्ट करा."
        },
        'mobile_num': {
            required: true,
            message: "Please enter mobile number.",
            pattern: /^\d{10}$/,
            patternMessage: "Mobile number must be 10 digits."
        },
        'aadhar_num': {
            required: true,
            message: "Please enter Aadhar number.",
            pattern: /^\d{12}$/,
            patternMessage: "Aadhar number must be 12 digits."
        },
        'email': {
            required: true,
            message: "Please enter email.",
            pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
            patternMessage: "Please enter a valid email."
        },
        'address': {
            required: true,
            message: "Please enter address."
        },
        'marathi_address': {
            required: true,
            message: "कृपया पत्ता प्रविष्ट करा."
        },
        'purpose': {
            required: true,
            message: "Please enter purpose."
        },
        'marathi_purpose': {
            required: true,
            message: "कृपया उद्देश प्रविष्ट करा."
        },
        'is_correct_info': {
            required: true,
            message: "Please accept the declaration."
        }
    };

    for (const key in validationRules) {
        if (key === 'is_correct_info') continue;
        if (validationRules[key].required) {
            validationRules[key].message = "This field is required";
        }
    }

    document.getElementById('saveAndPrintBtn').addEventListener('click', function() {
        Array.from(document.querySelectorAll('.is-invalid')).forEach(el => el.textContent = '');
        let valid = true;

        for (const [id, rule] of Object.entries(validationRules)) {
            const field = document.getElementById(id);

            if (!field) continue;

            if (field.type === 'checkbox' && !field.checked) {
                valid = false;
                document.querySelector(`.${id}_err`).textContent = rule.message;
            } else if (field.type === 'radio') {
                const radios = document.getElementsByName(field.name);
                if (![...radios].some(r => r.checked)) {
                    valid = false;
                    document.querySelector(`.${id}_err`).textContent = rule.message;
                }
            } else if (field.type === 'file' && field.files.length === 0) {
                valid = false;
                document.querySelector(`.${id}_err`).textContent = rule.message;
            } else if (rule.required && !field.value.trim()) {
                valid = false;
                document.querySelector(`.${id}_err`).textContent = rule.message;
            } else if (rule.pattern && !rule.pattern.test(field.value.trim())) {
                valid = false;
                document.querySelector(`.${id}_err`).textContent = rule.patternMessage;
            }
        }

        if (!valid) {
            return;
        }

        document.getElementById('upload_section').style.display = 'block';
        document.getElementById('card-footer').style.display = 'block';

        generatePDF();
    });

    function generatePDF() {
        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);

        Array.from(printContainerClone.querySelectorAll('input, textarea, select')).forEach(el => {
            if (!el.value || el.value.trim() === '') {
                const parentCol = el.closest('.col-md-4, .col-md-5, .col-md-6');
                if (parentCol) parentCol.style.display = 'none';
            }
        });

        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 = 'Change Nursing License Certificate';
        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);

        const prescribedInput = printContainerClone.querySelector('#prescribed_formats');
        if (prescribedInput) {
            prescribedInput.closest('.col-md-4').style.display = 'none';
        }

        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('change-nursing-license-certificate.pdf');
            document.getElementById('saveAndPrintBtn').style.display = 'none';
            document.getElementById('card-footer').style.display = 'block';
        });
    };
</script>

<script>
    $("#addForm").submit(function(e) {
        e.preventDefault();
        const fileField = document.getElementById('prescribed_formats');
        if (!fileField || fileField.files.length === 0) {
            // $('.prescribed_formats_err').text("Please upload application in prescribed format.");
            $('.prescribed_formats_err').text("This field is required");
            return false;
        }
        $("#addSubmit").prop('disabled', true);

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