<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
use Laravolt\Avatar\Avatar;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone' => ['nullable', 'string' ,'min:5','max:11', 'phone:MY'],
            'department' => ['nullable', 'string', 'max:255'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'roles' => ['array', 'exists:roles,id'],
        ]);

        // Log::info("validate ". $data);

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'phone' => $data['phone'],
            'department' => $data['department'],
        ]);

        $avatar = new Avatar();
        $image = $avatar->create($data['name']);
        $destinationPath = public_path('assets/media/avatars/');
        $filename = 'avatar-' . $user->id . '.png';
        $image->save($destinationPath . $filename);

        if (!empty($data['phone'])) {
            $user->phone = $data['phone'];
        }

        if (!empty($data['department'])) {
            $user->department = $data['department'];
        }

        $user->save();

        if (!empty($data['roles'])) {
            $roles = Role::whereIn('id', $data['roles'])->get();
            $user->syncRoles($roles);
        }

        event(new Registered($user));

        $notification = [
            'message' => 'User Created!',
            'alert-type' => 'success'
        ];
        if (auth()->user()->can('user-view')) {
            return redirect()->route('admin.users.index')->with($notification);
        } else {
            return redirect()->route('admin.dashboard')->with($notification);
        }
    }

}
