<?php
namespace SabaiApps\Directories\Component\System\Helper;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Request;

/**
 * CookieHelper provides methods to set and get cookies with application-specific naming.
 */
class CookieHelper {

	/**
	 * Sets or gets a cookie value.
	 *
	 * @param Application $application
	 * @param string      $name
	 * @param string|null $value
	 * @param int         $expire
	 * @param bool        $httpOnly
	 * @return bool|string|null
	 */
	public function help( Application $application, $name, $value = null, $expire = 0, $httpOnly = false ) {
		$name = $this->name( $application, $name );
		if ( isset( $value ) ) {
			if ( ! setcookie( $name, $value, $expire, $path = $application->getPlatform()->getCookiePath(), $domain = $application->getPlatform()->getCookieDomain(), false, $httpOnly ) ) {
				$application->logError( 'Failed setting cookie ' . $name . ' (Path: ' . $path . ', Domain: ' . $domain . ', Value: ' . $value . ').' );
				return false;
			}
			return true;
		}
		return Request::cookie( $name );
	}

	/**
	 * Returns the cookie name with application-specific hash.
	 *
	 * @param Application $application
	 * @param string      $name
	 * @return string
	 */
	public function name( Application $application, $name ) {
		return $name . '-' . $application->getPlatform()->getCookieHash();
	}
}
