<div class="modal fade lead-modal in" id="lead-modal" role="dialog" aria-labelledby="myLargeModalLabel">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content data">
            <div class="modal-header modal-header-image mb-3">
                <h5 class="modal-title text-white">{{ @$data['title'] }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                    <i class="fa fa-times text-white" aria-hidden="true"></i>
                </button>
            </div>

            <div class="modal-body">
                <div class="row p-2">
                    <div class="col-md-12">
                        <form id="salaryForm" action="{{ route('hrm.payroll_salary.generate') }}" method="POST">
                            @csrf

                            {{-- Department --}}
                            <div class="col-md-12 form-group mb-3" id="department_section">
                                <label class="form-label">{{ _trans('common.Department') }}</label>
                                <select id="department_id" name="department_id" class="form-select mb-3 modal_select2"
                                    data-placeholder="{{ _trans('common.Choose One') }}">
                                    <option value="">{{ _trans('common.Choose One') }}</option>
                                    @foreach ($data['departments'] as $department)
                                        <option value="{{ $department->id }}"
                                            {{ old('department_id') == $department->id ? 'selected' : '' }}>
                                            {{ $department->title }}
                                        </option>
                                    @endforeach
                                </select>
                                <div class="error_show_department"></div>
                                @error('department_id')
                                    <div class="text-danger">{{ $message }}</div>
                                @enderror
                            </div>

                            {{-- Employee --}}
                            <div class="col-md-12 form-group mb-3" id="employee_section">
                                <label class="form-label">{{ _trans('common.Employee') }}</label>
                                <select name="employee_id" id="employee_id"
                                    class="form-select select2-input ot-input mb-3 modal_select2"
                                    data-placeholder="{{ _trans('common.Choose One') }}">
                                    <option value="">{{ _trans('common.Choose One') }}</option>
                                    @foreach ($data['employees'] as $employee)
                                        <option value="{{ $employee->id }}"
                                            {{ old('employee_id') == $employee->id ? 'selected' : '' }}>
                                            {{ $employee->name }} - {{ $employee->userID }}
                                        </option>
                                    @endforeach
                                </select>
                                <div class="error_show_employee"></div>
                                @error('employee_id')
                                    <div class="text-danger">{{ $message }}</div>
                                @enderror
                            </div>

                            {{-- Month --}}
                            <div class="form-group mb-3">
                                <label class="form-label">{{ _trans('common.Date') }}</label>
                                <input type="month"
                                    class="form-control ot-form-control ot-input @error('month') is-invalid @enderror"
                                    id="month" name="month" value="{{ old('month', date('Y-m')) }}" required />
                            </div>

                            <div class="form-group text-right mt-3 d-flex justify-content-end">
                                <button type="submit" class="btn btn-gradian pull-right">
                                    <b>{{ @$data['button'] }}</b>
                                </button>
                            </div>
                        </form> <!-- #salaryForm -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- include your modal helper -->
<script src="{{ global_asset('backend/js/fs_d_ecma/modal/__modal.min.js') }}"></script>

<script>
    $(function() {
        // Helper: show/hide sections based on current values
        function toggleSections() {
            const deptVal = $('#department_id').val();
            const empVal = $('#employee_id').val();

            if (deptVal) {
                $('#employee_section').hide();
            } else {
                $('#employee_section').show();
            }

            if (empVal) {
                $('#department_section').hide();
            } else {
                $('#department_section').show();
            }
        }

        // Initial toggle (useful if old() values exist)
        toggleSections();

        // When department changes: hide employee and clear it
        $(document).on('change', '#department_id', function() {
            const v = $(this).val();
            if (v) {
                $('#employee_section').hide();
                // clear employee select (works with or without Select2)
                $('#employee_id').val(null).trigger('change');
            } else {
                $('#employee_section').show();
            }

            // Clear department errors (visual)
            $('.error_show_department').html('');
            $('#department_id').removeClass('is-invalid');
            if ($.fn.select2) {
                $('#department_id').next('.select2-container').find('.select2-selection').removeClass(
                    'is-invalid');
            }
        });

        // When employee changes: hide department and clear it
        $(document).on('change', '#employee_id', function() {
            const v = $(this).val();
            if (v) {
                $('#department_section').hide();
                $('#department_id').val(null).trigger('change');
            } else {
                $('#department_section').show();
            }

            // Clear employee errors (visual)
            $('.error_show_employee').html('');
            $('#employee_id').removeClass('is-invalid');
            if ($.fn.select2) {
                $('#employee_id').next('.select2-container').find('.select2-selection').removeClass(
                    'is-invalid');
            }
        });

        // AJAX submit
        $('#salaryForm').on('submit', function(e) {
            e.preventDefault();

            // Clear old validation UI
            $('.error_show_department, .error_show_employee').html('');
            $('#department_id, #employee_id').removeClass('is-invalid');

            if ($.fn.select2) {
                $('#department_id').next('.select2-container').find('.select2-selection').removeClass(
                    'is-invalid');
                $('#employee_id').next('.select2-container').find('.select2-selection').removeClass(
                    'is-invalid');
            }

            const $form = $(this);

            $.ajax({
                url: $form.attr('action'),
                method: $form.attr('method'),
                data: $form.serialize(),
                dataType: 'json',
                success: function(res) {
                    if (res.result || res.success) {
                        Swal.fire({
                            title: res.message || 'Success',
                            icon: 'success',
                            showConfirmButton: false,
                            timer: 1500
                        });
                        setTimeout(function() {
                            location.reload();
                        }, 1200);
                        return;
                    }
                    Swal.fire({
                        title: res.message || 'Done',
                        icon: 'info'
                    });
                },
                error: function(xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON?.errors || {};

                        if (errors.department_id) {
                            $('#department_id').addClass('is-invalid');
                            $('.error_show_department').html(
                                '<div class="invalid-feedback d-block">' + errors
                                .department_id[0] + '</div>');
                            if ($.fn.select2) {
                                $('#department_id').next('.select2-container').find(
                                    '.select2-selection').addClass('is-invalid');
                            }
                        }
                        if (errors.employee_id) {
                            $('#employee_id').addClass('is-invalid');
                            $('.error_show_employee').html(
                                '<div class="invalid-feedback d-block">' + errors
                                .employee_id[0] + '</div>');
                            if ($.fn.select2) {
                                $('#employee_id').next('.select2-container').find(
                                    '.select2-selection').addClass('is-invalid');
                            }
                        }
                        $('#lead-modal').modal('show');
                    } else {
                        // other errors
                        console.error(xhr);
                        Swal.fire({
                            title: xhr.responseJSON?.message,
                            icon: 'error'
                        });
                    }
                }
            });
        });
    });
</script>
