<?php

namespace Modules\TPConnector\Http\Controllers;

use App\BusinessLocation;
use App\User;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Laravel\Passport\Passport;

class TPConnectorAuthApiController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Application|ResponseFactory|JsonResponse|Response
     * @noinspection SpellCheckingInspection
     */
    public function login(Request $request)
    {
        $input = $request->all();
        $validator = Validator::make($request->only(['username']), [
            'username' => ['required'],
        ]);
        if ($validator->fails())
            return response()->json([
                'error' => trans('auth.failed'),
            ], 401);

        /** @var User $user */
        $user = User::query()->where([
            'allow_login' => true,
            'status' => true,
            'username' => $input['username'],
        ])->limit(1)->first();

        if (is_null($user) || !Hash::check($request->post('password'), $user->password)) {
            return response()->json([
                'error' => trans('auth.failed'),
            ], 401);
        } else {
            Passport::tokensExpireIn(now()->addHours(env('TPCONNECTOR_TOKEN_EXPIRY_HOURS', 8)));
            Passport::personalAccessTokensExpireIn(now()->addHours(env('TPCONNECTOR_TOKEN_EXPIRY_HOURS', 8)));
            $token = $user->createToken('Laravel Password Grant Client');
            $locations_id = $user->permitted_locations($user->business_id);
            $locations = $locations_id === 'all' ?
                BusinessLocation::query()->where('is_active', true)->where('business_id', $user->business_id)->get() :
                BusinessLocation::query()->where('is_active', true)->whereIn('id', $locations_id)->get();
            return response([
                'token_type' => 'Bearer',
                'access_token' => $token->accessToken,
                'expires_in' => $token->token->expires_at,
                'user' => [
                    'id' => $user->id,
                    'username' => $user->username,
                    'name' => $user->UserFullName,
                    'role' => $user->custom_field_2,
                    'locations' => $locations->map->only(['id', 'name', 'custom_field1']),
                ]
            ], 200);
        }
    }

    /**
     * Display a listing of the resource.
     * @return Application|Response|ResponseFactory
     */
    public function me(Request $request)
    {
        /** @var User $user */
        $user = $request->user();
        $locations_id = $user->permitted_locations();
        $locations = $locations_id === 'all' ?
            BusinessLocation::query()->where('is_active', true)->where('business_id', $user->business_id)->get() :
            BusinessLocation::query()->where('is_active', true)->whereIn('id', $locations_id)->get();
        return response([
            'id' => $user->id,
            'username' => $user->username,
            'name' => $user->UserFullName,
            'role' => $user->custom_field_2,
            'locations' => $locations->map->only(['id', 'name', 'custom_field1']),
        ], 200);
    }

    /**
     * Display a listing of the resource.
     * @return JsonResponse
     */
    function logout(Request $request)
    {
        $request->user()->token()->revoke();
        return response()->json(['success' => true]);
    }
}
