@extends('layout.main')

@section('content')
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">
        <div class="card-body border-bottom">
            <form method="GET" action="{{ route('provinsi.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="Search Provinsi..." 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 add-new" data-bs-toggle="offcanvas" data-bs-target="#offcanvasAddProvinsi">
                        <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>Kode Provinsi</th>
                        <th>Nama Provinsi</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($provinsi as $index => $prov)
                        <tr>
                            <td>{{ $provinsi->firstItem() + $index }}</td> 
                            <td><span class="text-heading">{{ $prov->kode }}</span></td>
                            <td>
                                @php
                                    $words = explode(' ', $prov->nama);
                                    $initials = substr(implode('', array_map(fn($w) => strtoupper($w[0]), $words)), 0, 2);
                                    $states = ['success', 'danger', 'warning', 'info', 'primary', 'secondary'];
                                    $state = $states[array_rand($states)];
                                @endphp
                                <div class="d-flex justify-content-start align-items-center">
                                    <div class="avatar-wrapper me-3">
                                        <div class="avatar avatar-sm">
                                            <span class="avatar-initial rounded-circle bg-label-{{ $state }}">{{ $initials }}</span>
                                        </div>
                                    </div>
                                    <div class="d-flex flex-column">
                                        <span class="fw-medium text-heading">{{ $prov->nama }}</span>
                                        <small class="text-muted">{{ $prov->iso ?? '' }}</small>
                                    </div>
                                </div>
                            </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="{{ $prov->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="{{ $prov->id }}" data-nama="{{ $prov->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="{{ $prov->id }}"><i class="ti tabler-eye ti-md"></i></a>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="4" class="text-center py-4">Tidak ada data ditemukan.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <div class="card-footer d-flex justify-content-center justify-content-md-end border-top">
            {{ $provinsi->appends(request()->query())->links('pagination::bootstrap-5') }}
        </div>
    </div>
    @include('master.provinsi.add')
    @include('master.provinsi.view')
    @include('master.provinsi.edit')
</div>
@endsection

@push('scripts')
<script>
    'use strict';

    const csrfToken = "{{ csrf_token() }}";

    $(document).ready(function () {
        
        $.validator.setDefaults({
            errorElement: 'div',
            errorPlacement: function (error, element) {
                error.addClass('invalid-feedback');
                element.closest('.mb-6, .form-control-validation').append(error);
            },
            highlight: function (element) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function (element) {
                $(element).removeClass('is-invalid');
            }
        });

        const offcanvasAdd = new bootstrap.Offcanvas(document.getElementById('offcanvasAddProvinsi'));
        $('#addNewProvinsiForm').validate({
            rules: {
                kode: { required: true, minlength: 2, maxlength: 2 },
                nama: { required: true },
                iso: { required: true }
            },
            messages: {
                kode: { required: "Kode wajib diisi", minlength: "Harus 2 digit", maxlength: "Maksimal 2 digit" },
                nama: { required: "Nama provinsi wajib diisi" },
                iso: { required: "ISO wajib diisi" }
            },
            submitHandler: function (form) {
                $.ajax({
                    url: $(form).attr('action'),
                    type: 'POST',
                    data: $(form).serialize(),
                    success: function () {
                        offcanvasAdd.hide();
                        form.reset();
                        Swal.fire({ icon: 'success', title: 'Berhasil!', showConfirmButton: false, timer: 1500 })
                            .then(() => window.location.reload());
                    },
                    error: function (xhr) {
                        Swal.fire({ icon: 'error', title: 'Gagal!', text: xhr.responseJSON?.message || 'Error' });
                    }
                });
            }
        });

        const offcanvasView = new bootstrap.Offcanvas(document.getElementById('offcanvasViewProvinsi'));
        const offcanvasEdit = new bootstrap.Offcanvas(document.getElementById('offcanvasEditProvinsi'));

        $(document).on('click', '.view-record', function () {
            const id = $(this).data('id');
            $.get(`/provinsi/${id}`, function (res) {
                if (res.status === 'success') {
                    $('#view-provinsi-code').val(res.data.kode);
                    $('#view-provinsi-name').val(res.data.nama);
                    $('#view-provinsi-path').val(res.data.path);
                    $('#view-provinsi-iso').val(res.data.iso);
                    offcanvasView.show();
                }
            });
        });

        $(document).on('click', '.edit-record', function () {
            const id = $(this).data('id');
            
            const editForm = $('#editProvinsiForm');
            editForm.validate().resetForm();
            editForm.find('.is-invalid').removeClass('is-invalid');

            $.get(`/provinsi/${id}`, function (res) {
                if (res.status === 'success') {
                    $('#edit-provinsi-id').val(res.data.id);
                    $('#edit-provinsi-code').val(res.data.kode);
                    $('#edit-provinsi-name').val(res.data.nama);
                    $('#edit-provinsi-path').val(res.data.path);
                    $('#edit-provinsi-iso').val(res.data.iso);
                    offcanvasEdit.show();
                }
            });
        });

        $('#editProvinsiForm').validate({
            rules: {
                kode: { required: true, minlength: 2, maxlength: 2 },
                nama: { required: true },
                iso: { required: true }
            },
            messages: {
                kode: { required: "Kode wajib diisi", minlength: "Harus 2 digit", maxlength: "Maksimal 2 digit" },
                nama: { required: "Nama provinsi wajib diisi" },
                iso: { required: "ISO wajib diisi" }
            },
            submitHandler: function (form) {
                const id = $('#edit-provinsi-id').val();
                $.ajax({
                    url: `/provinsi/${id}`,
                    type: 'PUT',
                    data: $(form).serialize(),
                    headers: { 'X-CSRF-TOKEN': csrfToken },
                    success: function () {
                        offcanvasEdit.hide();
                        Swal.fire({ icon: 'success', title: 'Updated!', showConfirmButton: false, timer: 1500 })
                            .then(() => window.location.reload());
                    },
                    error: function(xhr) {
                        Swal.fire({ icon: 'error', title: 'Gagal!', text: xhr.responseJSON?.message || 'Gagal update data' });
                    }
                });
            }
        });

        $(document).on('click', '.delete-record', function () {
            const id = $(this).data('id');
            const name = $(this).data('nama');

            Swal.fire({
                title: 'Hapus?',
                text: `Provinsi ${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: `/provinsi/${id}`,
                        type: 'DELETE',
                        headers: { 'X-CSRF-TOKEN': csrfToken },
                        success: function () {
                            Swal.fire({ icon: 'success', title: 'Terhapus!', showConfirmButton: false, timer: 1500 })
                                .then(() => window.location.reload());
                        }
                    });
                }
            });
        });
    });
</script>
@endpush