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

use App\Models\User;
use App\Models\Role;
use Livewire\Component;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class UserController extends Component
{
    public $users;
    public $roles;
    
    // Form properties
    public $userId;
    public $name = '';
    public $email = '';
    public $password = '';
    public $password_confirmation = '';
    public $selectedRoles = [];
    public $editMode = false;
    public $selectedUser;
    
    // Modal state
    public $showUserModal = false;
    public $showViewModal = false;

    protected function rules()
    {
        $rules = [
            'name' => ['required', 'string', 'min:2', 'max:255'],
            'email' => ['required', 'email', Rule::unique('users')->ignore($this->userId)],
            'selectedRoles' => ['required', 'array', 'min:1'],
            'selectedRoles.*' => ['exists:roles,id'],
        ];

        if (!$this->editMode) {
            $rules['password'] = ['required', 'string', 'min:6', 'confirmed'];
        } else {
            $rules['password'] = ['nullable', 'string', 'min:6', 'confirmed'];
        }

        return $rules;
    }

    protected function messages()
    {
        return [
            'name.required' => 'Name is required.',
            'email.required' => 'Email is required.',
            'email.unique' => 'This email is already registered.',
            'password.required' => 'Password is required.',
            'password.min' => 'Password must be at least 6 characters.',
            'password.confirmed' => 'Password confirmation does not match.',
            'selectedRoles.required' => 'Please select at least one role.',
        ];
    }

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

    public function loadUsers()
    {
        $this->users = User::with('roles')->orderBy('name')->get();
    }

    public function loadRoles()
    {
        $this->roles = Role::where('active', true)->orderBy('name')->get();
    }

    public function resetForm()
    {
        $this->reset([
            'userId', 'name', 'email', 'password', 
            'password_confirmation', 'selectedRoles', 'editMode'
        ]);
    }

    public function openCreateModal()
    {
        $this->resetForm();
        $this->editMode = false;
        $this->showUserModal = true;
    }

    public function openEditModal($id)
    {
        $this->edit($id);
        $this->showUserModal = true;
    }

    public function openViewModal($id)
    {
        $this->view($id);
        $this->showViewModal = true;
    }

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

    public function view($id)
    {
        $this->selectedUser = User::with('roles.permissions')->findOrFail($id);
    }

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

        try {
            DB::beginTransaction();
            
            // Create user
            $user = User::create([
                'name' => $this->name,
                'email' => $this->email,
                'password' => Hash::make($this->password),
            ]);

            Log::info('User created:', ['user_id' => $user->id, 'name' => $user->name]);

            // Assign roles using direct DB insert
            if (!empty($this->selectedRoles)) {
                foreach ($this->selectedRoles as $roleId) {
                    // Check if role exists
                    $role = Role::find($roleId);
                    if ($role) {
                        // Insert directly into pivot table
                        DB::table('user_roles')->insert([
                            'user_id' => $user->id,
                            'role_id' => $roleId,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                        
                        Log::info('Role assigned:', [
                            'user_id' => $user->id,
                            'role_id' => $roleId,
                            'role_name' => $role->name
                        ]);
                    }
                }
            }

            DB::commit();
            
            // Reload user with roles
            $user->load('roles');
            Log::info('User roles after assignment:', [
                'user_id' => $user->id,
                'roles' => $user->roles->pluck('name')->toArray()
            ]);

            $this->loadUsers();
            $this->closeModal();

            $this->dispatch('show-success', 'User created successfully!');
            
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error creating user: ' . $e->getMessage());
            $this->dispatch('show-error', 'Error creating user: ' . $e->getMessage());
        }
    }

    public function edit($id)
    {
        $user = User::with('roles')->findOrFail($id);
        
        $this->userId = $user->id;
        $this->name = $user->name;
        $this->email = $user->email;
        $this->selectedRoles = $user->roles->pluck('id')->toArray();
        $this->editMode = true;
    }

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

        try {
            DB::beginTransaction();
            
            $user = User::findOrFail($this->userId);
            $user->name = $this->name;
            $user->email = $this->email;
            
            if ($this->password) {
                $user->password = Hash::make($this->password);
            }
            
            $user->save();

            Log::info('User updated:', ['user_id' => $user->id]);

            // Sync roles - Remove existing and add new
            DB::table('user_roles')->where('user_id', $user->id)->delete();
            
            if (!empty($this->selectedRoles)) {
                foreach ($this->selectedRoles as $roleId) {
                    $role = Role::find($roleId);
                    if ($role) {
                        DB::table('user_roles')->insert([
                            'user_id' => $user->id,
                            'role_id' => $roleId,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                        
                        Log::info('Role assigned during update:', [
                            'user_id' => $user->id,
                            'role_id' => $roleId,
                            'role_name' => $role->name
                        ]);
                    }
                }
            }

            DB::commit();
            
            // Reload user with roles
            $user->load('roles');
            Log::info('User roles after update:', [
                'user_id' => $user->id,
                'roles' => $user->roles->pluck('name')->toArray()
            ]);
            
            $this->loadUsers();
            $this->closeModal();

            $this->dispatch('show-success', 'User updated successfully!');
            
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error updating user: ' . $e->getMessage());
            $this->dispatch('show-error', 'Error updating user: ' . $e->getMessage());
        }
    }

    public function delete($id)
    {
        $user = User::findOrFail($id);
        
        if ($user->id === auth()->id()) {
            $this->dispatch('show-error', 'You cannot delete your own account.');
            return;
        }
        
        $userName = $user->name;
        
        // Remove role assignments first
        DB::table('user_roles')->where('user_id', $user->id)->delete();
        $user->delete();

        $this->loadUsers();
        
        $this->dispatch('show-success', "User '{$userName}' deleted successfully!");
    }

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