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

use Fortytwo\Wordpress\Plugin\TwoFactorAuthentication\Value\TrustedStateValue;

/**
 * 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 int $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 int $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 int $userId User Id.
     */
    public function collection($userId)
    {
        return get_user_meta($userId, self::TRUSTED_DEVICE_KEY);
    }

    /**
     * Check if the device is trusted
     *
     * @param int @userId User ID
     *
     * @return bool true if the device is trusted or not if is not.
     */
    public function isTrustedDevice($userId)
    {
        $trustedValue = new TrustedStateValue();

        if ($trustedValue->isActive()) {
            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;
                }
            }
        }

        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();
    }
}
