<?php
declare(strict_types=1);

require __DIR__ . '/_bootstrap.php';

function astrotvV2ZoekFetchUrl(string $url): array
{
    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_USERAGENT => 'AstroTV-v2-zoek/1.0',
        ]);
        $body = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return [
            'status' => $status,
            'body' => is_string($body) ? $body : '',
        ];
    }

    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => "User-Agent: AstroTV-v2-zoek/1.0\r\n",
            'timeout' => 15,
        ],
    ]);
    $body = @file_get_contents($url, false, $context);
    $status = 0;
    if (isset($http_response_header[0]) && preg_match('#\s(\d{3})\s#', $http_response_header[0], $matches)) {
        $status = (int) $matches[1];
    }

    return [
        'status' => $status,
        'body' => is_string($body) ? $body : '',
    ];
}

function astrotvV2ZoekRewriteHref(string $href): string
{
    $trimmed = trim($href);
    if ($trimmed === '' || str_starts_with($trimmed, '#') || str_starts_with($trimmed, 'mailto:') || str_starts_with($trimmed, 'tel:') || str_starts_with($trimmed, 'javascript:')) {
        return $href;
    }

    $normalized = $trimmed;
    if (str_starts_with($normalized, 'https://www.astrotv.nl')) {
        $normalized = substr($normalized, strlen('https://www.astrotv.nl'));
    } elseif (str_starts_with($normalized, 'http://www.astrotv.nl')) {
        $normalized = substr($normalized, strlen('http://www.astrotv.nl'));
    }

    if (!str_starts_with($normalized, '/')) {
        return $href;
    }

    if (preg_match('#^/(css|js|images|agents|favicon\.ico|robots\.txt|vendor|bxslider-4-master)(/|$)#', $normalized) === 1) {
        return '/new' . $normalized;
    }

    if (preg_match('#^/(apple-icon-|android-icon-|favicon-|manifest\.json|ms-icon-)(.*)?$#', $normalized) === 1) {
        return '/new' . $normalized;
    }

    $exactMap = [
        '/astroapp' => 'https://www.mediumsapp.com/',
        '/astrotv_zoek.php' => '/new/astrotv_zoek.php',
        '/info-contact' => '/new/contact/',
        '/astrotv_info.php' => '/new/contact/',
        '/privacy-avg' => '/new/privacy/',
        '/astrotv_avg.php' => '/new/privacy/',
        '/cookiebeleid' => '/new/cookiebeleid/',
        '/voorwaarden-disclaimer' => '/new/voorwaarden-disclaimer/',
        '/specialisten' => '/new/specialisten/',
        '/credits' => '/new/credits/',
        '/horoscopen' => '/new/horoscopen/',
        '/new' => '/new/',
        '/' => '/new/',
    ];
    if (isset($exactMap[$normalized])) {
        return $exactMap[$normalized];
    }

    $prefixMap = [
        '/horoscopen/' => '/new/horoscopen/',
        '/specialisten/' => '/new/specialisten/',
        '/call/credits/' => '/new/call/credits/',
    ];
    foreach ($prefixMap as $from => $to) {
        if (str_starts_with($normalized, $from)) {
            return $to . ltrim(substr($normalized, strlen($from)), '/');
        }
    }

    return $normalized;
}

function astrotvV2ZoekRewriteHtml(string $html): string
{
    $replacements = [
        'href="/css/' => 'href="/new/css/',
        "href='/css/" => "href='/new/css/",
        'href="/bxslider-4-master/' => 'href="/new/bxslider-4-master/',
        "href='/bxslider-4-master/" => "href='/new/bxslider-4-master/",
        'src="/js/' => 'src="/new/js/',
        "src='/js/" => "src='/new/js/",
        'src="/images/' => 'src="/new/images/',
        "src='/images/" => "src='/new/images/",
        'src="/agents/' => 'src="/new/agents/',
        "src='/agents/" => "src='/new/agents/",
        'src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"' => 'src="/new/js/vendor/jquery-1.7.2.min.js"',
        "src='//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'" => "src='/new/js/vendor/jquery-1.7.2.min.js'",
        'src="//code.jquery.com/ui/1.11.4/jquery-ui.js"' => 'src="/new/js/vendor/jquery-ui-1.11.4.js"',
        "src='//code.jquery.com/ui/1.11.4/jquery-ui.js'" => "src='/new/js/vendor/jquery-ui-1.11.4.js'",
        '$.get( "search.php"' => '$.get( "/new/search.php"',
        "$.get( 'search.php'" => "$.get( '/new/search.php'",
        'href="/astroapp"' => 'href="https://www.mediumsapp.com/"',
        "href='/astroapp'" => "href='https://www.mediumsapp.com/'",
    ];
    $html = str_replace(array_keys($replacements), array_values($replacements), $html);
    $html = preg_replace(
        '#https?://www\.astrotv\.nl/agents/4\.1/(\d+)/\1-1\.jpg#',
        '/new/agents/$1.png',
        $html
    ) ?? $html;
    $html = preg_replace(
        '#https?://www\.astrotv\.nl/agents/visitekaartje\.jpg#',
        '/new/agents/visitekaartje.jpg',
        $html
    ) ?? $html;

    if (!class_exists(DOMDocument::class)) {
        $html = str_replace('href="https://www.astrotv.nl/astrotv_zoek.php"', 'href="/new/astrotv_zoek.php"', $html);
        $html = str_replace('href="/astrotv_zoek.php"', 'href="/new/astrotv_zoek.php"', $html);
        return $html;
    }

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $loaded = $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    if (!$loaded) {
        return $html;
    }

    foreach (['a' => 'href', 'form' => 'action', 'link' => 'href'] as $tag => $attribute) {
        foreach ($dom->getElementsByTagName($tag) as $node) {
            if (!$node->hasAttribute($attribute)) {
                continue;
            }
            $node->setAttribute($attribute, astrotvV2ZoekRewriteHref($node->getAttribute($attribute)));
        }
    }

    $rendered = $dom->saveHTML();
    if (!is_string($rendered) || $rendered === '') {
        return $html;
    }

    return preg_replace('/^<\?xml[^>]+>\s*/', '', $rendered) ?? $rendered;
}

$queryString = (string) parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_QUERY);
$liveUrl = 'https://www.astrotv.nl/astrotv_zoek.php';
if ($queryString !== '') {
    $liveUrl .= '?' . $queryString;
}

$fetched = astrotvV2ZoekFetchUrl($liveUrl);
$status = (int) ($fetched['status'] ?? 0);
$body = (string) ($fetched['body'] ?? '');

if ($status === 404) {
    astrotvV2Render404('/astrotv_zoek.php');
}

if ($status >= 500 || $body === '') {
    http_response_code(502);
    echo 'Zoekpagina tijdelijk niet bereikbaar.';
    exit;
}

http_response_code(200);
header('Content-Type: text/html; charset=UTF-8');
echo astrotvV2ZoekRewriteHtml($body);
