<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\authUserRequest;
use App\Models\User;
use App\Models\Apply;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\create_user_request;
use App\Models\Category;

class UserController extends Controller
{
    public function auth(authUserRequest $request)
    {
        if (Auth::attempt(['login' => $request->login,  'password' => $request->password])) {
            return redirect()->route('index');
        } else {
            return redirect()->route('login')->withErrors([
                'password' => 'Incorrect password',
            ]);
        }
    }

    public function reg(create_user_request $request)
    {
        $user = User::create([
            'fio' =>  $request->fio,
            'login' =>  $request->login,
            'email' => $request->email,
            'number' => $request->number,
            'password' => $request->password,
        ]);
        Auth::login($user);
        return redirect()->route('index');
    }

    public function account()
    {
        $user = Auth::user();
        $aps = Apply::all();
        return view('account', ['aps' => $aps, 'user' => $user]);
    }

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

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

    public function logout()
    {
        Auth::Logout();
        return redirect("/");
    }

    public function categories(Request $request)
    {
        $categories = Category::all();
        if ($request->is('apply')) {
            return view('apply', ['categories' => $categories]);
        } elseif ($request->is('/')) {
            return view('index', ['categories' => $categories]);
        }
    }
}
