@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 Users</h5>
        </div>
        
        <div class="card-body border-bottom pt-4">
            <form method="GET" action="{{ route('users.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 / Email..." 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="#offcanvasAddUser">
                        <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>User</th>
                        <th>Role</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($users as $index => $item)
                        <tr>
                            <td>{{ $users->firstItem() + $index }}</td> 
                            <td>
                                @php
                                    $words = explode(' ', $item->name);
                                    $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="text-heading fw-medium">{{ $item->name }}</span>
                                        <small class="text-muted">{{ $item->email }}</small>
                                    </div>
                                </div>
                            </td>
                            <td><span class="badge bg-label-primary">{{ $item->role }}</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->name }}"><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="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">
            {{ $users->appends(request()->query())->links('pagination::bootstrap-5') }}
        </div>
    </div>

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

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

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

    $(document).ready(function () {

        // Fix Bug Select2 Offcanvas
        $('.select2').each(function () {
            var $this = $(this);
            $this.select2({
                dropdownParent: $this.closest('.offcanvas')
            });
        });

        // =======================================================
        // 1. ADD RECORD 
        // =======================================================
        const addForm = document.getElementById('addNewUserForm');
        const offcanvasAdd = new bootstrap.Offcanvas(document.getElementById('offcanvasAddUser'));
        
        let fvAdd;
        if (addForm) {
            fvAdd = FormValidation.formValidation(addForm, {
                fields: {
                    name: { validators: { notEmpty: { message: 'Nama wajib diisi' } } },
                    email: { validators: { notEmpty: { message: 'Email wajib diisi' }, emailAddress: { message: 'Email tidak valid' } } },
                    role: { validators: { notEmpty: { message: 'Role wajib dipilih' } } },
                    password: { validators: { notEmpty: { message: 'Password wajib diisi' }, stringLength: { min: 6, message: 'Minimal 6 karakter' } } }
                },
                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: 'User berhasil ditambahkan', 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' });
                        }
                    }
                });
            });
        }

        // =======================================================
        // 2. EDIT RECORD 
        // =======================================================
        const editForm = document.getElementById('editUserForm');
        const offcanvasEdit = new bootstrap.Offcanvas(document.getElementById('offcanvasEditUser'));
        
        let fvEdit;
        if (editForm) {
            fvEdit = FormValidation.formValidation(editForm, {
                fields: {
                    name: { validators: { notEmpty: { message: 'Nama wajib diisi' } } },
                    email: { validators: { notEmpty: { message: 'Email wajib diisi' }, emailAddress: { message: 'Email tidak valid' } } },
                    role: { validators: { notEmpty: { message: 'Role wajib dipilih' } } },
                    // Password tidak diwajibkan saat edit
                    password: { validators: { stringLength: { min: 6, message: 'Minimal 6 karakter' } } } 
                },
                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-user-id').val();
                $(editForm).find('select').prop('disabled', false);

                $.ajax({
                    url: `/users/${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.' });
                        }
                    }
                });
            });
        }

        // Revalidate Select2
        $('.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);
            }
        });

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

            $.get(`/users/${id}`, function (res) {
                $btn.removeClass('disabled');
                if (res.status === 'success') {
                    const d = res.data;
                    $('#edit-user-id').val(d.id);
                    $('#edit-user-name').val(d.name);
                    $('#edit-user-email').val(d.email);
                    $('#edit-user-role').val(d.role).trigger('change');
                    $('#edit-user-password').val(''); // Kosongkan password input

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

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

            $.get(`/users/${id}`, function (res) {
                $btn.removeClass('disabled');
                if (res.status === 'success') {
                    const d = res.data;
                    $('#view-user-name').val(d.name);
                    $('#view-user-email').val(d.email);
                    $('#view-user-role').val(d.role);
                    offcanvasView.show();
                }
            }).fail(() => { $btn.removeClass('disabled'); Swal.fire('Gagal!', 'Terjadi kesalahan.', 'error'); });
        });

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

            Swal.fire({
                title: 'Apakah Anda yakin?',
                text: `User "${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: `/users/${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