<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Admin;

use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\PasswordResetController;


use Illuminate\Auth\Passwords\PasswordBrokerManager;
use Illuminate\Support\Facades\Password;
# use Laravel\Lumen\Routing\Controller;
# use Illuminate\Http\Request;

class AuthController extends Controller
{

    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin', ['except' => ['login', 'register', 'ratings', 'generateResetToken']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $request->only(['email', 'password']);

        if (!$token = auth()->guard('admin')->attempt($credentials)) {
            return response()->json(['error' => 'Forbidden'], 403);
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->guard('admin')->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 360
        ]);
    }

    public function register(Request $request)
    {

        $tipologie_selezionate = $request->tipologie_selezionate;

        $check_tipologie = [];
        
        if (count($tipologie_selezionate) > 0) {
            foreach ($tipologie_selezionate as $key => $value) {
                $check_tipologie[$value] = $value;
            }

        }

        $productsEconomy = [];
        $productsPremiumEconomy = [];
        $productsBusiness = [];
        $productsFirstClass = [];

        $cabinClasses = [];

        if (isset( $request->products_economy ) && array_key_exists('Economy', $check_tipologie)) {
            $productsEconomy = $request->products_economy;
            $cabinClasses['Economy']['name'] = 'Economy';
            $cabinClasses['Economy']['products'] = [];
            foreach ($productsEconomy as $k => $v) {
                $cabinClasses['Economy']['products'][] = ['serial_number' => $v['label']]; 
            }
        }
        if (isset( $request->products_premium_economy ) && array_key_exists('Premium Economy', $check_tipologie)) {
            $productsPremiumEconomy = $request->products_premium_economy;
            $cabinClasses['Premium Economy']['name'] = 'Premium Economy';
            $cabinClasses['Premium Economy']['products'] = [];
            foreach ($productsPremiumEconomy as $k => $v) {
                $cabinClasses['Premium Economy']['products'][] = ['serial_number' => $v['label']]; 
            }
        }
        if (isset( $request->products_business ) && array_key_exists('Business', $check_tipologie)) {
            $productsBusiness = $request->products_business;
            $cabinClasses['Business']['name'] = 'Business';
            $cabinClasses['Business']['products'] = [];
            foreach ($productsBusiness as $k => $v) {
                $cabinClasses['Business']['products'][] = ['serial_number' => $v['label']]; 
            }

        }
        if (isset( $request->products_first_class ) && array_key_exists('First Class', $check_tipologie)) {
            $productsFirstClass = $request->products_first_class;
            $cabinClasses['First class']['name'] = 'First class';
            $cabinClasses['First class']['products'] = [];
            foreach ($productsFirstClass as $k => $v) {
                $cabinClasses['First class']['products'][] = ['serial_number' => $v['label']]; 
            }

        }
        $request->cabin_classes = $cabinClasses;
        $request->req_from = 'registration';

        $res = (new UserController)->create($request);

        return response()->json($res, 200);


        // // Controllo email
        // $email = $request->email;

        // $name = $request->name;
        // $surname = $request->surname;

        // // Controllo che non esista la company, nel caso che non esiste, posso anche creare la cartella se le info sono tutte corrette
        // $company_name = $request->company_name;

        // // In base alle tipologie selezionate, se le info generiche sono ok, vado a popolare la tabella products
        // $tipologie_selezionate = $request->tipologie_selezionate;

        // // Controllo password & controllo utente già esistente
        // $username = $request->username;
        

        // $password = $request->password;
        // $password_confirmation = $request->password_confirmation;

        // if ($password != $password_confirmation) {
        //     return response()->json(['status' => false, 'info' => 'Le password non coincidono']);
        // }

        // return response()->json($request);


    }

    // 1. Send reset password email
    public function generateResetToken(Request $request)
    {
        # var_dump($request->email);die();
        // Check email address is valid
        $this->validate($request, ['email' => 'required|email']);

       # var_dump(PasswordReset::create(['email' => 'andreazerbinati@gmail.com', 'token' => 'wedfnwefinefnwefnwoefnwoefn']));die();

        // Send password reset to the user with this email address
        $response = $this->broker()->sendResetLink(
            $request->only('email')
        );

        return $response == Password::RESET_LINK_SENT
            ? response()->json(true)
            : response()->json(false);
    }

    // 2. Reset Password
    public function resetPassword(Request $request)
    {
        // Check input is valid
        $rules = [
            'token'    => 'required',
            'username' => 'required|string',
            'password' => 'required|confirmed|min:6',
        ];
        $this->validate($request, $rules);

        // Reset the password
        $response = $this->broker()->reset(
        $this->credentials($request),
            function ($user, $password) {
                $user->password = app('hash')->make($password);
                $user->save();
            }
        );

        return $response == Password::PASSWORD_RESET
            ? response()->json(true)
            : response()->json(false);
    }

    /**
     * Get the password reset credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(Request $request)
    {
        return $request->only('username', 'password', 'password_confirmation', 'token');
    }

    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        $passwordBrokerManager = new PasswordBrokerManager(app());
        return $passwordBrokerManager->broker();
    }




}
