<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Verify_accounts;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Socialite;
use Route;
use Config;

class AuthController extends Controller
{
    public function login(Request $request) {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            //'remember_me' => 'boolean'
        ]);
        $credentials = request(['email', 'password']);
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString(),
            'userid' => $user->id,
            'role' => $user->role_id,
            'verified' => $user->phone_verified_at,
            'reported' => $user->reported
        ]);
    }

    public function fb(Request $request)
    {
      $params = [
        'grant_type' => 'social',
        'client_id' => '2', // it should be password grant client
        'client_secret' => config('app.secret'),
        'provider' => 'facebook',
        'access_token' => $request->access_token // access token from provider
      ];

      $requestToken = Request::create("/oauth/token", "POST", $params);
      $response = app()->handle($requestToken);
      $json = json_decode($response->content(), true);
      $user = User::where('social_id', $request->social_id) -> first();
      $frontend = json_encode([
        'token_type' => $json['token_type'],
        'expires_at' => $json['expires_in'],
        'access_token' => $json['access_token'],
        'userid' => $user->id,
        'role' => $user->role_id,
        'verified' => $user->phone_verified_at,
        'reported' => $user->reported
      ]);
      return $frontend;
    }

    public function google(Request $request)
    {
      $params = [
        'grant_type' => 'social',
        'client_id' => '2', // it should be password grant client
        'client_secret' => config('app.secret'),
        'provider' => 'google',
        'access_token' => $request->access_token // access token from provider
      ];

      $requestToken = Request::create("/oauth/token", "POST", $params);
      $response = app()->handle($requestToken);
      $json = json_decode($response->content(), true);
      $user = User::where('social_id', $request->social_id) -> first();
      $frontend = json_encode([
        'token_type' => $json['token_type'],
        'expires_at' => $json['expires_in'],
        'access_token' => $json['access_token'],
        'userid' => $user->id,
        'role' => $user->role_id,
        'verified' => $user->phone_verified_at,
        'reported' => $user->reported
      ]);
      return $frontend;
    }

    public function apple(Request $request)
    {
      $params = [
        'grant_type' => 'social',
        'client_id' => '2', // it should be password grant client
        'client_secret' => config('app.secret'),
        'provider' => 'apple',
        'access_token' => $request->access_token // access token from provider
      ];

      $requestToken = Request::create("/oauth/token", "POST", $params);
      $response = app()->handle($requestToken);
      $json = json_decode($response->content(), true);
      $user = User::where('social_id', $request->social_id) -> first();
      $frontend = json_encode([
        'token_type' => $json['token_type'],
        'expires_at' => $json['expires_in'],
        'access_token' => $json['access_token'],
        'userid' => $user->id,
        'role' => $user->role_id,
        'verified' => $user->phone_verified_at,
        'reported' => $user->reported
      ]);
      return $frontend;
    }


    public function register(Request $request)
    {
        $rules = [
            'name' => 'required|string|regex:/(^[a-zA-Z\s ÑñÁáÉéÍíÓóÚúÜü]+$)+/',
            'email' => 'required|string|email|unique:users',
            'phone' => 'required|numeric',
            'password' => 'required|string',
            'secret' => 'required|string'
        ];

        $messages = [
          'email.unique' => 'Correo electronico ya registrado',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);

        if ($validator->fails()) {
          return response()->json([
            'message' => $validator->messages()->first()
          ], 422);
        }

        if ($request->secret == config('app.pass')) {

          /**$verify = new Verify_accounts;
          $verify->name = $request->name;
          $verify->email = $request->email;
          $verify->password = bcrypt($request->password);
          $verify->token = str_random(70);

          $verify->save(); */

          $user = new User;
          $user->name = $request->name;
          $user->email = $request->email;
          $user->phone = $request->phone;
          $user->password = bcrypt($request->password);
          $user->role_id = "1";
          $user->save();

          return response()->json([
              'message' => 'Successfully created user!'
          ], 201);
        } else {
        return response()->json([
            'message' => 'Puto el que la hackee'
        ], 201);
        }
    }
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return response()->json([
            'message' => 'Successfully logged out'
        ]);
    }

    /**
     * Get the authenticated User
     *
     * @return [json] user object
     */
    public function user(Request $request)
    {
        return response()->json($request->user());
    }

    public function checkemail($token)
    {
         $verifyUser = Verify_accounts::where('token', $token)->first();
         $user = new User;
         $user->name = $verifyUser->name;
         $user->email = $verifyUser->email;
         $user->password = $verifyUser->password;
         $user->role_id = "1";
         $user->save();
         Verify_accounts::destroy($verifyUser->id);
    }

    public function verify(Request $request)
    {
      $user = $request->user();

      $user->phone = $request->phone;
      $user->phone_verified_at = date("Y-m-d H:i:s");

      $user->save();

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