<?php

/**
 * Class TwoFaModel
 */
class TwoFaModel extends Cf_Model
{
    public const TWO_FA_URL = '/2fa/totp';

    public function getConfiguration()
    {
        return json_decode($this->getRestClient()->get(self::TWO_FA_URL . '/configure'), JSON_OBJECT_AS_ARRAY);
    }

    /**
     * @param $code
     * @return mixed
     *
     * Finishes 2FA configuration by verifying code from the authentication app
     */
    public function verifyConfiguration($code)
    {
        return json_decode(
            $this->getRestClient()->post(self::TWO_FA_URL . '/configure', ['code' => $code]),
            JSON_OBJECT_AS_ARRAY,
        );
    }

    /**
     * @param $code
     * @return array
     *
     * Verifies 2FA code, returns [valid => true|false, message]
     */
    public function verify($code): array
    {
        try {
            $message = $this->getRestClient()->post(self::TWO_FA_URL . '/verify', ['code' => $code]);
            return ['valid' => true, 'message' => $message];
        } catch (HttpClient_InvalidRecord $exception) {
            return ['valid' => false, 'message' => $exception->getMessage()];
        }
    }

    /**
     * @param $code
     * @return mixed
     *
     * Disabled 2FA for the current user
     */
    public function disable($code)
    {
        return json_decode(
            $this->getRestClient()->post(self::TWO_FA_URL . '/disable', ['code' => $code]),
            JSON_OBJECT_AS_ARRAY,
        );
    }

    /**
     * @param $user
     * @param $twoFaCode
     * @return mixed
     *
     * Disables 2FA for any user if the current user has permission.
     */
    public function disableToUser($user)
    {
        return json_decode(
            $this->getRestClient()->post(self::TWO_FA_URL . '/disable/user/' . $user),
            JSON_OBJECT_AS_ARRAY,
        );
    }

    public function mustUserEnable2Fa($user): bool
    {
        $needs2FaEnabled = false;
        $this->load->model(['settings_rest_model', 'ProfileModel']);
        $settings = $this->settings_rest_model->get_app_settings();
        if ($settings['enforce2FA'] === true) {
            $profile = $this->ProfileModel->getProfileData($user);
            $needs2FaEnabled = isset($profile['two_factor_enabled']) && $profile['two_factor_enabled'] === false;
        }
        return $needs2FaEnabled;
    }

    public function unlockUser($user)
    {
        return json_decode($this->getRestClient()->post("/user/$user/unlock"), JSON_OBJECT_AS_ARRAY);
    }
}
