<x-admin.layout>
    <x-slot name="title">Fire No Objection Certificate(Fire) / अग्निशमन ना-हरकत दाखला देणे</x-slot>
    <x-slot name="heading">Fire No Objection Certificate(Fire) / अग्निशमन ना-हरकत दाखला देणे</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" method="post">
                    @csrf

                    <div class="card-header">
                        <h4 class="card-title">Add Details</h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">

                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_full_name">Applicant Full Name / अर्जदाराचे
                                    संपूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_full_name" name="applicant_full_name"
                                    type="text" placeholder="Enter Applicant Full Name">
                                <span class="text-danger is-invalid applicant_full_name_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="building_type">Building Type / इमारतीचा प्रकार<span
                                        class="text-danger">*</span></label>
                                <select class="form-select" name="building_type" id="building_type">
                                    <option value="">Select Type</option>
                                    @php
                                        $options = ['इमारत', 'थिएटर', 'दवाखाना', 'दुकान', 'बंगला', 'मॉल'];
                                    @endphp
                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid building_type_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="building_name">Building name / इमारतीचे नाव <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" type="text" name="building_name" id="building_name"
                                    placeholder="Enter building name">
                                <span class="text-danger is-invalid building_name_err"></span>
                            </div>

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

                            <div class="col-md-4">
                                <label class="col-form-label" for="zone">Zone / झोन<span
                                        class="text-danger">*</span></label>
                                <select class="form-select" name="zone" id="zone">
                                    @php
                                        $options = [
                                            'Prabhag1',
                                            'Prabhag2',
                                            'Prabhag3',
                                            'Prabhag4',
                                            'Prabhag5',
                                            'Prabhag6',
                                        ];
                                    @endphp
                                    <option value="">Select Zone</option>
                                    @foreach ($options as $option)
                                        <option value="{{ $option }}">{{ $option }}</option>
                                    @endforeach
                                </select>
                                <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>
                                <select class="form-select" name="ward" id="ward" required>
                                    <option value="">Select Ward</option>
                                    @foreach ($wards as $ward)
                                        <option value="{{ $ward->id }}">{{ $ward->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="subject">Subject / विषय<span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="subject" name="subject" type="text"
                                    placeholder="Enter Subject">
                                <span class="text-danger is-invalid subject_err"></span>
                            </div>

                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="uploaded_applications">Upload Application In Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="uploaded_applications" name="uploaded_applications" type="file">
                                <span class="text-danger is-invalid uploaded_applications_err"></span>
                            </div> --}}

                            <div class="col-md-4">
                                <label class="col-form-label" for="no_dues_documents">Upload Certificate Of No Dues /
                                    थकबाकी नसल्याचा दाखला अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="no_dues_documents" name="no_dues_documents"
                                    type="file">
                                <span class="text-danger is-invalid no_dues_documents_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="architect_application_documents">Upload Architect
                                    Application / वास्तुविशारद अर्ज अपलोड करा <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="architect_application_documents"
                                    name="architect_application_documents" type="file">
                                <span class="text-danger is-invalid architect_application_documents_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="fire_prevention_documents">Upload Outline Of Fire
                                    Prevention Measures / आग प्रतिबंधक उपायांची रूपरेषा अपलोड करा <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="fire_prevention_documents"
                                    name="fire_prevention_documents" type="file">
                                <span class="text-danger is-invalid fire_prevention_documents_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="capitation_fee_documents">Upload Capitation Fee /
                                    कॅपिटेशन फी अपलोड करा <span class="text-danger">*</span></label>
                                <input class="form-control" id="capitation_fee_documents"
                                    name="capitation_fee_documents" type="file">
                                <span class="text-danger is-invalid capitation_fee_documents_err"></span>
                            </div>

                            <div id="upload_section" style="display: none;">
                                <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="upload_prescribed_formats">Upload Application
                                        in Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span
                                            class="text-danger">*</span></label>
                                    <input class="form-control" id="upload_prescribed_formats"
                                        name="upload_prescribed_formats" type="file">
                                    <span class="text-danger is-invalid upload_prescribed_formats_err"></span>
                                </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. / वरील पुरविलेली सर्व माहिती ही अचूक असून, त्यात कुठल्याही
                                        प्रकारची तफावत आढळल्यास त्यास मी पूर्णतः जबाबदार
                                        असेन."
                                    </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 = {
        'applicant_full_name': {
            required: true,
            message: "Please enter applicant full name."
        },
        'building_type': {
            required: true,
            message: "Please select building type."
        },
        'building_name': {
            required: true,
            message: "Please enter building name."
        },
        'address': {
            required: true,
            message: "Please enter address."
        },
        'mobile_no': {
            required: true,
            message: "Please enter mobile number.",
            pattern: /^\d{10}$/,
            patternMessage: "Mobile number must be 10 digits."
        },
        'email_id': {
            required: true,
            message: "Please enter email.",
            pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
            patternMessage: "Please enter a valid email."
        },
        'aadhar_no': {
            required: true,
            message: "Please enter Aadhar number.",
            pattern: /^\d{12}$/,
            patternMessage: "Aadhar number must be 12 digits."
        },
        'zone': {
            required: true,
            message: "Please select zone."
        },
        'ward': {
            required: true,
            message: "Please select ward."
        },
        'subject': {
            required: true,
            message: "Please enter subject."
        },
        'no_dues_documents': {
            required: true,
            message: "Please upload certificate of no dues."
        },
        'architect_application_documents': {
            required: true,
            message: "Please upload architect application."
        },
        'fire_prevention_documents': {
            required: true,
            message: "Please upload fire prevention outline."
        },
        'capitation_fee_documents': {
            required: true,
            message: "Please upload capitation fee document."
        },
        '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 === '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() {
        const addContainer = document.getElementById('addContainer');
        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 = 'Fire No Objection Certificate(Fire)';
        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="checkbox"]')).forEach(checkbox => {
            const info = document.createElement('span');
            info.style.display = 'inline-block';
            info.style.width = '20px';
            info.style.height = '20px';
            info.style.marginRight = '8px';
            info.style.border = '1px solid #000';
            info.style.textAlign = 'center';
            info.style.lineHeight = '18px';
            info.style.fontSize = '16px';
            info.style.verticalAlign = 'middle';
            info.textContent = checkbox.checked ? '✔' : '';
            const label = checkbox.nextElementSibling;
            if (label) {
                label.prepend(info);
            }
            checkbox.style.display = 'none';
        });

        Array.from(printContainerClone.querySelectorAll('select')).forEach(select => {
            const originalSelect = document.getElementById(select.id);
            let selectedText = '';
            if (originalSelect) {
                if (originalSelect.multiple) {
                    selectedText = Array.from(originalSelect.selectedOptions).map(opt => opt.text).join(', ');
                } else {
                    selectedText = originalSelect.options[originalSelect.selectedIndex].text;
                }
            }

            const span = document.createElement('span');
            span.textContent = selectedText || '-';
            span.style.display = 'inline-block';
            span.style.minWidth = '150px';
            span.style.padding = '12px';
            span.style.border = '1px solid #ccc';
            span.style.borderRadius = '4px';
            span.style.backgroundColor = '#f9f9f9';

            const wrapper = document.createElement('div');
            wrapper.appendChild(span);

            select.parentNode.replaceChild(wrapper, select);
        });

        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('#upload_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('FireNoObjectionCertificate.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('upload_prescribed_formats');
        if (!fileField || fileField.files.length === 0) {
            // $('.upload_prescribed_formats_err').text("Please upload application in prescribed format.");
            $('.upload_prescribed_formats_err').text("This field is required");
            return false;
        }

        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('fire-no-objection.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.error2)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        window.location.href = '{{ route('my-application') }}';
                    });
                else
                    swal("Error!", data.error2, "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>
