<?php
/**
 * Social Login Cookie storage
 *
 * @package um_ext\um_social_login\core\Social_Login_Cookie
 */

namespace um_ext\um_social_login\core;

use \Hybridauth\Storage\StorageInterface;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Social_Login_Cookie
 *
 * @package um_ext\um_social_login\core
 */
class Social_Login_Cookie implements StorageInterface {
	/**
	 * Namespace
	 *
	 * @var string
	 */
	protected $store_namespace = 'UM_SSO_STORAGE';

	/**
	 * Key prefix
	 *
	 * @var string
	 */
	protected $key_prefix = '';

	/**
	 * Initiate a new session
	 */
	public function __construct() {

		if ( ini_get( 'session.use_cookies' ) ) {
			return;
		}
	}

	/**
	 * Get cookie
	 *
	 * @param string $key Cookie Key.
	 */
	public function get( $key ) {
		$key = $this->key_prefix . strtolower( $key );
		return isset( $_COOKIE[ $this->store_namespace ][ $key ] ) ? $_COOKIE[ $this->store_namespace ][ $key ] : null; //phpcs:ignore

	}

	/**
	 * Set cookie
	 *
	 * @param string $key Cookie Key.
	 * @param string $value Cookie Value.
	 */
	public function set( $key, $value ) {

		$key = $this->key_prefix . strtolower( $key );

		setcookie( "{$this->store_namespace}[{$key}]", $value, time() + 3600, COOKIEPATH, COOKIE_DOMAIN );

	}

	/**
	 *  Clear Cookie
	 */
	public function clear() {
		setcookie( $this->store_namespace, '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN );
	}

	/**
	 *  Delete Cookie
	 *
	 * @param string $key Cookie Key.
	 */
	public function delete( $key ) {
		$key = $this->key_prefix . strtolower( $key );
		setcookie( "{$this->store_namespace}[{$key}]", '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN );
	}

	/**
	 *  Delete Match Cookie
	 *
	 * @param string $key Cookie Key.
	 * @param string $cv  Cookie Value to match.
	 */
	public function deleteMatch( $key, $cv = '' ) {
		$key = $this->key_prefix . strtolower( $key );

		if ( isset( $_COOKIE['UM_SSO_STORAGE'] ) ) {
			foreach ( $_COOKIE['UM_SSO_STORAGE'] as $k => $v ) { //phpcs:ignore
				if ( strpos( $k, $key ) > -1 && $v === $cv ) {
					setcookie( "{$this->store_namespace}[{$k}]", '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN );
				}
			}
		}

	}
}
