<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;
use App\Http\Requests\authUserRequest;
use App\Http\Requests\create_user_request;
use App\Models\User;
use App\Models\Abonent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function candidates(){
        $users = User::where('role', 'user')->get();
        return view('candidates', ['users' => $users]);
    }

    public function employers(){
        $users = User::where('role', 'employer')->get();
        return view('employers', ['users' => $users]);
    }

    public function user($user){
        $user = User::find($user);
        if($user->id != 1 || Auth::user()->role == 'admin'){ 
            return view('user', ['user' => $user]);
        }
        else
        {
            return redirect()->route('index', $user);
        }
        
    }

    public function edit_user($user){
        $user = User::find($user);
        return view('user', ['user' => $user]);
    }

    public function edituser(User $user, Request $request){
        $user->name = $request->nameEdit;
        $user->email = $request->emailEdit;
        $user->comment = $request->commentEdit;
        if($request->avatar)
        {
            $user->avatar = Storage::disk('public')->put('avatars', $request->file('avatar'));
        }
        $user->save();
        return redirect()->route('user', $user->id);
    }

    public function reg(create_user_request $request)
    {
        $user = new User();
        $user->name = $request->nameReg;
        $user->email = $request->emailReg;
        $user->password = $request->passReg;
        $user->avatar = Storage::disk('public')->put('avatars', $request->file('avatar'));
        $user->role = $request->role;
        $user->save();
        Auth::login($user);
        return redirect()->route('index');
    }

    public function auth(authUserRequest $request)
    {
        if (Auth::attempt(['email' => $request->email,  'password' => $request->password])) {
            // $request->session()->regenerate();
            return redirect()->route('index');
            // return redirect()->intended('dashboard');
        }
        else {
            return redirect()->route('login')->withErrors([
                'password' => 'Неверный пароль',
            ]);
        }
    }

    public function login() {
        return view('login');
    }

    public function register(){
        return view('login');
    }

    public function logout(User $user) {
        Auth::logout($user);
        return redirect()->route('index');
    }
}
