<?php
namespace Misuzu\Auth;

use DateTimeImmutable;

// is this the right way to do this?
final class AuthTokenCookie {
    public static function domain(): string {
        $url = parse_url($_SERVER['HTTP_HOST'], PHP_URL_HOST);
        if(empty($url))
            $url = $_SERVER['HTTP_HOST'];

        if(!filter_var($url, FILTER_VALIDATE_IP))
            $url = '.' . $url;

        return $url;
    }

    public static function apply(string $packed): void {
        $now = new DateTimeImmutable('now');
        $threeMonths = $now->modify('+3 months');

        header(sprintf(
            'Set-Cookie: msz_auth=%s; Expires=%s; Max-Age=%d; Domain=%s; Path=/; SameSite=Lax; HttpOnly;%s',
            $packed,
            $threeMonths->format('D, d M Y H:i:s e'),
            $threeMonths->getTimestamp() - $now->getTimestamp(),
            self::domain(),
            filter_has_var(INPUT_SERVER, 'HTTPS') ? ' Secure' : ''
        ));
    }

    public static function nuke(): void {
        header(sprintf(
            'Set-Cookie: msz_auth=; Expires=Wed, 31 Dec 1969 21:29:59 UTC; Max-Age=-9001; Domain=%s; Path=/; SameSite=Lax; HttpOnly;%s',
            self::domain(),
            filter_has_var(INPUT_SERVER, 'HTTPS') ? ' Secure' : ''
        ));
    }
}
