<x-admin.layout>
    <x-slot name="title">Giving Part Map / भाग नकाशा देणे</x-slot>
    <x-slot name="heading">Giving Part Map / भाग नकाशा देणे</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 Giving Part Map / भाग नकाशा देणे</h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-3 row">

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_name">Applicant's Full Name / अर्जदाराचे
                                    संपूर्ण नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_name" name="applicant_name" type="text"
                                    pattern="^[A-Za-zअ-हऀ-ॿ\s]+$"
                                    title="Only letters and spaces are allowed. No numbers or special characters."
                                    onkeypress="return isLetterOrSpace(event)" placeholder="Enter Applicant Name">
                                <span class="text-danger is-invalid applicant_name_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="applicant_full_address">Applicant's Full Address /
                                    अर्जदाराचा संपूर्ण पत्ता <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="applicant_full_address" id="applicant_full_address" cols="30" rows="2"
                                    placeholder="Enter Applicant Address"></textarea>
                                <span class="text-danger is-invalid applicant_full_address_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="mouje">मौजे<span
                                        class="text-danger">*</span></label>
                                <textarea class="form-control" type="text" name="mouje" id="mouje" cols="30" rows="2"></textarea>
                                <span class="text-danger is-invalid mouje_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <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="number"
                                    maxlength="10"
                                    oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0, 10);"
                                    placeholder="Enter Mobile Number">
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>
                            <div class="col-md-4 mb-2">
                                <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 mb-2">
                                <label class="col-form-label" for="aadhar_no">Aadhar Number / आधार क्रमांक <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="aadhar_no" name="aadhar_no" type="number"
                                    onkeypress="return isNumberKey(event)" oninput="limitAadharLength(this)"
                                    placeholder="Enter Aadhar Card No">
                                <span class="text-danger is-invalid aadhar_no_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="maptype"> Copy Types <span
                                        class="text-danger">*</span></label>
                                <select name="maptype" id="maptype" class="form-select">
                                    <option value="">Select Copy Types</option>
                                    @foreach ($maptype as $option)
                                        <option value="{{ $option->id }}">{{ $option->type }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid maptype_err"></span>
                            </div>

                            {{-- <div class="col-md-4 mb-2">
                                    <label class="col-form-label" for="zone">Zone <span class="text-danger">*</span></label>
                                    <select name="zone" id="zone" class="form-select">
                                        <option value="">Select Zone</option>
                                        @php
                                            $options = ["Prabhag1", "Prabhag2", "Prabhag3", "Prabhag4", "Prabhag5", "Prabhag6"];
                                        @endphp
                                        @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 mb-2">
                                <label class="col-form-label" for="servey_number">सर्व्हे क्रमांक / सि.टी.एस. क्रमांक
                                    (फक्त सर्व्हे क्रमांक / सि.टी.एस क्रमांक) -<span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="servey_number" name="servey_number" type="text"
                                    placeholder="Enter City Servey Number">
                                <span class="text-danger is-invalid servey_number_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_city_survey_certificates"> Upload 7/12 Utara or City Servey Utara / अपलोड ७/१२ उतारा किंवा सिटी सर्व्हे नकाशा उतारा <span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="upload_city_survey_certificates"
                                    name="upload_city_survey_certificates" type="file">
                                <span class="text-danger is-invalid upload_city_survey_certificates_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="upload_city_servey_maps">Upload Adhaar Photo<span
                                        class="text-danger">*</span></label>
                                <input class="form-control" id="upload_city_servey_maps"
                                    name="upload_city_servey_maps" type="file">
                                <span class="text-danger is-invalid upload_city_servey_maps_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 / घोषणापत्र <span
                                    class="text-danger">*</span></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 = {
        'applicant_name': {
            required: true,
            message: "Please enter applicant full name."
        },
        'applicant_full_address': {
            required: true,
            message: "Please enter applicant full address."
        },
        'mouje': {
            required: true,
            message: "Please enter mouje."
        },
        '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."
        },
        'maptype': {
            required: true,
            message: "Please select copy type."
        },
        'servey_number': {
            required: true,
            message: "Please enter survey number."
        },
        'upload_city_survey_certificates': {
            required: true,
            message: "Please upload 7/12 certificate."
        },
        'upload_city_servey_maps': {
            required: true,
            message: "Please upload Aadhaar photo."
        },
        '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');
        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 = 'Giving Part Map';
        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');
        });

        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('#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('Giving-Part-Map.pdf');
            document.getElementById('saveAndPrintBtn').style.display = 'none';
            document.getElementById('card-footer').style.display = 'block';
        });
    }
</script>


{{-- Add --}}
<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('town-planing-bhag-nakasha.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>
<!--applicant name-->
<script>
    function isLetterOrSpace(e) {
        const char = String.fromCharCode(e.which || e.keyCode);
        const regex = /^[A-Za-zअ-हऀ-ॿ\s]+$/;
        return regex.test(char);
    }
</script>

<!--adhar card no validation-->
<script>
    function isNumberKey(evt) {
        var charCode = evt.which ? evt.which : evt.keyCode;

        if (charCode < 48 || charCode > 57) {
            evt.preventDefault();
            return false;
        }
        return true;
    }


    function limitAadharLength(input) {
        if (input.value.length > 12) {
            input.value = input.value.slice(0, 12);
        }
    }
</script>
