<x-admin.layout>
    <x-slot name="title">Movie Shooting License (Movie Shooting License) New License and Renewal/ चित्रपट शूटिंग परवाना (चित्रपट शूटिंग परवाना) नवीन परवाना आणि नूतनीकरण</x-slot>
    <x-slot name="heading">Movie Shooting License (Movie Shooting License) New License and Renewal/ चित्रपट शूटिंग परवाना (चित्रपट शूटिंग परवाना) नवीन परवाना आणि नूतनीकरण</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" required>
                                    <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" required>
                                <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" required>
                                <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" required>
                                <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="नाव प्रविष्ट करा प्रथम" required>
                                <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="प्रविष्ट करा मधले नाव" required>
                                <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="आडनाव प्रविष्ट करा" required>
                                <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" required>
                                <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" required></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="पत्ता" required></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" required></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="उद्देश" required></textarea>
                                <span class="text-danger is-invalid marathi_purpose_err"></span>
                            </div>

                             <div class="col-md-4" id="upload_section" style="display:none;">
                                    <label class="col-form-label" for="prescribed_docs">Upload Application In
                                        Prescribed
                                        Format / विहित नमुन्यातील अर्ज अपलोड करा <span
                                            class="text-danger">*</span></label>
                                    <input class="form-control" id="prescribed_docs" name="prescribed_docs"
                                        type="file" required>
                                    <span class="text-danger is-invalid prescribed_docs_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" required>
                                    <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" 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>

{{-- Add --}}
<script>
    $("#addForm").submit(function(e) {
        e.preventDefault();
        $("#addSubmit").prop('disabled', true);

        var formdata = new FormData(this);
        $.ajax({
            url: '{{ route('movie-shooting.store') }}',
            type: 'POST',
            data: formdata,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $('#preloader').css('opacity', '0.5');
                $('#preloader').css('visibility', 'visible');
            },
            success: function(data) {
                $("#addSubmit").prop('disabled', false);
                if (!data.error)
                    swal("Successful!", data.success, "success")
                    .then((action) => {
                        window.location.href = '{{ route('my-application') }}';
                    });
                else
                    swal("Error!", data.error, "error");
            },
            statusCode: {
                422: function(responseObject, textStatus, jqXHR) {
                    $("#addSubmit").prop('disabled', false);
                    resetErrors();
                    printErrMsg(responseObject.responseJSON.errors);
                },
                500: function(responseObject, textStatus, errorThrown) {
                    $("#addSubmit").prop('disabled', false);
                    swal("Error occured!", "Something went wrong please try again", "error");
                }
            },
            complete: function() {
                $('#preloader').css('opacity', '0');
                $('#preloader').css('visibility', 'hidden');
            },
        });

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

    // --- Detect field type based on name/id/placeholder ---
    function detectFieldType(input) {
        const s = ((input.name || '') + ' ' + (input.id || '') + ' ' + (input.placeholder || '')).toLowerCase();
        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|\balternet_email|\balternate_email|\bemail_id/.test(s)) return 'email';
        return null;
    }

    // --- Get associated 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, input) {
        // Aadhaar logic (skip numeric check if file input)
        if (type === 'aadhar') {
            if (input.type === 'file') {
                if (required && !input.files.length) return 'This field is required';
                return '';
            } else {
                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 '';
        }

        return '';
    }

    // --- Validate a single field ---
    function validateField(input) {
        const type = detectFieldType(input);
        const required = input.hasAttribute('required');
        const value = (input.value || '').trim();

        let err = '';
        if (type) {
            err = validateValueByType(value, type, required, input);
        } else if (required) {
            if (input.type === 'file' && !input.files.length) {
                err = 'This field is required';
            } else if (input.type !== 'checkbox' && 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 visible fields (including checkbox rule) ---
    function validateAllFields(form) {
        let allValid = true;
        const inputs = Array.from(form.querySelectorAll('input, textarea, select'));

        inputs.forEach(field => {
            if (field.offsetParent === null) return; // skip hidden fields

            // ✅ Special rule for checkbox (is_correct_info)
            if (field.type === 'checkbox' && (field.id === 'is_correct_info' || field.name === 'is_correct_info')) {
                const errorSpan = getErrorSpan(field);
                if (!field.checked) {
                    if (errorSpan) {
                        errorSpan.textContent = 'Please accept the declaration.';
                        errorSpan.style.display = 'block';
                    }
                    allValid = false;
                } else {
                    if (errorSpan) {
                        errorSpan.textContent = '';
                        errorSpan.style.display = 'none';
                    }
                }
                return;
            }

            // ✅ Normal validation for all other fields
            if (!validateField(field)) 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));

        // ✅ If checkbox is checked later, hide error immediately
        if (input.type === 'checkbox' && (input.id === 'is_correct_info' || input.name === 'is_correct_info')) {
            input.addEventListener('change', () => {
                const span = getErrorSpan(input);
                if (span && input.checked) {
                    span.textContent = '';
                    span.style.display = 'none';
                }
            });
        }
    });

    // Expose global function
    window.validateAllFields = validateAllFields;

});
</script>
