<?php

namespace App\Livewire\Admin\User;

use Livewire\Component;
use App\Models\Admin\User;
use Livewire\Attributes\Computed;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Auth;

class EditUserForm extends Component
{
    public User $user;
    public $name;
    public $email;
    public $role;

    public $password;

    

    public function mount(User $user)
    {
        $this->user = $user;
        $this->name = $user->name;
        $this->email = $user->email;
        $this->role = $user->roles->first()->name;
       
    }

    #[Computed()]
    public function countries()
    {
        return DB::table('countries')->get();
    }

    #[Computed()]
    public function cities()
    {
        return DB::table('cities')->where('country_id', $this->country_id)->orderBy('name', 'asc')->get();
    }

    public function updatedCountryId($value)
    {
        $this->city_id = null;

        $this->cities = DB::table('cities')->where('country_id', $value)->orderBy('name', 'asc')->get();
    }


    #[Computed()]
    public function roles()
    {
        $currentUser = Auth::user();

        $rolesQuery = Role::where('name', '<>', 'super-admin');

        if (!$currentUser->hasRole('admin') && !$currentUser->hasRole('super-admin')) {
            $rolesQuery->where('name', '<>', 'admin');
        }

        $allowedRoles = $rolesQuery->get();

        return $allowedRoles;
    }

    public function save()
    {
        $this->validate([
            'name' => 'required|min:2',
            'email' => 'required|email|unique:users,email,' . $this->user->id,
            'role' => 'required|exists:roles,name',
            'password' => 'nullable|min:8',
        ]);

        $this->user->update([
            'name' => $this->name,
            'email' => $this->email,
        ]);

        if (!empty($this->password)) {
            $this->user->update([
                'password' => bcrypt($this->password),
            ]);
        }

        $this->user->syncRoles($this->role);

        activity()->performedOn($this->user)->causedBy(auth()->id())->log('Kullanıcı güncellendi');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Kullanıcı başarıyla güncellendi.', 'icon' => 'success'
        ]);
    }

    public function render()
    {
        if ($this->user->hasRole('super-admin') && !auth()->user()->hasRole('super-admin')) {
            abort(403);
        }

        return view('livewire.admin.user.edit-user-form');
    }
}