<?php
// app/Livewire/PermissionsController.php
namespace App\Livewire;

use App\Models\Permission;
use Livewire\Component;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class PermissionsController extends Component
{
    public $permissions = [];
    public $name = '';
    public $slug = '';
    public $category = '';
    public $description = '';
    public $active = true;
    public $editId = null;
    public $showModal = false;
    public $selectedPermission = null;
    public $showViewModal = false;

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

    public function loadPermissions()
    {
        $this->permissions = Permission::orderBy('category')->orderBy('name')->get();
    }

    public function openCreateModal()
    {
        $this->resetForm();
        $this->editId = null;
        $this->showModal = true;
    }

    public function openEditModal($id)
    {
        $perm = Permission::find($id);
        $this->editId = $perm->id;
        $this->name = $perm->name;
        $this->slug = $perm->slug;
        $this->category = $perm->category;
        $this->description = $perm->description;
        $this->active = $perm->active;
        $this->showModal = true;
    }

    public function openViewModal($id)
    {
        $this->selectedPermission = Permission::find($id);
        $this->dispatch('open-view-modal');
    }

    public function closeViewModal()
    {
        $this->selectedPermission = null;
        $this->dispatch('close-view-modal');
    }

    public function closeModal()
    {
        $this->showModal = false;
        $this->resetForm();
    }

    public function resetForm()
    {
        $this->editId = null;
        $this->name = '';
        $this->slug = '';
        $this->category = '';
        $this->description = '';
        $this->active = true;
    }

    public function autoSlug()
    {
        if ($this->name) {
            $this->slug = Str::slug($this->name);
        }
    }

    public function save()
    {
        $rules = [
            'name' => 'required|min:2|max:255',
            'category' => 'required|string|max:100',
            'description' => 'nullable|string',
            'active' => 'boolean',
        ];

        if ($this->editId) {
            $rules['slug'] = ['required', 'alpha_dash', Rule::unique('permissions')->ignore($this->editId)];
        } else {
            $rules['slug'] = ['required', 'alpha_dash', 'unique:permissions,slug'];
        }

        $this->validate($rules);

        if ($this->editId) {
            $perm = Permission::find($this->editId);
            $perm->name = $this->name;
            $perm->slug = $this->slug;
            $perm->category = $this->category;
            $perm->description = $this->description;
            $perm->active = $this->active;
            $perm->save();
            $this->dispatch('showSuccess', 'Permission updated successfully!');
        } else {
            Permission::create([
                'name' => $this->name,
                'slug' => $this->slug,
                'category' => $this->category,
                'description' => $this->description,
                'active' => $this->active,
            ]);
            $this->dispatch('showSuccess', 'Permission created successfully!');
        }

        $this->loadPermissions();
        $this->closeModal();
    }

    public function delete($id)
    {
        $perm = Permission::find($id);
        $permName = $perm->name;
        
        // Check if permission is assigned to any role
        if ($perm->roles()->count() > 0) {
            $this->dispatch('showError', 'Cannot delete permission because it is assigned to roles!');
            return;
        }
        
        $perm->delete();
        $this->loadPermissions();
        $this->dispatch('showSuccess', "Permission '{$permName}' deleted successfully!");
    }

    public function toggleActive($id)
    {
        $perm = Permission::find($id);
        $perm->active = !$perm->active;
        $perm->save();
        $this->loadPermissions();
        $this->dispatch('showSuccess', 'Permission status updated successfully!');
    }

    public function render()
    {
        return view('livewire.permissions-controller');
    }
}