@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 Desa/Kelurahan</h5>
        </div>
        
        <div class="card-body border-bottom pt-4">
            <form method="GET" action="{{ route('desakelurahan.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 Desa/Kel..." 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="#offcanvasAddDesaKelurahan">
                        <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 Desa/Kel</th>
                        <th>Nama Desa/Kelurahan</th>
                        <th>Kecamatan</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($desakelurahan as $index => $desa)
                        <tr>
                            <td>{{ $desakelurahan->firstItem() + $index }}</td> 
                            <td><span class="text-heading fw-medium">{{ $desa->kode }}</span></td>
                            <td>
                                @php
                                    $words = explode(' ', $desa->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">{{ $desa->nama }}</span>
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-label-secondary">{{ $desa->kecamatan->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="{{ $desa->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="{{ $desa->id }}" data-nama="{{ $desa->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="{{ $desa->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">
            {{ $desakelurahan->appends(request()->query())->links('pagination::bootstrap-5') }}
        </div>
    </div>

    @include('master.desakelurahan.add')
    @include('master.desakelurahan.view')
    @include('master.desakelurahan.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');
                if (element.hasClass('select2-hidden-accessible')) {
                    error.insertAfter(element.next('span.select2'));
                } else {
                    element.closest('.mb-6, .form-control-validation').append(error);
                }
            },
            highlight: function (element) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function (element) {
                $(element).removeClass('is-invalid');
            }
        });

        $('.select2').on('change', function() { $(this).valid(); });

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

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

                if (provinsiId) {
                    $.get(`/kabupatenkotabyprovinsi/${provinsiId}`, function (data) {
                        $kabupaten.prop('disabled', false);
                        $.each(data, function (key, val) {
                            $kabupaten.append(`<option value="${val.id}">${val.nama}</option>`);
                        });
                        $kabupaten.trigger('change.select2');
                    });
                }
            });

            $(`#${prefix}-kabupaten`).on('change', function () {
                let kabupatenId = $(this).val();
                let $kecamatan = $(`#${prefix}-kecamatan`);
                let $desa = $(`#${prefix}-desa`);

                $kecamatan.empty().append('<option value="">Pilih Kecamatan</option>').prop('disabled', true).trigger('change.select2');
                $desa.empty().append('<option value="">Pilih Desa/Kelurahan</option>').prop('disabled', true).trigger('change.select2');

                if (kabupatenId) {
                    $.get(`/kecamatanbykabupatenkota/${kabupatenId}`, function (data) {
                        $kecamatan.prop('disabled', false);
                        $.each(data, function (key, val) {
                            $kecamatan.append(`<option value="${val.id}">${val.nama}</option>`);
                        });
                        $kecamatan.trigger('change.select2');
                    });
                }
            });
        }

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

        const offcanvasAdd = new bootstrap.Offcanvas(document.getElementById('offcanvasAddDesaKelurahan'));
        $('#addNewDesaKelurahanForm').validate({
            rules: {
                kecamatan_id: { required: true },
                kode: { required: true, minlength: 10, maxlength: 10, digits: true },
                nama: { required: true }
            },
            messages: {
                kecamatan_id: { required: "Kecamatan wajib dipilih" },
                kode: { required: "Kode wajib diisi", minlength: "Kode harus 10 digit", maxlength: "Kode harus 10 digit", digits: "Hanya angka" },
                nama: { required: "Nama Desa/Kelurahan wajib diisi" }
            },
            submitHandler: function (form, event) {
                event.preventDefault();
                $(form).find('select').prop('disabled', false);
                $.ajax({
                    url: $(form).attr('action'),
                    type: 'POST',
                    data: $(form).serialize(),
                    success: function () {
                        offcanvasAdd.hide();
                        form.reset();
                        $('.select2').val(null).trigger('change');
                        Swal.fire({ icon: 'success', title: 'Berhasil!', text: 'Data disimpan', 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('offcanvasViewDesaKelurahan'));
        $(document).on('click', '.view-record', function () {
            const id = $(this).data('id');
            const $btn = $(this).addClass('disabled');

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

        const offcanvasEdit = new bootstrap.Offcanvas(document.getElementById('offcanvasEditDesaKelurahan'));
        $(document).on('click', '.edit-record', function () {
            const id = $(this).data('id');
            const editForm = $('#editDesaKelurahanForm');
            
            editForm.validate().resetForm();
            editForm.find('.is-invalid').removeClass('is-invalid');

            $.get(`/desakelurahan/${id}`, function (res) {
                if (res.status === 'success') {
                    const d = res.data;
                    $('#edit-desa-id').val(d.id);
                    $('#edit-desa-code').val(d.kode);
                    $('#edit-desa-name').val(d.nama);
                    $('#edit-desa-path').val(d.path);
                    if (d.provinsi_id) {
                        let optionProv = new Option(d.nama_provinsi, d.provinsi_id, true, true);
                        $('#edit-desa-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-desa-kabupaten').append(optionKab).prop('disabled', false).trigger('change');
                    }
                    if (d.kecamatan_id) {
                        let optionKec = new Option(d.nama_kecamatan, d.kecamatan_id, true, true);
                        $('#edit-desa-kecamatan').append(optionKec).prop('disabled', false).trigger('change');
                    }
                    offcanvasEdit.show();
                }
            }).fail(function(xhr) {
                Swal.fire({
                    icon: 'error',
                    title: 'Gagal!',
                    text: 'Terjadi kesalahan saat mengambil data: ' + (xhr.responseJSON?.message || xhr.statusText)
                });
            });
        });

        $('#editDesaKelurahanForm').validate({
            rules: {
                kecamatan_id: { required: true },
                kode: { required: true, minlength: 10, maxlength: 10, digits: true },
                nama: { required: true }
            },
            messages: {
                kecamatan_id: { required: "Kecamatan wajib dipilih" },
                kode: { required: "Kode wajib diisi", minlength: "Kode harus 10 digit", maxlength: "Kode harus 10 digit", digits: "Hanya angka" },
                nama: { required: "Nama Desa/Kelurahan wajib diisi" }
            },
            submitHandler: function (form, event) {
                event.preventDefault();
                const id = $('#edit-desa-id').val();
                $(form).find('select').prop('disabled', false);
                $.ajax({
                    url: `/desakelurahan/${id}`,
                    type: 'PUT',
                    data: $(form).serialize(),
                    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: 'Apakah Anda yakin?',
                text: `Desa/Kelurahan "${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: `/desakelurahan/${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