<x-admin.layout>
    @push('styles')
    <style>
     .position-relative span.text-danger {
        position: absolute;
        bottom: -1.2em; /* adjust vertical spacing */
        left: 12px;
        font-size: 0.875rem;
        color: red;
    }

    /* Optional: give enough height to row to prevent overlap */
    .mb-4.row {
        min-height: 80px; /* adjust based on input + error text */
    }

    </style>
        
    @endpush
    <x-slot name="title">Issuance of hawker registration certificate/ फेरीवाले नोंदणी प्रमाणपत्र देणे</x-slot>
    <x-slot name="heading">Issuance of hawker registration 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">
                <div class="mb-4 row">
                <div class="col-md-3 position-relative">
                    <label class="col-form-label" for="service_type">Service Id<span class="">*</span></label>
                    <select name="service_type" id="service_type" class="form-select" required>
                        <option value="" disabled selected> -- Select -- </option>
                        <option value="Service 1">Service 1</option>
                        <option value="Service 2">Service 2</option>
                        <option value="Service 3">Service 3</option>
                    </select>
                    <span class="text-danger service_type_err"></span>
                </div>

                <div class="col-md-3 position-relative">
                    <label class="col-form-label" for="licenses_no">License No<span class="">*</span></label>
                    <input class="form-control" id="licenses_no" name="licenses_no" type="text" placeholder="Enter License No" required>
                    <span class="text-danger licenses_no_err"></span>
                </div>

                <div class="col-md-2 d-flex align-items-end">
                    <button type="button" id="searchLicense" class="btn btn-primary w-100">Search</button>
                </div>
                </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="mobile_num">Mobile Number<span class="text-danger">*</span></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" required>
                                <span class="text-danger is-invalid mobile_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-4">
                                <label class="col-form-label" for="aadhar_num">Aadhar Number<span class="text-danger">*</span></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" required>
                                <span class="text-danger is-invalid aadhar_num_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="property_num">Property Number<span class="text-danger">*</span></label>
                                <input class="form-control" id="property_num" name="property_num" type="number" placeholder="Enter Property Number" required>
                                <span class="text-danger is-invalid property_num_err"></span>
                            </div>

                            <div class="col-md-5">
                                <label class="col-form-label" for="address">Residential 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-4">
                                <label class="col-form-label" for="bussiness_type">Bussiness Type<span class="text-danger">*</span></label>
                                <input class="form-control" id="bussiness_type" name="bussiness_type" type="text" placeholder="Enter Bussiness Type" required>
                                <span class="text-danger is-invalid bussiness_type_err"></span>
                            </div>
                            <div class="col-md-4">
                                <label class="col-form-label" for="bussiness_name">Bussiness Name<span class="text-danger">*</span></label>
                                <input class="form-control" id="bussiness_name" name="bussiness_name" type="text" placeholder="Enter Bussiness Name" required>
                                <span class="text-danger is-invalid bussiness_name_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="from_date">From Date<span class="text-danger">*</span></label>
                                <input class="form-control" id="from_date" name="from_date" type="date" required>
                                <span class="text-danger is-invalid from_date_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="to_date">To Date<span class="text-danger">*</span></label>
                                <input class="form-control" id="to_date" name="to_date" type="date" required>
                                <span class="text-danger is-invalid to_date_err"></span>
                            </div>

                            <div class="col-md-4">
                                <label class="col-form-label" for="reason">Reason<span class="text-danger">*</span></label>
                                <input class="form-control" id="reason" name="reason" type="text" placeholder="Enter Reason" required>
                                <span class="text-danger is-invalid reason_err"></span>
                            </div>

                            <div class="col-md-4 mb-2">
                                <label class="col-form-label" for="images">Document<span class="text-danger">*</span></label>
                                <input class="form-control" id="images" name="images" type="file" required>
                                <span class="text-danger is-invalid images_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>

                            <div class="col-md-12 mt-2">
                                <label class="col-form-label" for="is_correct_info">Declaration / घोषणापत्र:</label>
                                <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."
                                    </label>
                                </div>
                                <span class="text-danger is-invalid is_correct_info_err"></span>
                            </div>
                        </div>

                    </div>

                    <div class="form-group text-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>
    document.addEventListener('DOMContentLoaded', function() {
    attachGlobalValidation('#addForm', '#saveAndPrintBtn', {
        containerId: 'addContainer',
        printTitle: 'Trade-license',
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // --- Detect field type for validation ---
    function detectFieldType(input) {
        const s = ((input.name || '') + ' ' + (input.id || '') + ' ' + (input.placeholder || '')).toLowerCase();
        if (/\bfirst_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 '';
    }

    // --- Validate single field ---
    function validateField(input) {

        // ✅ 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', () => {
        const form = document.getElementById('addForm');
        if (!validateAllFields(form)) return;

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

});
</script>


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

    var formdata = new FormData(this);
    $.ajax({
        url: '{{ route('hawker-register.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 occured!", "Something went wrong please try again", "error"); }
        },
        complete: function(){ $('#preloader').css({'opacity':'0','visibility':'hidden'}); },
    });
});
</script>
