<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\User;
use App\Models\Role;
use Illuminate\Support\Facades\Hash;

class AdminUsers extends Component
{
    use WithPagination;

    public $search = '';
    public $sortField = 'id';
    public $sortDirection = 'desc';
    public $editingUser = null;
    public $deletingUser = null;
    public $showEditModal = false;
    public $showDeleteModal = false;
    
    // Editable fields
    public $editName;
    public $editEmail;
    public $editLogin;
    public $editPassword;
    public $editRoles = [];
    public $editAddress;
    public $editPromoCode;
    public $editingUserId = null;
    public $editingComment = '';

    protected $queryString = ['search', 'sortField', 'sortDirection'];
    protected $paginationTheme = 'bootstrap';

    protected $rules = [
        'editName' => 'required|string|max:255',
        'editEmail' => 'required|string|email|max:255',
        'editLogin' => 'required|string|max:255',
        'editPassword' => 'nullable|string|min:8',
        'editRoles' => 'array',
        'editAddress' => 'nullable|string|max:255',
        'editPromoCode' => 'nullable|string|max:255',
        'editingComment' => 'nullable|string|max:1000',
    ];

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }
        $this->sortField = $field;
    }

    public function editUser($userId)
    {
        return redirect()->route('admin.users.edit', $userId);
    }

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

        if ($this->editingUser) {
            $updateData = [
                'name' => $this->editName,
                'email' => $this->editEmail,
                'login' => $this->editLogin,
                'promo_code' => $this->editPromoCode,
            ];

            if ($this->editPassword) {
                $updateData['password'] = Hash::make($this->editPassword);
            }

            $this->editingUser->update($updateData);
            $this->editingUser->roles()->sync($this->editRoles);

            // Update or create address
            if ($this->editAddress) {
                if ($this->editingUser->address) {
                    $this->editingUser->address->update(['address' => $this->editAddress]);
                } else {
                    $this->editingUser->address()->create(['address' => $this->editAddress]);
                }
            } else if ($this->editingUser->address) {
                $this->editingUser->address->delete();
            }

            $this->editingUser->update([
                'comment' => $this->editingComment ? $this->editingComment : null,
            ]);

            session()->flash('message', 'User updated successfully.');
            $this->closeModal();
        }
    }

    public function confirmDelete($userId)
    {
        $this->deletingUser = User::findOrFail($userId);
        $this->showDeleteModal = true;
    }

    public function deleteUser()
    {
        if ($this->deletingUser) {
            $this->deletingUser->delete();
            session()->flash('message', 'User deleted successfully.');
            $this->closeModal();
        }
    }

    public function closeModal()
    {
        $this->showEditModal = false;
        $this->showDeleteModal = false;
        $this->editingUser = null;
        $this->deletingUser = null;
        $this->reset(['editName', 'editEmail', 'editLogin', 'editPassword', 'editRoles', 'editAddress', 'editingComment', 'editPromoCode']);
    }

    public function render()
    {
        if (auth()->user()->hasRole('admin')) {
            $query = User::with('roles')
                ->when($this->search, function ($query) {
                    $query->where(function ($q) {
                        $q->where('name', 'like', '%' . $this->search . '%')
                        ->orWhere('email', 'like', '%' . $this->search . '%')
                        ->orWhere('login', 'like', '%' . $this->search . '%');
                    });
                })
                ->orderBy($this->sortField, $this->sortDirection);
        } else {
            $query = User::with('roles')
            
                ->when($this->search, function ($query) {
                    $query->where(function ($q) {
                        $q->where('name', 'like', '%' . $this->search . '%')
                        ->orWhere('email', 'like', '%' . $this->search . '%')
                        ->orWhere('login', 'like', '%' . $this->search . '%');
                    });
                })
                ->where('manager_id', auth()->user()->id)
                ->orderBy($this->sortField, $this->sortDirection);
        }


        return view('livewire.admin-users', [
            'users' => $query->paginate(10),
            'roles' => Role::all(),
        ]);
    }
} 