<?php

namespace EstatebudConnect\Core;

if (!defined('WPINC')) {
    die();
}

use EstatebudConnect\Traits\Singleton;

class Session
{
    use Singleton;

    const COOKIE_NAME = 'eb_session_id';
    const COOKIE_EXPIRE = 2592000;

    public function start(): string
    {
        if (!isset($_COOKIE[self::COOKIE_NAME])) {
            $session_id = wp_generate_uuid4();
            setcookie(
                self::COOKIE_NAME,
                $session_id,
                time() + self::COOKIE_EXPIRE,
                COOKIEPATH,
                COOKIE_DOMAIN,
                is_ssl(),
                true,
            );
            $_COOKIE[self::COOKIE_NAME] = $session_id;
        }

        return $session_id;
    }

    public function get(): ?string
    {
        $cookie = isset($_COOKIE[self::COOKIE_NAME]) ? sanitize_text_field(wp_unslash($_COOKIE[self::COOKIE_NAME])) : null;
        return $cookie;
    }

    public function exists(): bool
    {
        return isset($_COOKIE[self::COOKIE_NAME]);
    }

    public function destroy(): void
    {
        if ($this->exists()) {
            setcookie(self::COOKIE_NAME, '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
            unset($_COOKIE[self::COOKIE_NAME]);
        }
    }

    public function set(string $session_id): void
    {
        $result = setcookie(
            self::COOKIE_NAME,
            $session_id,
            time() + self::COOKIE_EXPIRE,
            COOKIEPATH,
            COOKIE_DOMAIN,
            is_ssl(),
            true,
        );
        $_COOKIE[self::COOKIE_NAME] = $session_id;
    }
}
