<?php

namespace App\Livewire\Settings;

use Livewire\Component;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesIndex extends Component
{
    public $showCreateModal = false;
    public $showEditModal = false;
    public $editingRoleId = null;
    public $roleName = '';
    public $selectedPermissions = [];

    protected $rules = [
        'roleName' => 'required|string|max:255|unique:roles,name',
    ];

    public function openCreateModal()
    {
        $this->reset(['roleName', 'selectedPermissions']);
        $this->showCreateModal = true;
    }

    public function openEditModal($roleId)
    {
        $role = Role::findOrFail($roleId);
        
        // Prevent editing system roles
        if (in_array($role->name, ['super-admin', 'admin', 'owner', 'accounting', 'purchasing', 'cashier'])) {
            session()->flash('error', __('System roles cannot be edited.'));
            return;
        }

        $this->editingRoleId = $roleId;
        $this->roleName = $role->name;
        $this->selectedPermissions = $role->permissions->pluck('name')->toArray();
        $this->showEditModal = true;
    }

    public function createRole()
    {
        $this->validate();

        $role = Role::create(['name' => $this->roleName]);
        $role->syncPermissions($this->selectedPermissions);

        session()->flash('success', __('Role created successfully.'));
        $this->showCreateModal = false;
        $this->reset(['roleName', 'selectedPermissions']);
    }

    public function updateRole()
    {
        $this->validate([
            'roleName' => 'required|string|max:255|unique:roles,name,' . $this->editingRoleId,
        ]);

        $role = Role::findOrFail($this->editingRoleId);
        $role->update(['name' => $this->roleName]);
        $role->syncPermissions($this->selectedPermissions);

        session()->flash('success', __('Role updated successfully.'));
        $this->showEditModal = false;
        $this->reset(['editingRoleId', 'roleName', 'selectedPermissions']);
    }

    public function deleteRole($roleId)
    {
        $role = Role::findOrFail($roleId);

        // Prevent deleting system roles
        if (in_array($role->name, ['super-admin', 'admin', 'owner', 'accounting', 'purchasing', 'cashier'])) {
            session()->flash('error', __('System roles cannot be deleted.'));
            return;
        }

        // Check if role has users
        if ($role->users()->count() > 0) {
            session()->flash('error', __('Cannot delete role with assigned users.'));
            return;
        }

        $role->delete();
        session()->flash('success', __('Role deleted successfully.'));
    }

    public function render()
    {
        $roles = Role::withCount('users')->get();
        
        // Load permissions grouped by module from config
        $modules = config('permissions.modules', []);
        $permissions = collect();
        
        foreach ($modules as $moduleKey => $module) {
            $modulePermissions = Permission::whereIn('name', array_keys($module['permissions']))->get();
            if ($modulePermissions->isNotEmpty()) {
                $permissions->put($module['label'], $modulePermissions);
            }
        }

        return view('livewire.settings.roles-index', [
            'roles' => $roles,
            'permissions' => $permissions,
        ]);
    }
}
