<?php

namespace App\Http\Controllers;

use App\Http\Requests\auth_user;
use App\Http\Requests\reg_user;
use App\Models\User;
use App\Models\Subscriber;
use App\Models\Trafic;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function reg(reg_user $request)
    {
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => $request->password,
            'role' => $request->role,
        ]);
        
        Auth::login($user);

        function generateNumber(){
            $numbergen = '';
            for ($i = 0; $i < 9; $i++){
                $numbergen .= mt_rand(0, 9);
            }
            return '79' . $numbergen;
        }
        $number_phone = generateNumber();
        
        Subscriber::create([
            'number_phone' => $number_phone,
            'user_id' => Auth::user()->id,
            'trafic_id' => 1,
        ]);

        return redirect()->route('welcome');
    }

    public function auth(auth_user $request)
    {
        if (Auth::attempt(['email' => $request->email,  'password' => $request->password])) {
            return redirect()->route('welcome');
        }
        else {
            return redirect()->route('login')->withErrors([
                'password' => 'Incorrect password',
            ]);
        }
    }

    public function cabinet(Trafic $trafic){
        $id = Auth::id();
        $subscriber = Subscriber::where('user_id', $id)->first();
        return view('cabinet', ['subscriber' => $subscriber, 'trafic' => $trafic]);
    }

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

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

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