<?php

    namespace App\Http\Controllers\Api;

    use App\Http\Controllers\Controller;
    use App\Http\Lib\ApiAuthHelper;
    use Illuminate\Http\Request;
    use App\Models\User;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Hash;
    use Illuminate\Support\Facades\Validator;
    use function PHPUnit\Framework\isEmpty;

    class AuthController extends Controller
    {
        use ApiAuthHelper;

        public function checkAuth()
        {
            return response()->json(['auth' => true]);
        }

        public function createUser(Request $request)
        {
            try {
                //Validated
                $validateUser = Validator::make($request->all(),
                    [
                        'name' => 'required|string|max:255',
                        'middle_name' => 'required|string|max:255',
                        'surname' => 'required|string|max:255',
                        'email' => 'required|email|unique:users,email',
                        'phone' => 'required|max:20',

                        'date_of_birth' => 'string',
                        'device' => 'required|max:255|string',
                        'role' => 'required|string|max:255',
                        'password' => 'required|string|min:6'
                    ]);

                if ($validateUser->fails()) {

                    return $this->apiResponse(false, 'Данные введены некорректно: ' . $validateUser->errors()->all()[0], $validateUser->errors()->all()[0], null, null, 401);
                }
            if($request->avatar != '') {
                $exploded = explode(',', $request->avatar);
                $decoded = base64_decode($exploded[1]);
                $exploded = explode('/', $exploded[0]);
                $exploded = explode(';', $exploded[1]);
                $extension = $exploded[0];
                $fileName = base64_encode(now() . rand(0, 1000)) . '.' . $extension;
                $path = public_path('storage/images/') . $fileName;
                file_put_contents($path, $decoded);
            }
                $user = User::create([
                    'name' => $request->name,
                    'middle_name' => $request->middle_name,
                    'surname' => $request->surname,
                    'phone' => $request->phone,
                    'avatar' => $request->avatar != '' ? asset('/storage/images') . '/' . $fileName : asset('images/admin/empty.jpg'),
                    'date_of_birth' => now(),
                    'email' => $request->email,
                    'device' => $request->device,
                    'role' => $request->role,
                    'password' => Hash::make($request->password)
                ]);

                return $this->apiResponse(true, 'User Created Successfully!', null, $user->createToken($request->device, [$request->role]), $user, 200);

            } catch (\Throwable $th) {

                return $this->apiResponse(false, $th->getMessage(), [$th->getFile(), $th->getLine()], null, null, 500);
            }
        }

        public function check()
        {
            return view('auth.login', ['message' => '',]);
        }

        public function loginUser(Request $request)
        {
            try {
                $validateUser = Validator::make($request->all(),
                    [
                        'email' => 'required|email|max:255',
                        'password' => 'required|string|max:255',

                    ]);

                if ($validateUser->fails()) {

                    return $this->apiResponse(false, 'Данные введены некорректно:', $validateUser->errors()->all()[0], null, null, 401);
                }

                if (!Auth::attempt($request->only(['email', 'password']))) {

                    return $this->apiResponse(false, 'Email либо пароль введены неверно.', ['no such user in DB'], null, null, 401);
                }

                $user = User::where('email', $request->email)->first();
                $user->tokens()->delete();

//                if($user->id !== 1 && $user->role == 'admin') {
//
//                    return $this->apiResponse(false, 'You cant\'t be an admin! So sorry ...', ['Try to have to high privileges'], null, 401);
//
//                } elseif ($user->role !== 'individual' && $user->role !== 'entity') {
//
//                    return $this->apiResponse(false, 'No such role', ['Try to have role with does not exist'], null, 401);
//                }

                return $this->apiResponse(true, 'User Login Successfully!',
                    null, $user->createToken(!empty($user->device) ? $user->device : 'API', [$user->role], now()->addDays(1), 200), $user);

            } catch (\Throwable $th) {

                return $this->apiResponse(false, $th->getMessage(), [$th->getFile(), $th->getLine()], null, null, 500);
            }
        }

        public function logoutUser(Request $request)
        {
//            if (!Auth::attempt($request->only(['email', 'password']))) {
//
//                return $this->apiResponse(false, 'Email & Password does not match with our record.', ['no such user in DB'], null, null, 401);
//            }

            $user = User::where('email', $request->email)->first();
            $user->tokens()->delete();
            return $this->apiResponse(true, 'User ' . $user->name . 'was logout! All keys had been cleared', null, null, null, 200);
        }
    }

