<?php
namespace Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Utils;

/**
 * Manage the trusted device functionality.
 */

class TrustedDevice
{
    // Device Key used for setting the key name
    const TRUSTED_DEVICE_KEY = 'two_factor_authentication_trusted_device';
    // Cookie name
    const TRUSTED_DEVICE_COOKIE_NAME = 'trusted_device_fortytwo';

    /**
     * Add a new device as trusted, setting up a cookie on the machine and
     * adding the id on the meta user.
     *
     * @param integer $userId User Id.
     */
    public function add($userId)
    {
        $deviceId = self::getDeviceId();
        setcookie(self::TRUSTED_DEVICE_COOKIE_NAME, $deviceId, self::getTime(), "/");
        add_user_meta($userId, self::TRUSTED_DEVICE_KEY, $deviceId);
    }

    /**
     * Remove the specified device
     *
     * @param integer $userId User Id.
     * @param string  $deviceId saved Id of the device
     */
    public function remove($userId, $deviceId)
    {
        delete_user_meta($userId, self::TRUSTED_DEVICE_KEY, $deviceId);
    }

    /**
     * Return a list of trusted device
     *
     * @param integer $userId User Id.
     */
    public function collection($userId)
    {
        return get_user_meta($userId, self::TRUSTED_DEVICE_KEY);
    }

    /**
     * Check if the device is trusted
     *
     * @param integer @userId User ID
     *
     * @return boolean true if the device is trusted or not if is not.
     */
    public function isTrustedDevice($userId)
    {
        if (isset($_COOKIE[self::TRUSTED_DEVICE_COOKIE_NAME])) {
            $deviceId = $_COOKIE[self::TRUSTED_DEVICE_COOKIE_NAME];
            $trustedDevices = get_user_meta($userId, self::TRUSTED_DEVICE_KEY);

            if (in_array($deviceId, $trustedDevices)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * Return the timeout for the device
     */
    private function getTime()
    {
        $options = get_option('fortytwo2fa');

        return time() + ($options['trustedDeviceTimeOut'] * 24 * 60 * 60);
    }

    /**
     * Return the autogenerated device ID.
     */
    private function getDeviceId()
    {
        return uniqid();
    }
}
