<?php

declare(strict_types=1);

namespace PrettyLinks\Pro\RedirectTypes;

use PrettyLinks\Repositories\LinkMetas;

/**
 * Meta-refresh redirect. Emits a minimal HTML page whose `<meta http-equiv>`
 * redirects the browser after an optional delay. Drop-in port of v3's
 * `metarefresh` redirect type — same `delay` per-link meta (seconds) is
 * honored.
 */
final class MetaRefreshRenderer
{
    /**
     * Link meta repository.
     *
     * @var LinkMetas
     */
    private LinkMetas $linkMetas;

    /**
     * Stores the link meta repository dependency.
     *
     * @param LinkMetas $linkMetas Link meta repository.
     */
    public function __construct(LinkMetas $linkMetas)
    {
        $this->linkMetas = $linkMetas;
    }

    /**
     * `prli_handle_redirect_type` filter callback.
     *
     * @param boolean              $handled Whether the redirect was already handled.
     * @param array<string, mixed> $link    Link row.
     * @param string               $target  Resolved outbound URL.
     * @param integer              $status  HTTP status code.
     * @param string               $type    The link redirect_type value.
     *
     * @return boolean Whether the redirect was handled.
     */
    public function filter(bool $handled, array $link, string $target, int $status, string $type): bool
    {
        unset($status);
        if ($handled || $type !== 'metarefresh') {
            return $handled;
        }

        $delay = $this->delay((int) ($link['id'] ?? 0));
        $title = (string) ($link['name'] ?? get_bloginfo('name'));

        nocache_headers();
        if (!headers_sent()) {
            header('Content-Type: text/html; charset=utf-8');
            header('X-Pretty-Link: metarefresh');
        }

        echo '<!doctype html><html lang="en"><head>';
        echo '<meta charset="utf-8">';
        echo '<meta name="robots" content="noindex,nofollow">';
        echo '<meta http-equiv="refresh" content="' . esc_attr((string) $delay) . ';url=' . esc_url($target) . '">';
        echo '<title>' . esc_html($title) . '</title>';
        do_action('prli_metarefresh_head', $link);
        echo '</head><body></body></html>';
        exit;
    }

    /**
     * Resolves the configured redirect delay for a link, in seconds.
     *
     * @param integer $linkId The link ID.
     *
     * @return integer The delay in seconds.
     */
    private function delay(int $linkId): int
    {
        if ($linkId <= 0) {
            return 0;
        }
        $raw = $this->linkMetas->get($linkId, 'delay', '0');
        return max(0, (int) $raw);
    }
}
