<?php


namespace App\Http\Controllers\Api\User\Auth;

use App\Models\User;
use App\Constants\Status;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'signup']]);
    }

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

        if ($token = $this->guard()->attempt($credentials)) {
            return $this->respondWithToken($token);
        }

        // return response()->json(['error' => 'Unauthorized'], 401);
        return response()->json(['msg' => 'Failed to Login!', 'cls'=>'error'], 401);
    }

    public function signup(Request $request)
    {
        $general = gs();

        $passwordValidation = Password::min(6);

        $request->validate([
            'email' => 'required|string|email|unique:users',
            'mobile' => 'required|regex:/^([0-9]*)$/|unique:users',
            'password' => ['required','confirmed',$passwordValidation],
            'username' => 'required|unique:users',
        ],
        [
            'username.required' => 'Username must be required!',
            'username.unique' => 'Username already exist!',
            'mobile.required' => 'Mobile number must be required!',
            'mobile.unique' => 'Mobile number already exist!',
        ]
        );


        // $encryptedCode = session()->get('inviteCode');
        $encryptedCode = $request->inviteCode;
        $decodedCode = base64_decode($encryptedCode);

        if (is_numeric($decodedCode)) {
            $referBy = $decodedCode - 50000;
        }else {
            $referBy = null;
        }

        if ($request->inviteCode) {
            if ($referBy) {
                $referUser = User::where('id', $referBy)->first();
                if (!$referUser) {
                    return response()->json(['cls'=>'error', 'msg'=>"Refer not found!"]);
                }
            } else {
                $referUser = null;
                return response()->json(['cls'=>'error', 'msg'=>"Invalid Refer Code!"]);
            }
        }else {
            $referUser = null;
        }

        $user = new User();
        $user->collect_date = Carbon::yesterday();
        $user->email = strtolower(@$request->email ? @$request->email : @$request->username.'@gmail.com');
        $user->password = Hash::make(@$request->password);
        $user->firstname = @$request->firstname ? @$request->firstname : ' ';
        $user->lastname = @$request->lastname ? @$request->lastname : ' ';
        $user->username = @$request->username;
        $user->ref_by = $referUser ? $referUser->id : 0;
        $user->country_code = @$request->country_code ? @$request->country_code : 'BD';
        $user->mobile = @$request->mobile ? @$request->mobile : @$request->username;
        $user->kv = $general->kv ? Status::NO : Status::YES;
        $user->ev = $general->ev ? Status::NO : Status::YES;
        $user->sv = $general->sv ? Status::NO : Status::YES;
        $user->ts = 0;
        $user->tv = 1;
        $user->save();
        return response()->json(['cls'=>'success', 'msg'=>"Sign up Successfull!"]);
    }

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

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

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

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken($this->guard()->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' => $this->guard()->factory()->getTTL() * 60,
            'user' => auth()->user()
        ]);
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\Guard
     */
    public function guard()
    {
        return Auth::guard();
    }
}
