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

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

class RolesController extends Component
{
    public $roles = [];
    public $permissions = [];
    public $groupedPermissions = [];
    public $name = '';
    public $slug = '';
    public $description = '';
    public $is_default = false;
    public $active = true;
    public $editId = null;
    public $showModal = false;
    public $selectedRole = null;
    public $selectedPermissions = [];

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

    public function loadRoles()
    {
        // Get roles as plain arrays, not models
        $this->roles = Role::orderBy('name')->get()->map(function($role) {
            return [
                'id' => $role->id,
                'name' => $role->name,
                'slug' => $role->slug,
                'description' => $role->description,
                'is_default' => $role->is_default,
                'active' => $role->active,
                'created_at' => $role->created_at,
                'permissions_count' => DB::table('role_permission')->where('role_id', $role->id)->count()
            ];
        });
    }

    public function loadPermissions()
    {
        $this->permissions = Permission::where('active', true)
            ->orderBy('category')
            ->orderBy('name')
            ->get()
            ->map(function($perm) {
                return [
                    'id' => $perm->id,
                    'name' => $perm->name,
                    'slug' => $perm->slug,
                    'category' => $perm->category,
                    'description' => $perm->description,
                    'active' => $perm->active,
                ];
            });
        $this->groupedPermissions = collect($this->permissions)->groupBy('category');
    }

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

    public function openEditModal($id)
    {
        $role = Role::find($id);
        if ($role) {
            $this->editId = $role->id;
            $this->name = $role->name;
            $this->slug = $role->slug;
            $this->description = $role->description;
            $this->is_default = $role->is_default;
            $this->active = $role->active;
            // Load permissions separately
            $this->selectedPermissions = DB::table('role_permission')
                ->where('role_id', $role->id)
                ->pluck('permission_id')
                ->toArray();
            $this->showModal = true;
        }
    }

    public function openViewModal($id)
    {
        $role = Role::find($id);
        if ($role) {
            $this->selectedRole = [
                'id' => $role->id,
                'name' => $role->name,
                'slug' => $role->slug,
                'description' => $role->description,
                'is_default' => $role->is_default,
                'active' => $role->active,
                'created_at' => $role->created_at,
            ];
            // Load permissions for view modal
            $permissionIds = DB::table('role_permission')
                ->where('role_id', $role->id)
                ->pluck('permission_id')
                ->toArray();
            
            $this->selectedRole['permissions'] = Permission::whereIn('id', $permissionIds)
                ->orderBy('category')
                ->orderBy('name')
                ->get()
                ->map(function($perm) {
                    return [
                        'id' => $perm->id,
                        'name' => $perm->name,
                        'slug' => $perm->slug,
                        'category' => $perm->category,
                    ];
                });
        }
        $this->dispatch('open-view-modal');
    }

    public function closeViewModal()
    {
        $this->selectedRole = 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->description = '';
        $this->is_default = false;
        $this->active = true;
        $this->selectedPermissions = [];
    }

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

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

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

            $this->validate($rules);

            DB::beginTransaction();

            if ($this->editId) {
                $role = Role::find($this->editId);
                if ($role) {
                    $role->name = $this->name;
                    $role->slug = $this->slug;
                    $role->description = $this->description;
                    $role->is_default = $this->is_default;
                    $role->active = $this->active;
                    $role->save();
                    
                    // Sync permissions using DB
                    DB::table('role_permission')
                        ->where('role_id', $role->id)
                        ->delete();
                    
                    foreach ($this->selectedPermissions as $permId) {
                        DB::table('role_permission')->insert([
                            'role_id' => $role->id,
                            'permission_id' => $permId,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }
                }
                
                DB::commit();
                $this->dispatch('showSuccess', 'Role updated successfully!');
            } else {
                $role = Role::create([
                    'name' => $this->name,
                    'slug' => $this->slug,
                    'description' => $this->description,
                    'is_default' => $this->is_default,
                    'active' => $this->active,
                ]);
                
                // Sync permissions
                foreach ($this->selectedPermissions as $permId) {
                    DB::table('role_permission')->insert([
                        'role_id' => $role->id,
                        'permission_id' => $permId,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
                
                DB::commit();
                $this->dispatch('showSuccess', 'Role created successfully!');
            }

            if ($this->is_default && isset($role)) {
                Role::where('id', '!=', $role->id)->update(['is_default' => false]);
            }

            $this->loadRoles();
            $this->closeModal();
            
        } catch (\Illuminate\Validation\ValidationException $e) {
            throw $e;
        } catch (\Exception $e) {
            DB::rollBack();
            $this->dispatch('showError', 'Error: ' . $e->getMessage());
        }
    }

    public function delete($id)
    {
        try {
            $role = Role::find($id);
            
            if (!$role) {
                $this->dispatch('showError', 'Role not found!');
                return;
            }
            
            if ($role->is_default) {
                $this->dispatch('showError', 'Cannot delete the default role!');
                return;
            }
            
            DB::beginTransaction();
            DB::table('role_permission')->where('role_id', $role->id)->delete();
            $role->delete();
            DB::commit();
            
            $this->loadRoles();
            $this->dispatch('showSuccess', 'Role deleted successfully!');
            
        } catch (\Exception $e) {
            DB::rollBack();
            $this->dispatch('showError', 'Error deleting role: ' . $e->getMessage());
        }
    }

    public function toggleActive($id)
    {
        try {
            $role = Role::find($id);
            if ($role) {
                $role->active = !$role->active;
                $role->save();
                $this->loadRoles();
                $this->dispatch('showSuccess', 'Role status updated successfully!');
            }
        } catch (\Exception $e) {
            $this->dispatch('showError', 'Error updating role status: ' . $e->getMessage());
        }
    }

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