@extends('layout.main')

@section('content')
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">
        <div class="card-header border-bottom">
            <h5 class="card-title mb-0">Data Master Komoditas</h5>
        </div>
        
        <div class="card-body border-bottom pt-4">
            <form method="GET" action="{{ route('komoditas.index') }}" class="d-flex justify-content-between align-items-center row gap-3 gap-md-0">
                <div class="col-md-auto">
                    <div class="d-flex align-items-center">
                        <label class="me-2 text-nowrap">Show</label>
                        <select name="per_page" class="form-select form-select-sm w-auto" onchange="this.form.submit()">
                            <option value="10" {{ request('per_page') == 10 ? 'selected' : '' }}>10</option>
                            <option value="25" {{ request('per_page') == 25 ? 'selected' : '' }}>25</option>
                            <option value="50" {{ request('per_page') == 50 ? 'selected' : '' }}>50</option>
                        </select>
                        <label class="ms-2 text-nowrap">entries</label>
                    </div>
                </div>
                <div class="col-md-auto d-flex gap-2">
                    <div class="input-group input-group-sm w-auto">
                        <input type="text" name="search" class="form-control" placeholder="Cari Nama Komoditas..." value="{{ request('search') }}">
                        <button type="submit" class="btn btn-outline-primary"><i class="ti tabler-search"></i></button>
                    </div>
                    <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="offcanvas" data-bs-target="#offcanvasAddKomoditas">
                        <i class="ti tabler-plus me-1"></i> Tambah
                    </button>
                </div>
            </form>
        </div>

        <div class="table-responsive text-nowrap">
            <table class="table table-hover">
                <thead class="border-top">
                    <tr>
                        <th>No</th>
                        <th>Nama Komoditas</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($komoditas as $index => $item)
                        <tr>
                            <td>{{ $komoditas->firstItem() + $index }}</td> 
                            <td><span class="text-heading fw-medium">{{ $item->nama }}</span></td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <a href="javascript:;" class="btn btn-icon btn-text-secondary rounded-pill edit-record" data-id="{{ $item->id }}"><i class="ti tabler-edit ti-md"></i></a>
                                    <a href="javascript:;" class="btn btn-icon btn-text-secondary rounded-pill delete-record" data-id="{{ $item->id }}" data-nama="{{ $item->nama }}"><i class="ti tabler-trash ti-md"></i></a>
                                    <a href="javascript:;" class="btn btn-icon btn-text-secondary rounded-pill view-record" data-id="{{ $item->id }}"><i class="ti tabler-eye ti-md"></i></a>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="3" class="text-center py-4">Tidak ada data komoditas ditemukan.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <div class="card-footer d-flex justify-content-center justify-content-md-end border-top">
            {{ $komoditas->appends(request()->query())->links('pagination::bootstrap-5') }}
        </div>
    </div>

    @include('master.komoditas.add')
    @include('master.komoditas.edit')
    @include('master.komoditas.view')
</div>
@endsection

@push('scripts')
<script>
    'use strict';
    const csrfToken = "{{ csrf_token() }}";

    $(document).ready(function () {
        
        const addForm = document.getElementById('addKomoditasForm');
        const offcanvasAdd = new bootstrap.Offcanvas(document.getElementById('offcanvasAddKomoditas'));
        
        let fvAdd = FormValidation.formValidation(addForm, {
            fields: { nama: { validators: { notEmpty: { message: 'Nama komoditas wajib diisi' } } } },
            plugins: {
                trigger: new FormValidation.plugins.Trigger(),
                bootstrap5: new FormValidation.plugins.Bootstrap5({ eleValidClass: '', rowSelector: '.form-control-validation' }),
                submitButton: new FormValidation.plugins.SubmitButton(),
            }
        }).on('core.form.valid', function () {
            let formData = $(addForm).serialize();
            $.ajax({
                url: addForm.action,
                type: 'POST',
                data: formData,
                success: function (res) {
                    offcanvasAdd.hide();
                    addForm.reset();
                    fvAdd.resetForm();
                    Swal.fire({ icon: 'success', title: 'Berhasil!', text: res.message, timer: 1500, showConfirmButton: false })
                        .then(() => window.location.reload());
                },
                error: function (xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors || {};
                        Object.keys(errors).forEach(key => {
                            fvAdd.updateFieldStatus(key, 'Invalid', 'notEmpty');
                            const fieldRow = addForm.querySelector(`[name="${key}"]`).closest('.form-control-validation');
                            const messageContainer = fieldRow.querySelector('.fv-plugins-message-container');
                            if (messageContainer) messageContainer.innerHTML = `<div class="fv-help-block text-danger">${errors[key][0]}</div>`;
                        });
                    } else {
                        Swal.fire({ icon: 'error', title: 'Gagal!', text: xhr.responseJSON?.message || 'Error sistem' });
                    }
                }
            });
        });

        const offcanvasEdit = new bootstrap.Offcanvas(document.getElementById('offcanvasEditKomoditas'));
        $(document).on('click', '.edit-record', function (e) {
            e.preventDefault();
            const id = $(e.currentTarget).data('id');
            const $btn = $(e.currentTarget).addClass('disabled');

            let url = "{{ route('komoditas.show', ':id') }}".replace(':id', id);

            $.get(url, function (res) {
                $btn.removeClass('disabled');
                if (res.status === 'success') {
                    $('#edit-id').val(res.data.id);
                    $('#edit-nama').val(res.data.nama);
                    if (typeof fvEdit !== 'undefined') fvEdit.resetForm();
                    offcanvasEdit.show();
                }
            }).fail((xhr) => { 
                $btn.removeClass('disabled'); 
                console.log(xhr.responseText); 
                Swal.fire('Gagal!', 'Gagal mengambil data edit. Cek console.', 'error'); 
            });
        });

        const offcanvasView = new bootstrap.Offcanvas(document.getElementById('offcanvasViewKomoditas'));
        $(document).on('click', '.view-record', function (e) {
            e.preventDefault();
            const id = $(e.currentTarget).data('id');
            const $btn = $(e.currentTarget).addClass('disabled');

            let url = "{{ route('komoditas.show', ':id') }}".replace(':id', id);

            $.get(url, function (res) {
                $btn.removeClass('disabled');
                if (res.status === 'success') {
                    $('#view-nama').val(res.data.nama);
                    offcanvasView.show();
                }
            }).fail((xhr) => { 
                $btn.removeClass('disabled'); 
                console.log(xhr.responseText);
                Swal.fire('Gagal!', 'Gagal mengambil data view. Cek console.', 'error'); 
            });
        });

        const editForm = document.getElementById('editKomoditasForm');
        let fvEdit = FormValidation.formValidation(editForm, {
            fields: { nama: { validators: { notEmpty: { message: 'Nama komoditas wajib diisi' } } } },
            plugins: {
                trigger: new FormValidation.plugins.Trigger(),
                bootstrap5: new FormValidation.plugins.Bootstrap5({ eleValidClass: '', rowSelector: '.form-control-validation' }),
                submitButton: new FormValidation.plugins.SubmitButton(),
            }
        }).on('core.form.valid', function () {
            const id = $('#edit-id').val();
            let formData = $(editForm).serialize();
            
            let url = "{{ route('komoditas.update', ':id') }}".replace(':id', id);

            $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                success: function (res) {
                    offcanvasEdit.hide();
                    Swal.fire({ icon: 'success', title: 'Updated!', text: res.message, showConfirmButton: false, timer: 1500 })
                        .then(() => window.location.reload());
                },
                error: function (xhr) {
                    if (xhr.status === 422) {
                        const errors = xhr.responseJSON.errors || {};
                        Object.keys(errors).forEach(key => {
                            fvEdit.updateFieldStatus(key, 'Invalid', 'notEmpty');
                            const fieldRow = editForm.querySelector(`[name="${key}"]`).closest('.form-control-validation');
                            const messageContainer = fieldRow.querySelector('.fv-plugins-message-container');
                            if (messageContainer) messageContainer.innerHTML = `<div class="fv-help-block text-danger">${errors[key][0]}</div>`;
                        });
                    } else {
                        Swal.fire({ icon: 'error', title: 'Gagal!', text: xhr.responseJSON?.message || 'Terjadi kesalahan' });
                    }
                }
            });
        });

        $(document).on('click', '.delete-record', function (e) {
            e.preventDefault();
            const id = $(e.currentTarget).data('id');
            const name = $(e.currentTarget).data('nama');
            
            let url = "{{ route('komoditas.destroy', ':id') }}".replace(':id', id);

            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: `Komoditas "${name}" akan dihapus.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Ya, Hapus!',
                customClass: { confirmButton: 'btn btn-primary me-3', cancelButton: 'btn btn-label-secondary' },
                buttonsStyling: false
            }).then(function (result) {
                if (result.value) {
                    $.ajax({
                        url: url,
                        type: 'DELETE',
                        headers: { 'X-CSRF-TOKEN': csrfToken },
                        success: function (res) {
                            Swal.fire({ icon: 'success', title: 'Terhapus!', text: res.message, showConfirmButton: false, timer: 1500 })
                                .then(() => window.location.reload());
                        },
                        error: () => Swal.fire({ icon: 'error', title: 'Gagal!', text: 'Terjadi kesalahan sistem.' })
                    });
                }
            });
        });
    });
</script>
@endpush