<?php

class WPML_Cookie {

	public function set_cookie( $name, $value, $expires, $path, $domain, $HTTPOnly  = false, $sameSite = null ) {
		$name  = is_null( $name ) ? '' : rawurlencode( $name );
		$value = is_null( $value ) ? '' : rawurlencode( $value );

		wp_cache_add_non_persistent_groups( __CLASS__ );

		$sameSite = $sameSite ? $sameSite : 'Lax';

		$entryHash = md5( (string) wp_json_encode( [ $name, $value, $path, $domain, $HTTPOnly, $sameSite ] ) );

		if ( wp_cache_get( $name, __CLASS__ ) !== $entryHash ) {
			$this->handle_cache_plugins( $name );
			header(
				'Set-Cookie: ' . $name . '=' . $value
				. ( $domain ? '; Domain=' . $domain : '' )
				. ( $expires ? '; expires=' . gmdate( 'D, d-M-Y H:i:s', $expires ) . ' GMT' : '' )
				. ( $path ? '; Path=' . $path : '' )
				. ( $this->is_secure_connection() ? '; Secure' : '' )
				. ( $HTTPOnly ? '; HttpOnly' : '' )
				. '; SameSite=' . $sameSite,
				false
			);

			wp_cache_set( $name, $entryHash, __CLASS__ );
		}
	}

	public function get_cookie( $name ) {
		if ( isset( $_COOKIE[ $name ] ) ) {
			return $_COOKIE[ $name ];
		}
		return '';
	}

	public function headers_sent() {
		return headers_sent();
	}

	private function handle_cache_plugins( $name ) {
	}

	private function is_secure_connection() {
		if (
			\WPML\FP\Obj::prop( 'HTTPS', $_SERVER ) === 'on' ||
			\WPML\FP\Obj::prop( 'HTTP_X_FORWARDED_PROTO', $_SERVER ) === 'https' ||
			\WPML\FP\Obj::prop( 'HTTP_X_FORWARDED_SSL', $_SERVER ) === 'on'
		) {
			return true;
		}

		return false;
	}
}
