<?php

declare(strict_types=1);

/**
 * Open Graph HTML rendering for social media crawlers.
 * Included by redirect/index.php after constants and helpers are defined.
 *
 * Depends on (from index.php):
 *   srp_is_https(), srp_server_string(), srp_validate_host(),
 *   srp_e(), srp_proxy_image_url(), SRP_FB_APP_ID
 */
function srp_render_og(string $title, string $imageUrl): void
{
    $proxiedImage = srp_proxy_image_url($imageUrl);

    header('Content-Type: text/html; charset=UTF-8');
    header(
        "Content-Security-Policy: default-src 'none'; "
        . "img-src 'self' https:; "
        . "object-src 'none'; "
        . "base-uri 'self'; "
        . "frame-ancestors 'none'",
    );

    $displayTitle = $title !== '' ? $title : 'Preview';
    $titleEsc     = srp_e($displayTitle);
    $imageEsc     = srp_e($proxiedImage);
    $ogHost     = srp_server_string('HTTP_HOST');
    $currentUrl = srp_validate_host($ogHost)
        ? 'https://' . $ogHost . srp_server_string('REQUEST_URI')
        : '';
    $urlEsc     = srp_e($currentUrl);

    $markup = [
        '<!DOCTYPE html>',
        '<html lang="en" prefix="og: https://ogp.me/ns# fb: https://ogp.me/ns/fb#"><head>',
        '<meta charset="UTF-8">',
        '<title>' . $titleEsc . '</title>',
        '<meta name="description" content="' . $titleEsc . '">',
        '<meta prefix="fb: https://ogp.me/ns/fb#" property="fb:app_id" content="' . SRP_FB_APP_ID . '">',
        '<meta property="og:title" content="' . $titleEsc . '">',
        '<meta property="og:type" content="website">',
        '<meta property="og:url" content="' . $urlEsc . '">',
        '<meta property="og:description" content="' . $titleEsc . '">',
    ];

    if ($proxiedImage !== '') {
        $markup[] = '<meta property="og:image" content="' . $imageEsc . '">';
        $markup[] = '<meta property="og:image:secure_url" content="' . $imageEsc . '">';
        $markup[] = '<meta name="twitter:card" content="summary_large_image">';
        $markup[] = '<meta name="twitter:image" content="' . $imageEsc . '">';
    }

    $markup[] = '</head><body></body></html>';

    echo implode('', $markup);
}
