<?php
// index.php

// Environment variables (like dotenv in Node)
$BASE_URL    = "https://dejavu-s3.ashm999.fr/api/v2/";
$BASE_DOMAIN = "alpha.sederamcs.org";

// Polyfill for str_ends_with for older PHP versions
if (!function_exists('str_ends_with')) {
    function str_ends_with(string $haystack, string $needle): bool {
        if ($needle === '') {
            return true;
        }
        return substr($haystack, -strlen($needle)) === $needle;
    }
}

// Simple HTTP GET helper (equivalent of async hentai() in Node)
function hentai(string $url): string {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);

    $res = curl_exec($ch);
    if ($res === false) {
        error_log("Fetch error: " . curl_error($ch));
        curl_close($ch);
        return "";
    }

    curl_close($ch);
    return $res;
}

function fetchArticleCacheOnce(string $key, string $BASE_URL, string $BASE_DOMAIN): array {
    $cacheDir = __DIR__ . '/cacheArticles';
    if (!is_dir($cacheDir)) {
        mkdir($cacheDir, 0755, true);
    }

    // safe filename
    $safeKey = preg_replace('/[^a-zA-Z0-9\-_\.]/', '_', $key);
    $cacheFile = $cacheDir . '/' . $safeKey . '.json';

    // ✅ 1. Use cache if exists
    if (file_exists($cacheFile)) {
        $raw = file_get_contents($cacheFile);
        $data = json_decode($raw, true);
        if (is_array($data)) {
            return $data;
        }
        // corrupted cache → delete
        unlink($cacheFile);
    }

    // ✅ 2. Call API normally
    $apiUrl = rtrim($BASE_URL, '/') . '/fetch/' . $BASE_DOMAIN . '/' . $key;
    $raw = hentai($apiUrl);
    $data = json_decode($raw, true);

    // ✅ 3. Save ONLY if valid
    if (is_array($data) && (!isset($data['statusCode']) || $data['statusCode'] === 200)) {
        file_put_contents(
            $cacheFile,
            json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
        );
    }

    return is_array($data) ? $data : [];
}


// Equivalent of addAnchorToFirstOccurrence()
function addAnchorToFirstOccurrence(string $text, string $search, string $url): string {
    if ($search === '') {
        return $text;
    }

    $pos = stripos($text, $search); // case-insensitive search

    if ($pos !== false) {
        $before = substr($text, 0, $pos);
        $after  = substr($text, $pos + strlen($search));

        $anchor = '<a style="color: #ff0000;" href="' . $url . '">'
                . str_replace("-"," ",htmlspecialchars($search, ENT_QUOTES))
                . '</a>';

        return $before . $anchor . $after;
    } else {
        $searchx = str_replace(' ', '-', $search);
        $name    = $search;
        return "<a style='color: #ff0000;' href='/'>" . str_replace("-"," ",htmlspecialchars($name)) . "</a> " . $text;
    }
}

function ensureDir(string $dir): void {
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
}

function loadOrCreateRelatedKw(string $brand, array $relatedKeywords, string $BASE_DOMAIN): array {
    $dir = __DIR__ . '/relatedKw';
    ensureDir($dir);

    $file = $dir . '/' . $brand . '.json';

    // use existing cache
    if (file_exists($file)) {
        $raw = file_get_contents($file);
        $arr = json_decode($raw, true);
        if (is_array($arr)) return $arr;
    }

    // load relatedlist.txt
    $listPath = __DIR__ . '/relatedlist.txt';
    $lines = [];

    if (file_exists($listPath)) {
        $lines = array_values(array_filter(
            array_map('trim', file($listPath)),
            fn($x) => $x !== ''
        ));
    }

    // shuffle once → ensures uniqueness
    if ($lines) {
        shuffle($lines);
    }

    // fallback if lines exhausted
    $fallback = "เข้าเล่นกับ related22 พร้อมโปรโมชั่นเด็ด <a href='https://related22.$BASE_DOMAIN/'>related22</a> เล่นได้ทุกวัน";

    $out = [];
    $lineIndex = 0;
    $lineCount = count($lines);

    foreach ($relatedKeywords as $kw) {
        $kw = trim((string)$kw);
        if ($kw === '') continue;

        // pick unique line if available
        if ($lineIndex < $lineCount) {
            $picked = $lines[$lineIndex];
            $lineIndex++;
        } else {
            $picked = $fallback;
        }

        $venezia = str_replace('-', ' ', $kw);

        $anchor = "<a style='color:#ff0000;' href='https://{$kw}.{$BASE_DOMAIN}/'>{$venezia}</a>";

        $text = str_replace('related22', $anchor, $picked);

        $out[] = [
            'keyword' => $kw,
            'text'    => $text,
        ];
    }

    file_put_contents(
        $file,
        json_encode($out, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
    );

    return $out;
}




function removeSpecialCharacters(string $str): string {
    return preg_replace('/[^a-zA-Z0-9\x{0E00}-\x{0E7F}\.\,\:\ ]/u', '', $str);
}

// Equivalent of replaceAll(template, oldArr, newArr)
function replaceAll(string $template, array $oldArr, array $newArr): string {
    return str_replace($oldArr, $newArr, $template);
}

// Helper to send JSON response and exit
function json_response($data, int $statusCode = 200): void {
    http_response_code($statusCode);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit;
}

// Basic router (similar to Express routes)
$uri    = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];

// Route: /login and /register  (GET)
if ($method === 'GET' && ($uri === '/login' || $uri === '/register')) {
    $server  = $BASE_DOMAIN;
    $api_url = rtrim($BASE_URL, '/') . '/domain/' . $server;

    $raw    = hentai($api_url);
    $config = json_decode($raw, true);

    if (!is_array($config)) {
        json_response([
            'message' => 'Invalid JSON from API',
            'raw'     => $raw,
        ], 500);
    }

    $action = $config['action'] ?? '/';
    header('Location: ' . $action, true, 302);
    exit;
}

// Route: /sitemap.xml
if ($method === 'GET' && $uri === '/sitemap.xml') {
    $server  = $BASE_DOMAIN;
    $api_url = rtrim($BASE_URL, '/') . '/sitemap/' . $server;

    $sitemap = hentai($api_url);
    if ($sitemap === '') {
        http_response_code(500);
        header('Content-Type: text/plain; charset=utf-8');
        echo "Error generating sitemap";
        exit;
    }

    header('Content-Type: application/xml; charset=utf-8');
    echo $sitemap;
    exit;
}

if ($method === 'GET' && $uri === '/robots.txt') {
    $server  = $BASE_DOMAIN;
    header('Content-Type: text/plain; charset=utf-8');
    echo str_replace("app.hubble.pg.com",$_SERVER['HTTP_HOST'],file_get_contents("rbt.txt"));
    exit;
}

// Route: /  (catch-all like app.get("/") in Express)
if ($method === 'GET' && $uri === '/') {
    $server = $_SERVER['HTTP_HOST'] ?? $BASE_DOMAIN;   // req.hostname
    $baseurl = '.' . $BASE_DOMAIN;

    if (str_ends_with($server, $baseurl)) {
        $brand = substr($server, 0, -strlen($baseurl));
    } else {
        $brand = '';
    }

    $cdn = 'cdn.stillsunday.pl';
    
    if($_SERVER['HTTP_HOST']===$BASE_DOMAIN) {
        $brand = "bunny555";
    }

    $data = fetchArticleCacheOnce($brand, $BASE_URL, $BASE_DOMAIN);

    if (!is_array($data)) {
        json_response([
            'message' => 'Invalid JSON from API',
            'raw'     => "Please try Again.",
        ], 500);
    }

    if (isset($data['statusCode']) && $data['statusCode'] !== 200) {
        json_response($data, (int)$data['statusCode']);
    }

    if (!$data) {
        json_response([
            'message' => 'Unexpected response from API',
            'data'    => "Please Refresh.",
        ], 500);
    }

    $templatePath = __DIR__ . '/templates/bigC.html';
    if (!file_exists($templatePath)) {
        json_response([
            'message' => 'Template not found',
            'error'   => 'File ' . $templatePath . ' does not exist',
        ], 500);
    }

    $template = file_get_contents($templatePath);

    // Main article values
    $image     = $data['banner'] ?? '';

    $title_web       = removeSpecialCharacters(str_replace("-"," ",$data['title']) ?? '');
    $description_web = removeSpecialCharacters(str_replace("-"," ",$data['description']) ?? '');
    $article_web     = removeSpecialCharacters(str_replace("-"," ",$data['content']) ?? '');

    $rmv = str_replace("-"," ",$data['brand']) ?? '';
    $bn  = $data['brand'] ?? '';

    $hostname  = $server;
    $canonical = idn_to_utf8('https://' . $bn . $baseurl . '/');
    $image_url = 'https://ts2.mm.bing.net/th?q=' . "$bn" . " สล็อต " . "$image" . (int)$title_web + (int)$image  . " slot "; + (int)$image;

    $article_web = addAnchorToFirstOccurrence($article_web, $bn, $canonical);

$apiRelatedKeywords = $data['relatedKeywords'] ?? [];
if (!is_array($apiRelatedKeywords)) $apiRelatedKeywords = [];

$relatedKwItems = loadOrCreateRelatedKw($brand, $apiRelatedKeywords, $BASE_DOMAIN);

$relatedKeywordsHtml = '';
foreach ($relatedKwItems as $it) {
    $kwText = (string)($it['text'] ?? '');

    // Keep raw HTML (because it includes <a href='...'>)
    $relatedKeywordsHtml .=
        "<div class=\"content-section-1\"><div class=\"internal-link-1\">{$kwText}</div></div>";
}


$apiRelatedArticles = $data['relatedArticles'] ?? [];
if (!is_array($apiRelatedArticles)) $apiRelatedArticles = [];

$relatedArticlesHtml = '';
$idx = 1;

foreach ($apiRelatedArticles as $ra) {
    if (!is_array($ra)) continue;

    $kw     = trim((string)($ra['keyword'] ?? ''));   // ✅ key field from your API
    $raTitle  = (string)($ra['title'] ?? '');
    $raBanner = (string)($ra['banner'] ?? '');

    if ($kw === '') continue;

    $href = "https://{$kw}.{$BASE_DOMAIN}/";
    $img  = 'https://ts2.mm.bing.net/th?q=' . "$kw" . "$raBanner 2025" . "$kw สล็อต " .  "ทดลองเล่นสล็อต" . "$kw swan";

    $safeHref  = $href;
    $safeTitle = htmlspecialchars(removeSpecialCharacters($raTitle), ENT_QUOTES, 'UTF-8');
    $safeImg   = htmlspecialchars($img, ENT_QUOTES, 'UTF-8');

    $slideNum = str_pad((string)$idx, 2, "0", STR_PAD_LEFT);
    $liId = "splide19-slide{$slideNum}";

    $relatedArticlesHtml .= <<<HTML
<li class="splide__slide is-visible" id="{$liId}" role="tabpanel" aria-roledescription="slide" aria-label="{$idx} of 6" style="width: 11rem;">
  <div class="productCard_container__KXMQK productCard_mobile__9_02D">
    <div class="productCard_img_wrapper__NQKtj">
      <div class="productCard_img_mb__c5UEi">
        <a href="{$safeHref}">
          <img alt="{$safeTitle}" loading="lazy" width="256" height="256" decoding="async" data-nimg="1" src="{$safeImg}"
               style="color: transparent; height: 100%; object-fit: contain; width: 100%; max-width: 256px; max-height: 256px;">
        </a>
      </div>
      <div class="productCard_badge_warpper__Lj2KV">
        <div class="productCard_badge_top-right__cvOLY">
          <img alt="badge" loading="lazy" width="38" height="38" decoding="async" data-nimg="1" src="{$safeImg}"
               style="color: transparent; width: 100%; height: auto; max-width: 38px; max-height: 38px;">
        </div>
      </div>
      <div class="productCard_choose_qty__mXUjB">
        <button class="circle_addtocart_btn__GU0Zy" aria-label="atc_card_{$idx}">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 18 18">
            <path d="M17.035,3.058a2.245,2.245,0,0,0-1.727-.808H3.181L3.15,1.987A2.25,2.25,0,0,0,.916,0H.75a.75.75,0,0,0,0,1.5H.916a.75.75,0,0,1,.745.662l1.032,8.775A3.75,3.75,0,0,0,6.418,14.25H14.25a.75.75,0,1,0,0-1.5H6.418A2.25,2.25,0,0,1,4.3,11.25h8.94a3.75,3.75,0,0,0,3.691-3.085L17.522,4.9a2.246,2.246,0,0,0-.488-1.842ZM16.05,4.634,15.46,7.9A2.25,2.25,0,0,1,13.243,9.75H4.064l-.706-6H15.307a.75.75,0,0,1,.742.883Z"></path>
            <ellipse cx="1.5" cy="1.5" rx="1.5" ry="1.5" transform="translate(3.75 15)"></ellipse>
            <ellipse cx="1.5" cy="1.5" rx="1.5" ry="1.5" transform="translate(11.25 15)"></ellipse>
          </svg>
        </button>
      </div>
      <div class="productCard_promotion_label__7iHm_">-14%</div>
    </div>
    <div>
      <div class="productCard_title__f1ohZ"><a href="{$safeHref}">{$safeTitle}</a></div>
      <div class="productCard_price__9T3J8"><span class="productCard_baht__cMDbh">฿</span>174.00<span class="productCard_unit__AAcwW"></span></div>
      <span class="productCard_base_price__2GuG3">฿204.00</span>
      <div class="productCard_shipping_labels___UMHJ">
        <span class="productCard_item__rjT_2" title="ส่งด่วน"><i class="productCard_icon-shipping__n3jk3" style="background-image: url(&quot;/images/icon/shipping/icon-shipping1.svg&quot;);"></i></span>
        <span class="productCard_item__rjT_2" title="สั่งล่วงหน้า"><i class="productCard_icon-shipping__n3jk3" style="background-image: url(&quot;/images/icon/shipping/icon-shipping2.svg&quot;);"></i></span>
        <span class="productCard_item__rjT_2" title="รับที่สาขา"><i class="productCard_icon-shipping__n3jk3" style="background-image: url(&quot;/images/icon/shipping/icon-shipping3.svg&quot;);"></i></span>
      </div>
    </div>
  </div>
</li>
HTML;

    $idx++;
    if ($idx > 6) break;
}

$links = [
    "https://woyaotree.pages.dev/",
    "https://woyaocuoai.pages.dev/"
];

$banners = [
    "https://payara.black-bullet.qpon/good.webp",
    "https://payara.black-bullet.qpon/vipaston8.webp"
];

// random index
$rand = mt_rand(0, count($links) - 1);

// selected random values
$linksa = $links[$rand];
$bannersa = $banners[$rand];


    // ✅ Add placeholders to replace
    $oldVals = [
        "canonical22",
        "brand22",
        "banner22",
        "title22",
        "description22",
        "article22",
        "hostname22",
        "https://woyaotree.pages.dev/",
        "https://payara.black-bullet.qpon/good.webp",

        // NEW placeholders you must add into templates/bigC.html
        "relatedKeywords22",
        "relatedArticles22",
    ];

    $newVals = [
        $canonical,
        $rmv,
        $image_url,
        $title_web,
        $description_web,
        $article_web,
        $BASE_DOMAIN,
        $linksa,
        $bannersa,

        // NEW injected blocks
        $relatedKeywordsHtml,
        $relatedArticlesHtml,
    ];

    $output = replaceAll($template, $oldVals, $newVals);

    header('Content-Type: text/html; charset=UTF-8');
    echo $output;
    exit;
}


// Fallback 404 for anything else (like Express default)
http_response_code(400);
header('Content-Type: text/plain; charset=utf-8');
echo "404 Not Found";
