<x-admin.layout>
    <x-slot name="title">सोलार पॉवर / सोलार वॉटर हिटिंग ना हरकत दाखला / Solar Power / Solar Water Heating No Objection Certificate</x-slot>
    <x-slot name="heading">सोलार पॉवर / सोलार वॉटर हिटिंग ना हरकत दाखला / Solar Power / Solar Water Heating No Objection Certificate</x-slot>

    <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">

                        {{-- Applicant Details --}}
                        <h5 class="text-primary">Applicant Details / अर्जदाराची माहिती</h5>
                        <div class="mb-3 row">
                            <div class="col-md-4">
                                <label class="col-form-label" for="applicant_name">Applicant Name / अर्जदाराचे नाव<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_name" name="applicant_name" type="text" 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="applicant_address">Applicant Address / अर्जदाराचा पत्ता<span class="text-danger">*</span></label>
                                <input class="form-control" id="applicant_address" name="applicant_address" type="text" placeholder="Enter Address / पत्ता भरा" required>
                                <span class="text-danger is-invalid applicant_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" placeholder="Enter Mobile No. / मोबाईल नंबर भरा" maxlength="10" pattern="\d{10}" title="Please enter exactly 10 digits" required inputmode="numeric" oninput="this.value = this.value.replace(/[^0-9]/g, '').slice(0,10);" required>
                                <span class="text-danger is-invalid mobile_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="ward_area">Ward Area / प्रभाग क्षेत्र<span class="text-danger">*</span></label>
                                <select class="form-select" name="ward_area" id="ward_area" required>
                                    <option value="">Select Ward Area</option>
                                    @foreach ($wards as $ward)
                                        <option value="{{ $ward->id }}">{{ $ward->name }}</option>
                                    @endforeach
                                </select>
                                <span class="text-danger is-invalid ward_area_err"></span>
                            </div>
                            {{-- <div class="col-md-4">
                                <label class="col-form-label" for="stall_type">Stall Type / ईमेल आयडी<span class="text-danger">*</span></label>
                                <input class="form-control" id="stall_type" name="stall_type" type="stall_type" placeholder="Enter Stall Type / ईमेल भरा">
                                <span class="text-danger is-invalid stall_type_err"></span>
                            </div> --}}
                        </div>

                        <h5 class="text-primary">Stall Information / स्टॉलची माहिती</h5>
                        <div class="mb-3 row">
                            <div class="col-md-4">
                                <label class="col-form-label" for="stall_place">Stall Place/ अर्जदाराचा पत्ता<span class="text-danger">*</span></label>
                                <input class="form-control" id="stall_place" name="stall_place" type="text" placeholder="Enter Stall Place / पत्ता भरा" required>
                                <span class="text-danger is-invalid stall_place_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="stall_type">Stall Type / स्टॉल प्रकार <span class="text-danger">*</span></label>
                                <select class="form-control" id="stall_type" name="stall_type" onchange="showRelevantField()" required>
                                    <option value=""> -- Select Stall Type / स्टॉल प्रकार निवडा --</option>
                                    <option value="Divyang Stall / दिव्यांग स्टॉल">Divyang Stall / दिव्यांग स्टॉल</option>
                                    <option value="Gatai Stall / गटाई स्टॉल">Gatai Stall / गटाई स्टॉल</option>
                                    <option value="Dudh Kendra / दूध केंद्र">Dudh Kendra / दूध केंद्र</option>
                                    <option value="Other / इतर">Other / इतर</option>
                                </select>
                                <span class="text-danger is-invalid stall_type_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="authorization">Authorization / अधिकृतता <span class="text-danger">*</span> </label>
                                <select class="form-control" id="authorization" name="authorization" required>
                                    <option value=""> -- Select Authorization / अधिकृतता निवडा --</option>
                                    <option value="Yes">Yes / होय</option>
                                    <option value="No">No / नाही</option>
                                </select>
                                <span class="text-danger is-invalid authorization_err"></span>
                            </div>
                            {{--

                            <div class="col-md-4">
                                <label class="col-form-label" for="work_order_no">Work Order Number / काम आदेश क्रमांक<span class="text-danger">*</span></label>
                                <input class="form-control" id="work_order_no" name="work_order_no" type="text" placeholder="Enter Work Order No. / काम आदेश क्रमांक भरा">
                                <span class="text-danger is-invalid work_order_no_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="work_completition_date">Work Completion Date / काम पूर्ण होण्याची तारीख<span class="text-danger">*</span></label>
                                <input class="form-control" id="work_completition_date" name="work_completition_date" type="date">
                                <span class="text-danger is-invalid work_completition_date_err"></span>
                            </div> --}}
                        </div>

                        {{-- Documents --}}
                        <h5 class="text-primary">Documents / कागदपत्रे</h5>
                        <div class="mb-3 row">
                            <div class="col-md-3">
                                <label class="col-form-label" for="mul_parnaga_pics">Primary Licensing Department / मूल परवाना विभाग<span class="text-danger">*</span></label>
                                <input class="form-control" id="mul_parnaga_pics" name="mul_parnaga_pics" type="file" required>
                                <span class="text-danger is-invalid mul_parnaga_pics_err"></span>
                            </div>
                            <div class="col-md-3">
                                <label class="col-form-label" for="adhar_card_pics"> Aadhaar Card Department / आधार कार्ड विभाग<span class="text-danger">*</span></label>
                                <input class="form-control" id="adhar_card_pics" name="adhar_card_pics" type="file" required>
                                <span class="text-danger is-invalid adhar_card_pics_err"></span>
                            </div>
                            <div class="col-md-3">
                                <label class="col-form-label" for="pics"> Picture / छायाचित्र<span class="text-danger">*</span></label>
                                <input class="form-control" id="pics" name="pics" type="file" required>
                                <span class="text-danger is-invalid pics_err"></span>
                            </div>
                            <div class="col-md-3" id="handicap_pic_div" style="display: none;">
                                <label class="col-form-label" for="handicap_pic">Handicap Picture / दिव्यांग चिन्ह<span class="text-danger">*</span></label>
                                <input class="form-control" id="handicap_pic" name="handicap_pics" type="file">
                                <span class="text-danger is-invalid handicap_pic_err"></span>
                            </div>

                            <div class="col-md-3" id="caste_pic_div" style="display: none;">
                                <label class="col-form-label" for="caste_pic">Caste Picture / जात<span class="text-danger">*</span></label>
                                <input class="form-control" id="caste_pic" name="caste_pics" type="file">
                                <span class="text-danger is-invalid caste_pic_err"></span>
                            </div>

                            <div class="col-md-3" id="milk_center_pic_div" style="display: none;">
                                <label class="col-form-label" for="milk_center_pic">Milk Center Picture / दुध केंद्र<span class="text-danger">*</span></label>
                                <input class="form-control" id="milk_center_pic" name="milk_center_pics" type="file">
                                <span class="text-danger is-invalid milk_center_pic_err"></span>
                            </div>

                            <div class="col-md-3" id="gumasta_license_pic_div" style="display: none;">
                                <label class="col-form-label" for="gumasta_license_pic">Gumasta License Picture / गुमास्ता लायसन्स<span class="text-danger">*</span></label>
                                <input class="form-control" id="gumasta_license_pic" name="gumasta_license_pics" type="file">
                                <span class="text-danger is-invalid gumasta_license_pic_err"></span>
                            </div>
                        </div>

                        <div class="col-md-4" id="upload_section" style="display:none;">
                            <label class="col-form-label" for="prescribed_doc">Upload Application In Prescribed Format / विहित नमुन्यातील अर्ज अपलोड करा <span class="text-danger">*</span></label>
                            <input class="form-control" id="prescribed_doc" name="prescribed_docs" type="file" placeholder="Enter Document No. / दस्तऐवज क्रमांक भरा">
                            <span class="text-danger is-invalid prescribed_doc_err"></span>
                        </div>
                        {{-- Declaration --}}
                        <div class="mb-3 row">
                            <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>

                    {{-- Footer --}}
                    <div class="form-group" style="text-align: center;">
                        <button type="button" id="saveAndPrintBtn" class="btn btn-success">
                            <span class="btn-text">Save and Print</span>
                            <span class="spinner-border spinner-border-sm ms-2 d-none btn-loader"></span>
                        </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 --}}
<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>
    $("#addForm").submit(function(e) {
        e.preventDefault();

        const fileField = document.getElementById('prescribed_doc');
        if (!fileField || fileField.files.length === 0) {
            // $('.prescribed_formats_err').text("Please upload application in prescribed format.");
            $('.prescribed_doc_err').text("This field is required");
            return false;
        }
        $("#addSubmit").prop('disabled', true);
        let formdata = new FormData(this);
        $.ajax({
            url: '{{ route('solarpower-heater.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $('#preloader').css({
                    opacity: '0.5',
                    visibility: 'visible'
                });
            },
            success: function(data) {
                $("#addSubmit").prop('disabled', false);
                if (!data.error) {
                    swal("Successful!", data.success, "success").then(() => {
                        window.location.href = '{{ route('my-application') }}';
                    });
                } else {
                    swal("Error!", data.error, "error");
                }
            },
            statusCode: {
                422: function(response) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(response.responseJSON.errors);
                },
                500: function() {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occurred!", "Something went wrong. Please try again.", "error");
                }
            },
            complete: function() {
                $('#preloader').css({
                    opacity: '0',
                    visibility: 'hidden'
                });
            },
        });
    });
</script>


<script>
    function showRelevantField() {
        const selectedValue = document.getElementById("stall_type").value;

        document.getElementById("handicap_pic_div").style.display = "none";
        document.getElementById("caste_pic_div").style.display = "none";
        document.getElementById("milk_center_pic_div").style.display = "none";
        document.getElementById("gumasta_license_pic_div").style.display = "none";


        handleStallType(selectedValue);

    }

    function handleStallType(selectedValue) {
        // Hide all divs first
        const allDivs = [
            "handicap_pic_div",
            "caste_pic_div",
            "milk_center_pic_div",
            "gumasta_license_pic_div"
        ];

        allDivs.forEach(id => {
            document.getElementById(id).style.display = "none";
            $('#' + id.replace('_div', '')).attr('required', false);
        });

        // Show based on selection
        switch (selectedValue) {

            case "Divyang Stall / दिव्यांग स्टॉल":
                toggleDiv("handicap_pic_div", true);
                break;

            case "Gatai Stall / गटाई स्टॉल":
                toggleDiv("caste_pic_div", true);
                break;

            case "Dudh Kendra / दूध केंद्र":
                toggleDiv("milk_center_pic_div", true);
                break;

            case "Other / इतर":
                toggleDiv("gumasta_license_pic_div", true);
                break;
        }
    }

    // Helper function to show div + set required field
    function toggleDiv(divId, required = false) {
        document.getElementById(divId).style.display = "block";
        let inputId = divId.replace('_div', '');
        $('#' + inputId).attr('required', required);
    }
</script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // attachGlobalValidation('#addForm', '#saveAndPrintBtn', {
        //     containerId: 'addContainer',
        //     printTitle: 'Solar-Power',
        // });
    });
</script>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // --- Detect field type for validation ---
        function detectFieldType(input) {
            const s = ((input.name || '') + ' ' + (input.id || '') + ' ' + (input.placeholder || '')).toLowerCase();
            if (/\applicant_name|\bf_name|\bmiddle_name|\bm_name|\blast_name|\bl_name/.test(s)) return 'name';
            if (/\baadhaar|\baadhar|\baadhar_no|\baadhar_num|\baadhar-number/.test(s)) return 'aadhar';
            if (/\bmobile|\bmobile_no|\bcontact|\bcontact_no|\bphone|\btelephone|\btel/.test(s)) return 'phone';
            if (/\bemail|\be-mail|\bmail|\balternate_email|\balternate_email|\bemail_id/.test(s)) return 'email';
            if (/\bpan|\bpancard|\bpan_no|\bpan_number/.test(s)) return 'pan';
            return null;
        }

        // --- Get error span ---
        function getErrorSpan(input) {
            if (input.name) {
                const spanByName = document.querySelector(`.${input.name}_err`);
                if (spanByName) return spanByName;
            }
            if (input.id) {
                const spanById = document.querySelector(`.${input.id}_err`);
                if (spanById) return spanById;
            }
            return input.closest('div')?.querySelector('span.text-danger') || null;
        }

        // --- Validation rules ---
        function validateValueByType(value, type, required) {
            if (type === 'name') {
                if (required && value === '') return 'This field is required';
                if (value && !/^[A-Za-z\s]+$/.test(value)) return 'Only letters and spaces are allowed';
                return '';
            }
            if (type === 'aadhar') {
                if (required && value === '') return 'Aadhaar number is required';
                if (value && !/^\d{12}$/.test(value)) return 'Enter a valid 12-digit Aadhaar number';
                return '';
            }
            if (type === 'phone') {
                if (required && value === '') return 'Mobile number is required';
                if (value && !/^[6-9]\d{9}$/.test(value)) return 'Enter a valid 10-digit mobile number';
                return '';
            }
            if (type === 'email') {
                if (required && value === '') return 'Email is required';
                if (value && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return 'Enter a valid email address';
                return '';
            }
            if (type === 'pan') {
                if (required && value === '') return 'This field is required';
                if (value && !/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/.test(value.toUpperCase())) return 'Enter a valid PAN number';
                return '';
            }
            return '';
        }

        function validateField(input) {
            if (input.type === "file") {
                const file = input.files[0];
                const span = getErrorSpan(input);

                if (file) {
                    if (file.size > 2 * 1024 * 1024) { // > 2MB
                        if (span) {
                            span.textContent = `File must be less than 2MB.`;
                            span.style.display = "block";
                        }
                        input.classList.add("is-invalid");
                        input.setAttribute("aria-invalid", "true");
                        return false;
                    } else {
                        if (span) {
                            span.textContent = "";
                            span.style.display = "none";
                        }
                        input.classList.remove("is-invalid");
                        input.removeAttribute("aria-invalid");
                        return true;
                    }
                } else if (input.hasAttribute('required')) {
                    if (span) {
                        span.textContent = "This file is required";
                        span.style.display = "block";
                    }
                    input.classList.add("is-invalid");
                    input.setAttribute("aria-invalid", "true");
                    return false;
                }

                return true;
            }

            // Checkbox validation (must come first)
            if (input.type === 'checkbox' && (input.id === 'is_correct_info' || input.name === 'is_correct_info')) {
                const span = getErrorSpan(input);
                if (!input.checked) {
                    if (span) {
                        span.textContent = 'Please accept the declaration.';
                        span.style.display = 'block';
                    }
                    input.classList.add('is-invalid');
                    return false;
                } else {
                    if (span) {
                        span.textContent = '';
                        span.style.display = 'none';
                    }
                    input.classList.remove('is-invalid');
                    input.removeAttribute('aria-invalid');
                    return true;
                }
            }

            const value = (input.value || '').trim();
            const required = input.hasAttribute('required');
            const type = detectFieldType(input);

            let err = '';
            if (type) err = validateValueByType(value, type, required);
            else if (required && value === '') err = 'This field is required';

            const span = getErrorSpan(input);
            if (span) {
                span.textContent = err;
                span.style.display = err ? 'block' : 'none';
            }

            if (err) {
                input.classList.add('is-invalid');
                input.setAttribute('aria-invalid', 'true');
            } else {
                input.classList.remove('is-invalid');
                input.removeAttribute('aria-invalid');
            }

            return !err;
        }

        // --- Validate all fields ---
        function validateAllFields(form) {
            let allValid = true;
            const inputs = Array.from(form.querySelectorAll('input, textarea, select'));
            inputs.forEach(input => {
                if (input.offsetParent === null) return; // skip hidden
                if (!validateField(input)) allValid = false;
            });
            return allValid;
        }

        // --- Attach input/blur events ---
        const allInputs = Array.from(document.querySelectorAll('input, textarea, select'));
        allInputs.forEach(input => {
            input.addEventListener('input', () => validateField(input));
            input.addEventListener('blur', () => validateField(input));
        });

        window.validateAllFields = validateAllFields;

        // --- Save & Print button ---
        document.getElementById('saveAndPrintBtn').addEventListener('click', async () => {
            const form = document.getElementById('addForm');
            if (!validateAllFields(form)) return;

            const btn = document.getElementById('saveAndPrintBtn');
            const btnText = btn.querySelector('.btn-text');
            const loader = btn.querySelector('.btn-loader');

            // Disable button & show loader on the button
            btn.disabled = true;
            btnText.textContent = "Generating PDF...";
            loader.classList.remove('d-none');

            // Show footer only after validation passes
            document.getElementById('card-footer').style.display = 'block';

            // Wait until pdf is fully generated
            await generatePDF1();

            // Enable button again after PDF generated
            btn.disabled = false;
            btnText.textContent = "Save and Print";
            loader.classList.add('d-none');
        });


    });

   function generatePDF1() {

        document.getElementById('card-footer').style.display = 'block';
        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 = 'SolarPower';
        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';
            select.parentNode.replaceChild(span, 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('#uploaded_applications');
        if (prescribedInput) {
            prescribedInput.closest('.col-md-4').style.display = 'none';
        }

        html2canvas(printContainerClone, {
            scrollY: -window.scrollY,
            backgroundColor: '#fff',
            scale: 1,
            useCORS: true,
            allowTaint: true
        }).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('SolarPower.pdf');
             document.getElementById('upload_section').style.display = 'block';
            document.getElementById('saveAndPrintBtn').style.display = 'none';
        });
    }
</script>
