<?php

namespace Velis\Session;

use Phalcon\Session\ManagerInterface;
use SessionHandler;

/**
 * Session
 *
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class Session extends SessionHandler implements SessionInterface
{
    protected ManagerInterface $manager;

    /**
     * Constructor
     * @param ManagerInterface $manager
     */
    public function __construct(ManagerInterface $manager)
    {
        $this->manager = $manager;
    }

    /**
     * {@inheritDoc}
     */
    public function start(): bool
    {
        return $this->manager->start();
    }

    /**
     * {@inheritDoc}
     */
    public function exists(): bool
    {
        return $this->manager->exists();
    }

    /**
     * {@inheritDoc}
     */
    public function setId(string $id): void
    {
        $this->manager->setId($id);
    }

    /**
     * {@inheritDoc}
     */
    public function getId(): string
    {
        return $this->manager->getId();
    }

    /**
     * {@inheritDoc}
     */
    public function regenerateId(bool $deleteOldSession = true): SessionInterface
    {
        $this->manager->regenerateId($deleteOldSession);

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function has(string $key): bool
    {
        return $this->manager->has($key);
    }

    /**
     * {@inheritDoc}
     */
    public function set(string $key, mixed $value): void
    {
        $this->manager->set($key, $value);
    }

    /**
     * {@inheritDoc}
     */
    public function get(string $key)
    {
        return $this->manager->get($key);
    }

    /**
     * {@inheritDoc}
     */
    public function remove(string $key): void
    {
        $this->manager->remove($key);
    }

    /**
     * @param string $name
     * @param mixed $value
     */
    public function __set($name, $value)
    {
        $this->manager->set($name, $value);
    }

    public function __get(string $name): mixed
    {
        return $this->manager->get($name);
    }

    /**
     * @param string $name
     * @return bool
     */
    public function __isset($name)
    {
        return $this->manager->has($name);
    }

    /**
     * @param string $name
     */
    public function __unset($name)
    {
        $this->manager->remove($name);
    }

    /**
     * {@inheritDoc}
     */
    public function checkSession(string $sessionId, $userIds = null): bool
    {
        // do nothing - method can be overridden in descendant classes
        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function destroy($id): bool
    {
        $destroyed = $this->manager->getAdapter()->destroy($id);
        if ($destroyed) {
            $this->manager->destroy();
        }

        return $destroyed;
    }

    /**
     * {@inheritDoc}
     */
    public function getPrefix(): ?string
    {
        return $this->manager->getAdapter()->getPrefix();
    }
}
