@extends('template.master')
{{-- modal --}}

{{-- modal --}}
@section('content')
    @if ($canCreate)
        <x-primary-button data-bs-toggle="modal" data-bs-target="#modalTambah" class="mb-4">Tambah Data
            Checklist</x-primary-button>
    @endif

    <div class="card">
        <div class="card-body">
            <table id="activeTable" class="table table-striped data-table">
                <thead>
                    <tr>
                        <th id="no">No</th>
                        <th>Judul inspeksi</th>
                        <th>Tipe</th>
                        <th>Catatan</th>
                        <th width="105px">Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>

    @include('checklist.modal.add')
    @include('checklist.modal.edit')
@endsection
@push('extraJS')
    <script type="text/javascript">
        $(document).ready(function () {
            $(function () {
                var table = $('#activeTable').DataTable({
                    processing: true,
                    serverSide: true,
                    ajax: {
                        url: "{{ route('checklist.index') }}",
                        data: function (d) {
                            d.option = "active";
                        },
                    },
                    columnDefs: [{
                        width: "50px",
                        targets: 0
                    },
                    {
                        width: "250px",
                        targets: 1
                    }  // 0 adalah index kolom 'id'
                    ],
                    columns: [{
                        data: 'DT_RowIndex',
                        name: 'DT_RowIndex',
                        className: 'text-center',
                        orderable: false,
                        searchable: false
                    },
                    {
                        data: 'title',
                        name: 'title'
                    },
                    {
                        data: 'type_unit',
                        name: 'type_unit'
                    },
                    {
                        data: 'note',
                        name: 'note'
                    },
                    {
                        data: 'action',
                        name: 'action',
                        orderable: false,
                        searchable: false
                    },
                    ]
                });
            });

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

            $("#modalEdit .type-unit").select2({
                dropdownParent: $('#modalEdit'),
                width: '100%',
                allowClear: true,
                theme: "bootstrap",
                placeholder: "Pilih tipe inspeksi"
            })

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


                $.ajax({
                    url: '{{ route('checklist.store') }}',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: form.serialize(),
                    success: function (response) {
                        $('#modalTambah').modal('hide');
                        form.trigger("reset");

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

                        $('.data-table').DataTable().ajax.reload();
                    },
                    error: function (xhr) {
                        let message = xhr.responseJSON?.message || 'Terjadi kesalahan';
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal Menyimpan',
                            text: message
                        });

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

            // edit
            $(document).on('click', '.edit', function () {
                let id = $(this).data('id');
                let title = $(this).data('title');
                let note = $(this).data('note');
                let type_unit = $(this).data('type_unit');

                $('#edit-id').val(id);
                $('#edit-title').val(title);
                $('#edit-note').val(note);
                $('#edit-type_unit').val(type_unit).trigger("change");
                $('#modalEdit').modal('show');
            });

            // Handle form submit edit
            $('#formEdit').on('submit', function (e) {
                e.preventDefault();
                const form = $(this);

                let id = $('#edit-id').val();

                $.ajax({
                    url: `{{ route('checklist.update', ":id") }}`.replace(":id", id),
                    type: 'PUT',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: form.serialize(),
                    success: function (response) {
                        $('#modalEdit').modal('hide');

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

                        $('.data-table').DataTable().ajax.reload();
                    },
                    error: function (xhr) {
                        let message = xhr.responseJSON?.message || 'Terjadi kesalahan saat update.';
                        Swal.fire({
                            icon: 'error',
                            title: 'Gagal Update',
                            text: message
                        });

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

            // delete
            $(document).on("click", ".delete", function () {
                var id = $(this).data("id");

                Swal.fire({
                    title: 'Apakah kamu yakin?',
                    text: "Data akan dihapus secara permanen!",
                    icon: 'warning',
                    showCancelButton: true,
                    cancelButtonColor: '#3085d6',
                    confirmButtonColor: '#d33',
                    confirmButtonText: 'Ya, hapus!',
                    cancelButtonText: 'Batal'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: `{{ route('checklist.destroy', ":id") }}`.replace(":id", id),
                            type: 'DELETE',
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            },
                            success: function (res) {
                                Swal.fire('Terhapus!', res.message, 'success');
                                $('.data-table').DataTable().ajax.reload();
                            },
                            error: function (xhr) {
                                console.log(xhr);
                                Swal.fire('Gagal!', 'Gagal menghapus data, Data sedang digunakan.', 'error');
                            }
                        });
                    }
                });
            });
        })
    </script>
@endpush
