<?php

namespace App\Http\Controllers\Api;

use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;



class AuthController extends Controller
{

    //protected static API_MAIL = 'api.thomas.krummel@gmail.com';
    //protected static API_PASS = 'UF(Q<9knap!ev3vH?5~!b8DP';
    //protected static API_URL = 'https://mein.sterntours.test/api/';


    public $successStatus = 200;


    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);
        }else{
            $token->expires_at = Carbon::now()->addDays(1);
        }

        $token->save();
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString()
        ]);
    }


    public function checked(Request $request)
    {
        return response()->json([
            'message' => 'login'
        ]);
    }

    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 signup(Request $request)
   {
       $request->validate([
           'name' => 'required|string',
           'email' => 'required|string|email|unique:users',
           'password' => 'required|string|confirmed'
       ]);
       $user = new User([
           'name' => $request->name,
           'email' => $request->email,
           'password' => Hash::make($request->password),
       ]);
       $user->save();
       return response()->json([
           'message' => 'Successfully created user!'
       ], 201);
   }*/

}