@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 Kecamatan</h5>
        </div>
        
        <div class="card-body border-bottom pt-4">
            <form method="GET" action="{{ route('kecamatan.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 Kecamatan..." 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="#offcanvasAddKecamatan">
                        <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 Kecamatan</th>
                        <th>Nama Kecamatan</th>
                        <th>Kabupaten/Kota</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($kecamatan as $index => $kec)
                        <tr>
                            <td>{{ $kecamatan->firstItem() + $index }}</td> 
                            <td><span class="text-heading fw-medium">{{ $kec->kode }}</span></td>
                            <td>
                                @php
                                    $words = explode(' ', $kec->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>
                                    <span class="text-heading">{{ $kec->nama }}</span>
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-label-secondary">{{ $kec->kabupatenkota->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="{{ $kec->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="{{ $kec->id }}" data-nama="{{ $kec->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="{{ $kec->id }}"><i class="ti tabler-eye ti-md"></i></a>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="5" 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">
            {{ $kecamatan->appends(request()->query())->links('pagination::bootstrap-5') }}
        </div>
    </div>

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

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

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

    $(document).ready(function () {
        
        function setupCascadingDropdown(prefix) {
            $(`#${prefix}-provinsi`).on('change', function () {
                let provinsiId = $(this).val();
                let $kabupaten = $(`#${prefix}-kabupaten`);

                $kabupaten.empty().append('<option value="">Pilih Kabupaten/Kota</option>').prop('disabled', true).trigger('change');

                if (provinsiId) {
                    $.get(`/kabupatenkotabyprovinsi/${provinsiId}`, function (res) {
                        $kabupaten.prop('disabled', false);
                        let dataList = Array.isArray(res) ? res : (res.data || []);
                        $.each(dataList, function (key, val) {
                            $kabupaten.append(`<option value="${val.id}">${val.nama}</option>`);
                        });
                        $kabupaten.trigger('change');
                    });
                }
            });
        }

        setupCascadingDropdown('add-kec');
        setupCascadingDropdown('edit-kec');

        const addForm = document.getElementById('addNewKecamatanForm');
        const offcanvasAdd = new bootstrap.Offcanvas(document.getElementById('offcanvasAddKecamatan'));
        
        let fvAdd;
        if (addForm) {
            fvAdd = FormValidation.formValidation(addForm, {
                fields: {
                    kabupaten_kota_id: { validators: { notEmpty: { message: 'Kabupaten/Kota wajib dipilih' } } },
                    kode: { 
                        validators: { 
                            notEmpty: { message: 'Kode wajib diisi' },
                            stringLength: { min: 6, max: 6, message: 'Kode harus 6 digit' },
                            digits: { message: 'Hanya boleh berisi angka' }
                        } 
                    },
                    nama: { validators: { notEmpty: { message: 'Nama Kecamatan wajib diisi' } } }
                },
                plugins: {
                    trigger: new FormValidation.plugins.Trigger(),
                    bootstrap5: new FormValidation.plugins.Bootstrap5({ eleValidClass: '', rowSelector: '.form-control-validation' }),
                    submitButton: new FormValidation.plugins.SubmitButton(),
                    autoFocus: new FormValidation.plugins.AutoFocus()
                }
            }).on('core.form.valid', function () {
                $(addForm).find('select').prop('disabled', false);
                $.ajax({
                    url: addForm.action,
                    type: 'POST',
                    data: $(addForm).serialize(),
                    success: function () {
                        offcanvasAdd.hide();
                        addForm.reset();
                        fvAdd.resetForm();
                        $('.select2').val(null).trigger('change');
                        Swal.fire({ icon: 'success', title: 'Berhasil!', text: 'Data disimpan', 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' });
                        }
                    }
                });
            });
        }

        const editForm = document.getElementById('editKecamatanForm');
        const offcanvasEdit = new bootstrap.Offcanvas(document.getElementById('offcanvasEditKecamatan'));
        
        let fvEdit;
        if (editForm) {
            fvEdit = FormValidation.formValidation(editForm, {
                fields: {
                    kabupaten_kota_id: { validators: { notEmpty: { message: 'Kabupaten/Kota wajib dipilih' } } },
                    kode: { 
                        validators: { 
                            notEmpty: { message: 'Kode wajib diisi' },
                            stringLength: { min: 6, max: 6, message: 'Kode harus 6 digit' },
                            digits: { message: 'Hanya boleh berisi angka' }
                        } 
                    },
                    nama: { validators: { notEmpty: { message: 'Nama Kecamatan wajib diisi' } } }
                },
                plugins: {
                    trigger: new FormValidation.plugins.Trigger(),
                    bootstrap5: new FormValidation.plugins.Bootstrap5({ eleValidClass: '', rowSelector: '.form-control-validation' }),
                    submitButton: new FormValidation.plugins.SubmitButton(),
                    autoFocus: new FormValidation.plugins.AutoFocus()
                }
            }).on('core.form.valid', function () {
                const id = $('#edit-kecamatan-id').val();
                $(editForm).find('select').prop('disabled', false);

                $.ajax({
                    url: `/kecamatan/${id}`,
                    type: 'PUT',
                    data: $(editForm).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) {
                        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: 'Oops...', text: xhr.responseJSON?.message || 'Terjadi kesalahan.' });
                        }
                    }
                });
            });
        }

        $('.select2').on('change', function() {
            const name = $(this).attr('name');
            if (name) {
                if (fvAdd && addForm.querySelector(`[name="${name}"]`)) fvAdd.revalidateField(name);
                if (fvEdit && editForm.querySelector(`[name="${name}"]`)) fvEdit.revalidateField(name);
            }
        });

        $(document).on('click', '.edit-record', function () {
            const id = $(this).data('id');
            const $btn = $(this).addClass('disabled');

            $.get(`/kecamatan/${id}`, function (res) {
                $btn.removeClass('disabled');
                if (res.status === 'success') {
                    const d = res.data;
                    $('#edit-kecamatan-id').val(d.id);
                    $('#edit-kec-code').val(d.kode);
                    $('#edit-kec-name').val(d.nama);
                    $('#edit-kec-path').val(d.path);

                    if (d.provinsi_id) {
                        let optionProv = new Option(d.nama_provinsi, d.provinsi_id, true, true);
                        $('#edit-kec-provinsi').append(optionProv).trigger('change');
                    }
                    if (d.kabupaten_kota_id) {
                        let optionKab = new Option(d.nama_kabupaten_kota, d.kabupaten_kota_id, true, true);
                        $('#edit-kec-kabupaten').append(optionKab).prop('disabled', false).trigger('change');
                    }

                    if (fvEdit) fvEdit.resetForm();
                    offcanvasEdit.show();
                }
            }).fail(() => { $btn.removeClass('disabled'); Swal.fire('Gagal!', 'Terjadi kesalahan.', 'error'); });
        });

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

            $.get(`/kecamatan/${id}`, function (res) {
                $btn.removeClass('disabled');
                if (res.status === 'success') {
                    const d = res.data;
                    $('#view-kec-provinsi').val(d.nama_provinsi || '-');
                    $('#view-kec-kabupaten').val(d.nama_kabupaten_kota || '-');
                    $('#view-kec-code').val(d.kode || '-');
                    $('#view-kec-name').val(d.nama || '-');
                    $('#view-kec-path').val(d.path || '-');
                    offcanvasView.show();
                }
            }).fail(() => { $btn.removeClass('disabled'); Swal.fire('Gagal!', 'Terjadi kesalahan.', 'error'); });
        });

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

            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: `Kecamatan "${name}" akan dihapus secara permanen!`,
                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: `/kecamatan/${id}`,
                        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