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

{{-- modal --}}
@section('content')
    @if ($canCreate)
        <x-primary-button data-bs-toggle="modal" data-bs-target="#modalTambah" class="mb-4">Add Unit Type</x-primary-button>
    @endif
    <div class="card">
        <div class="card-body">
            <table class="table table-striped data-table">
                <thead>
                    <tr>
                        <th id="no">No</th>
                        <th>Name Unit Type</th>
                        <th>Icon</th>
                        <th width="105px">Action</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    @include('parts.unit_type.modal.add')
    @include('parts.unit_type.modal.edit')
@endsection
@push('extraJS')
    <script type="text/javascript">
        $(function () {
            var table = $('.data-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: "{{ route('unit-type.index') }}",
                columnDefs: [{
                    width: "50px",
                    targets: 0
                } // 0 adalah index kolom 'id'
                ],
                columns: [{
                    data: 'DT_RowIndex',
                    name: 'DT_RowIndex',
                    className: 'text-center',
                    orderable: false,
                    searchable: false
                },
                {
                    data: 'name',
                    name: 'name'
                },
                {
                    data: 'image',
                    name: 'image'
                },
                {
                    data: 'action',
                    name: 'action',
                    orderable: false,
                    searchable: false
                },
                ]
            });

        });

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

            let form = $(this)[0];
            let formData = new FormData(form);

            $.ajax({
                url: '{{ route('unit-type.store') }}',
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data: formData,
                contentType: false,
                processData: false,
                success: function (response) {
                    $('#modalTambah').modal('hide');
                    $('#formTambah').trigger("reset");
                    $('.data-table').DataTable().ajax.reload();

                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: 'Data berhasil ditambah.',
                        showConfirmButton: false,
                        timer: 1500
                    });
                },
                error: function (xhr) {
                    let message = xhr.responseJSON?.message || 'Terjadi kesalahan';
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal Menyimpan',
                        text: message
                    });
                }
            });
        });



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

            $('#edit-id').val(id);
            $('#edit-name').val(name);
            $('#modalEdit').modal('show');
        });

        $('#formEdit').on('submit', function (e) {
            e.preventDefault();

            const form = $(this)[0];
            const id = $('#edit-id').val();
            const formData = new FormData(form);
            formData.append('_method', 'PUT');

            $(".loading").show();

            $.ajax({
                url: `{{ route('unit-type.update', ':id') }}`.replace(':id', id),
                type: 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    $('#modalEdit').modal('hide');
                    $('#formEdit').trigger("reset");
                    $('.data-table').DataTable().ajax.reload();

                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: response.message,
                        showConfirmButton: false,
                        timer: 1500
                    });
                },
                error: function (xhr) {
                    let message = xhr.responseJSON?.message || 'Terjadi kesalahan';
                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal Menyimpan',
                        text: message
                    });
                },
                complete: function () {
                    $(".loading").hide();
                }
            });
        });

        // 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,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Ya, hapus!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `{{ route('unit-type.destroy', ':id') }}`.replace(':id', id),
                        type: 'POST',
                        data: {
                            _method: 'DELETE',
                            _token: '{{ csrf_token() }}'
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function (res) {
                            Swal.fire('Data berhasil Dihapus!', res.message, 'success');
                            $('.data-table').DataTable().ajax.reload();
                        },
                        error: function (xhr) {
                            Swal.fire('Gagal!', 'Data gagal dihapus.', 'error');
                        }
                    });
                }
            });
        });
    </script>
@endpush
