<?php

declare(strict_types=1);

/*
 * Copyright (c) 2017-2022 François Kooman <fkooman@tuxed.net>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace fkooman\SeCookie;

use DateTimeImmutable;
use DateTimeZone;
use fkooman\SeCookie\Exception\SessionException;

class Session
{
    private const SESSION_ID_LENGTH = 32;
    protected SessionStorageInterface $sessionStorage;
    protected DateTimeImmutable $dateTime;
    protected Cookie $cookie;
    private SessionOptions $sessionOptions;
    private ?ActiveSession $activeSession = null;

    public function __construct(?SessionOptions $sessionOptions = null, ?CookieOptions $cookieOptions = null, ?SessionStorageInterface $sessionStorage = null)
    {
        $this->sessionOptions = $sessionOptions ?? new SessionOptions();
        $this->cookie = new Cookie($cookieOptions ?? new CookieOptions());
        $this->sessionStorage = $sessionStorage ?? new FileSessionStorage();
        $this->dateTime = new DateTimeImmutable('now', new DateTimeZone('UTC'));
    }

    public function __destruct()
    {
        try {
            $this->stop();
        } catch (SessionException $e) {
            // prevent destructor from throwing exceptions as those will never
            // be caught...
        }
    }

    public function start(): void
    {
        if (null !== $this->activeSession) {
            // session has been started already, do nothing
            return;
        }

        // we take the exact same values PHP 7.3 also provides (by default)
        // after session_start()
        $this->sendHeader('Cache-Control: no-store, no-cache, must-revalidate');
        $this->sendHeader('Pragma: no-cache');

        $sessionName = $this->sessionOptions->getName();
        if (null === $sessionId = $this->cookie->get($sessionName)) {
            // no session cookie provided
            $this->activeSession = $this->createSession();

            return;
        }

        if (!self::isValidSessionId($sessionId)) {
            // invalid session id provided (invalid syntax)
            $this->activeSession = $this->createSession();

            return;
        }

        if (null === $activeSession = $this->sessionStorage->retrieve($sessionId)) {
            // session with provided session id not found
            $this->activeSession = $this->createSession();

            return;
        }

        if ($this->dateTime >= $activeSession->expiresAt()) {
            // session expired, delete it
            $this->sessionStorage->destroy($sessionId);
            $this->activeSession = $this->createSession();

            return;
        }

        // we have a valid session
        $this->activeSession = $activeSession;
    }

    public function stop(): void
    {
        if (null === $activeSession = $this->activeSession) {
            // session has been stopped already, or was never started, do
            // nothing
            return;
        }

        if ($activeSession->hasBeenModified()) {
            // if the session data has been modified...
            if (!$activeSession->isNew()) {
                // *and* it was not a freshly created session, create a new one
                // with the same data... (implicit "regenerate" behavior on
                // session data change)
                $activeSession = $this->regenerateSession($activeSession);
                // destroy the existing session
                $this->destroy();
            }
            // write session to storage, and send cookie
            $this->sessionStorage->store($activeSession);
            $this->cookie->set($this->sessionOptions->getName(), $activeSession->sessionId());
            $this->activeSession = null;
        }
    }

    public function destroy(): void
    {
        $activeSession = $this->requireActiveSession();
        $this->sessionStorage->destroy($activeSession->sessionId());
        $this->activeSession = null;
    }

    public function set(string $sessionKey, string $sessionValue): void
    {
        self::validateSessionKey($sessionKey);
        $activeSession = $this->requireActiveSession();
        $activeSession->set($sessionKey, $sessionValue);
    }

    public function get(string $sessionKey): ?string
    {
        self::validateSessionKey($sessionKey);
        $activeSession = $this->requireActiveSession();

        return $activeSession->get($sessionKey);
    }

    public function remove(string $sessionKey): void
    {
        self::validateSessionKey($sessionKey);
        $activeSession = $this->requireActiveSession();
        $activeSession->remove($sessionKey);
    }

    protected function createSessionId(): string
    {
        return sodium_bin2hex(random_bytes(self::SESSION_ID_LENGTH));
    }

    protected function sendHeader(string $headerKeyValue): void
    {
        // overwrite existing headers with same name
        header($headerKeyValue, true);
    }

    private function requireActiveSession(): ActiveSession
    {
        if (null === $activeSession = $this->activeSession) {
            throw new SessionException('session not active');
        }

        return $activeSession;
    }

    /**
     * Create a new session.
     */
    private function createSession(): ActiveSession
    {
        return new ActiveSession(
            $this->createSessionId(),
            $this->dateTime->add($this->sessionOptions->getExpiresIn())
        );
    }

    /**
     * Create a new session with data from an old session.
     */
    private function regenerateSession(ActiveSession $activeSession): ActiveSession
    {
        return new ActiveSession(
            $this->createSessionId(),
            $activeSession->expiresAt(),
            $activeSession->sessionData()
        );
    }

    private static function validateSessionKey(string $sessionKey): void
    {
        // "Strings containing valid decimal ints, unless the number is
        // preceded by a + sign, will be cast to the int type. E.g. the key
        // "8" will actually be stored under 8. On the other hand "08" will
        // not be cast, as it isn't a valid decimal integer."
        //
        // we "solve" this by disallowing any "numeric" value as a key, even
        // though strictly we only need to avoid "decimal ints".
        //
        // @see https://www.php.net/manual/en/language.types.array.php
        if (is_numeric($sessionKey)) {
            throw new SessionException('numeric "sessionKey" not allowed');
        }
    }

    private static function isValidSessionId(string $sessionId): bool
    {
        return 1 === preg_match('/^[0-9a-f]{64}$/', $sessionId);
    }
}
