<?php

namespace App\Services;

use ReallySimpleJWT\Token;

use function _\find;

class AuthService
{
    protected $config;
    protected $request;

    public function __construct(SettingsService $config)
    {
        $this->config = $config;
    }

    public function check($request)
    {
        $folks = $this->config->getFolks();
        $found = find($folks, ['handle' => $request->handle]);
        if ($found) {
            if (password_verify($request->password, $found['password'])) {
                $member = [
                    'handle' => $found['handle'],
                    'email'  => $found['email'],
                    'role'   => $found['role'],
                    'avatar' => $found['avi'],
                    'key'    => $found['key'],
                    'secret' => $found['secret'],
                ];

                $token = Token::create(
                    $found['key'],
                    $found['secret'],
                    time() + 3600,
                    'localhost'
                ); //expires in an hour
                $form_token = md5(uniqid(microtime(), true));
                $request->session()->put('member', $member);
                $request->session()->put('token', $token);
                $request->session()->put('form_token', $form_token);
                return ['status' => true, 'message' => 'HEY WELCOME BACK'];
            //DO SESSION STUFF
            } else {
                return ['status' => false, 'message' => 'CHECK THAT PASSWORD'];
                //RETURN ERROR
            }
        } else {
            return ['status' => false, 'message' => 'CHECK THAT HANDLE'];
        }
    }

    public static function status()
    {
        if (session('member') !== null) {
            if (
                Token::validate(session('token'), session('member')['secret']) &&
                Token::validateExpiration(session('token'), session('member')['secret'])
            ) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}