<?php

helper('app');

use App\Models\Mobile\UserModel;
use Firebase\JWT\JWT;

function setMPassword($password)
{
    $config         = new \Config\Encryption();
    $config->key = options('MOBILEPASSKEY');
    $encrypter = \Config\Services::encrypter($config);
    return $encrypter->encrypt($password);
}

function verifMPassword($plain_password, $password_hash)
{
    return MPdecrypt($password_hash) == $plain_password;
}

function MPdecrypt($hash)
{
    $config = new \Config\Encryption();
    $config->key = options('MOBILEPASSKEY');
    $encrypter = \Config\Services::encrypter($config);
    try {
        return $encrypter->decrypt($hash);
    } catch (\Throwable $th) {
        return false;
    }
}
if (!function_exists('logged_in')) {
    /**
     * Checks to see if the user is logged in.
     *
     * @return bool
     */
    function logged_in()
    {
        if (isset($GLOBALS['mobile_user'])) {
            return $GLOBALS['mobile_user'];
        }
        helper('cookie');
        try {
            $cn = MOBILECN();
            $c = get_cookie($cn);
            $decoded = JWT::decode($c, options('MOBILEJWTKEY'), array('HS256'));
            $sessout = options('mobile_session_timeout');
            $sessunit = options('mobile_session_unit');
            if ($decoded->iat < strtotime("-$sessout $sessunit")) {
                setcookie($cn, '', time() - 3600, '/'); // empty value and old timestamp
                return false;
            }
            $user = (new UserModel())->findId($decoded->user_id);
            if (!$user) return false;
            $GLOBALS['mobile_user'] = $user;
            return $user;
        } catch (\Throwable $th) {
            return false;
        }
    }
}
if (!function_exists('MOBILECN')) {
    function MOBILECN()
    {

        $cn = options('MOBILECN');
        if (get_cookie("rwno$cn")) $cn = "rwno$cn";
        return $cn;
    }
}
if (!function_exists('user')) {
    /**
     * Get user data
     *
     * @return object
     */

    function user()
    {
        if (!logged_in()) return null;
        return $GLOBALS['mobile_user'];
    }
}
