<?php

namespace App\Livewire\Admin;

use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

#[Layout('layouts.admin')]
#[Title('Role & Akses')]
class RolePermission extends Component
{
    public string $selectedRole = 'admin';
    public array  $selectedPermissions = [];

    // Grouping label permission
    private array $groupLabels = [
        'order'    => 'Pesanan',
        'payment'  => 'Pembayaran',
        'product'  => 'Produk',
        'category' => 'Kategori',
        'partner'  => 'Mitra',
        'banner'   => 'Banner',
        'voucher'  => 'Voucher',
        'delivery' => 'Area Ongkir',
        'customer' => 'Customer',
        'report'   => 'Laporan',
        'user'     => 'Pengguna Admin',
        'role'     => 'Role & Akses',
        'setting'  => 'Pengaturan',
        'audit'    => 'Audit Log',
    ];

    public function mount(): void
    {
        $this->loadPermissions();
    }

    public function updatedSelectedRole(): void
    {
        $this->loadPermissions();
    }

    private function loadPermissions(): void
    {
        $role = Role::findByName($this->selectedRole);
        $this->selectedPermissions = $role->permissions->pluck('name')->toArray();
    }

    public function save(): void
    {
        // Super admin tidak bisa diubah
        if ($this->selectedRole === 'super_admin') {
            $this->dispatch('notify', type: 'error', message: 'Permission Super Admin tidak dapat diubah.');
            return;
        }

        $role = Role::findByName($this->selectedRole);
        $role->syncPermissions($this->selectedPermissions);

        // Clear Spatie cache
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        activity('role')
            ->causedBy(auth()->user())
            ->log("Memperbarui permission role: {$this->selectedRole}");

        $this->dispatch('notify', type: 'success', message: 'Permission berhasil disimpan.');
    }

    public function render()
    {
        $allPermissions = Permission::all()->groupBy(function ($p) {
            return explode('.', $p->name)[0];
        });

        $roles = Role::whereNotIn('name', ['customer'])->get();

        return view('livewire.admin.role-permission', [
            'allPermissions' => $allPermissions,
            'groupLabels'    => $this->groupLabels,
            'roles'          => $roles,
        ]);
    }
}
