<div class="modal fade" id="modalTambah" tabindex="-1" aria-labelledby="modalTambahShiftLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form id="formTambah">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title fw-bold">Tambah Daily Inspection</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tutup"></button>
                </div>

                <div class="modal-body">
                    <!-- Pilihan Hari -->
                    <div class="d-flex flex-wrap gap-2 justify-content-start mb-3" id="day-buttons">
                        <button type="button" class="btn btn-outline-danger rounded-3" data-day="1">Sen</button>
                        <button type="button" class="btn btn-outline-danger rounded-3" data-day="2">Sel</button>
                        <button type="button" class="btn btn-outline-danger rounded-3" data-day="3">Rab</button>
                        <button type="button" class="btn btn-outline-danger rounded-3" data-day="4">Kam</button>
                        <button type="button" class="btn btn-outline-danger rounded-3" data-day="5">Jum</button>
                        <button type="button" class="btn btn-outline-danger rounded-3" data-day="6">Sab</button>
                        <button type="button" class="btn btn-outline-danger rounded-3" data-day="0">Min</button>
                    </div>

                    <hr>

                    <!-- Nama Shift -->
                    <div class="mb-3">
                        <label for="shift_id" class="form-label fw-semibold">Shift</label>
                        <select name="shift_id" class="form-select shift" id="shift_id">
                            <option value="">- Pilih -</option>
                            @foreach ($shift as $item)
                                <option value="{{ $item->id }}">Shift - {{ $item->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <!-- Unit -->
                    <div class="mb-3">
                        <label for="unit_id" class="form-label fw-semibold">Unit</label>
                        <select name="unit_id" class="form-select unit" id="unit_id">
                            <option value="">- Pilih -</option>
                            @foreach ($unit as $item)
                                <option data-type_id="{{ $item->unittype->id }}" value="{{ $item->id }}">
                                    {{ $item->unit_code }} - {{ $item->unittype->name }} -
                                    {{ $item->serial_number_unit }}
                                    {{ auth()->user()->name == 'Admin' ? '- ' . $item->location->name : '' }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <!-- Checklist -->
                    <div class="mb-3">
                        <label for="form_id" class="form-label fw-semibold">Checklist</label>
                        <select name="form_id" class="form-select checklist" id="form_id">
                            <option value="">- Silahkan pilih Unit -</option>
                        </select>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary">Lanjutkan</button>
                </div>
            </div>
        </form>
    </div>
</div>

@push('extraJS')
    <script>
        $(document).ready(function () {
            $(" #modalTambah .shift").select2({
                dropdownParent: $('#modalTambah'),
                width: '100%',
                allowClear: true,
                theme: "bootstrap",
                placeholder: "Pilih Shift"
            })

            $(" #modalTambah .unit").select2({
                dropdownParent: $('#modalTambah'),
                width: '100%',
                allowClear: true,
                theme: "bootstrap",
                placeholder: "Pilih Unit"
            })

            $(" #modalTambah .checklist").select2({
                dropdownParent: $('#modalTambah'),
                width: '100%',
                allowClear: true,
                theme: "bootstrap",
            })

            var today = new Date().getDay(); // 0 = Min, 1 = Sen, dst
            var $buttons = $('#day-buttons button');

            $buttons.each(function () {
                var $btn = $(this);
                var day = parseInt($btn.data('day'));

                $btn.removeClass('btn-danger').addClass('btn-outline-danger');
                if (day === today) {
                    $btn.removeClass('btn-outline-danger').addClass('btn-danger');
                }
            });

            $('#unit_id').on('change', function () {
                var unitId = $(this).find(':selected').data('type_id');
                var $formSelect = $('#form_id');
                $formSelect.html('<option value="">- Silahkan pilih Unit -</option>');
                if (unitId) {
                    $.ajax({
                        url: "{{ route('get-form-by-type-unit', '') }}/" + unitId,
                        type: "GET",
                        dataType: "json",
                        success: function (res) {
                            console.log(res);
                            $formSelect.empty();
                            $formSelect.append('<option value="">- Pilih -</option>');

                            if (res && res.length > 0) {
                                $.each(res, function (i, item) {
                                    $formSelect.append('<option value="' + item.id +
                                        '">' + item.title + '</option>');
                                });
                            } else {
                                $formSelect.append(
                                    '<option value="">Tidak ada checklist</option>');
                            }
                        },
                        error: function () {
                            $formSelect.html('<option value="">Gagal memuat data</option>');
                        }
                    });
                } else {
                    $formSelect.html('<option value="">- Silahkan pilih Unit -</option>');
                }
            });

            $('#formTambah').on('submit', function (e) {
                e.preventDefault();
                const form = $(this);


                $.post({
                    url: '{{ route('daily-report.store') }}',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: form.serialize(),
                    success: function (response) {

                        if (response.status === 1) {
                            $('#modalTambah').modal('hide');
                            form.trigger("reset");

                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil!',
                                text: response.message,
                                timer: 2000,
                                showConfirmButton: false
                            });

                            window.location.href = response.redirect;
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal Menyimpan',
                                text: response.message
                            });
                        }
                    },
                    error: function (xhr) {
                        let message = xhr.responseJSON?.message || 'Terjadi kesalahan';
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal Menyimpan',
                            text: message
                        });

                        handleValidationErrors(xhr, form);
                    }
                });
            });

        });
    </script>
@endpush
