@extends('layouts.app')

@section('content')
<div class="card">
    <div class="card-header">
        <h5>Edit Employee Rejoin</h5>
    </div>

    <div class="card-body">
        <form method="POST" id="editForm">
        @csrf
        @method('PUT')

        <div class="row mb-3">
            <div class="col-md-4">
                <label>Employee</label>
                <select name="employee_id" id="employeeSelect"
                        class="form-control" required>
                    <option value="">Select</option>
                    @foreach($employees as $emp)
                        <option value="{{ $emp->id }}" @if($emp->id==$rejoin->employee_id) selected @endif
                            data-working="{{ $emp->currently_working ? 1 : 0 }}"
                            data-attendance="{{ $emp->attendance ? 1 : 0 }}"
                            data-payroll="{{ $emp->payroll ? 1 : 0 }}">
                            {{ $emp->employee_code }} - {{ $emp->first_name }} {{ $emp->last_name }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="col-md-4">
                <label>Rejoin Date</label>
                <input type="date" name="rejoin_date"
                    value="{{ $rejoin->rejoin_date}}"
                    class="form-control" required>
            </div>
        </div>

        <div class="mb-3">
            <label>Remarks</label>
            <textarea name="remarks" class="form-control">{{ $rejoin->remarks }}</textarea>
        </div>

        <button class="btn btn-primary">Update</button>
        <a href="{{ route('core.employee-rejoins.index') }}" class="btn btn-secondary">Cancel</a>

        </form>

    </div>
</div>
@endsection
@section('scripts')
<script>
$('#editForm').on('submit', function (e) {
    e.preventDefault();

    let btn = $(this).find('button[type=submit]');
    btn.prop('disabled', true);

    $.ajax({
        url: "{{ route('core.employee-rejoins.update', $rejoin->id) }}",
        type: "POST",
        data: $(this).serialize(),
        success: function (res) {
            Swal.fire('Success', res.message, 'success')
                .then(() => window.location.href = "{{ route('core.employee-rejoins.index') }}");
        },
        error: function (xhr) {
            btn.prop('disabled', false);
            if (xhr.status === 422) {
                let error = Object.values(xhr.responseJSON.errors)[0][0];
                Swal.fire('Validation Error', error, 'error');
            }
        }
    });
});
</script>
@endsection