<?php

namespace Core;

class Cookie
{
    /**
     * Sets a cookie.
     *
     * @param string $key The cookie name.
     * @param mixed $value The cookie value.
     * @param int $expiry The expiration time in seconds (e.g., time() + 3600).
     * @param string $path The path on the server where the cookie will be available.
     * @param string $domain The domain that the cookie is available to.
     * @param bool $secure Indicates that the cookie should only be transmitted over a secure HTTPS connection.
     * @param bool $httponly When true, the cookie will be made accessible only through the HTTP protocol.
     * @return bool True on success, false on failure.
     */
    public static function set(string $key, $value, int $expiry = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httponly = true): bool
    {
        return setcookie($key, $value, [
            'expires' => $expiry,
            'path' => $path,
            'domain' => $domain,
            'secure' => $secure,
            'httponly' => $httponly,
            'samesite' => 'Lax'
        ]);
    }

    /**
     * Retrieves a cookie value.
     *
     * @param string $key The cookie name.
     * @param mixed $default The default value to return if the cookie doesn't exist.
     * @return mixed The cookie value or the default value.
     */
    public static function get(string $key, $default = null)
    {
        return $_COOKIE[$key] ?? $default;
    }

    /**
     * Checks if a cookie exists.
     *
     * @param string $key The cookie name.
     * @return bool True if the cookie exists, false otherwise.
     */
    public static function has(string $key): bool
    {
        return isset($_COOKIE[$key]);
    }

    /**
     * Destroys a cookie.
     *
     * @param string $key The cookie name.
     * @param string $path The path of the cookie to destroy.
     * @param string $domain The domain of the cookie to destroy.
     * @return bool True on success, false on failure.
     */
    public static function destroy(string $key, string $path = '/', string $domain = ''): bool
    {
        // Set the expiration to a time in the past to delete the cookie
        return setcookie($key, '', time() - 3600, $path, $domain);
    }
}
