<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '0');
set_time_limit(300);

$sites = [
    'betslots88' => [
        'domain' => 'betslots88.info-angkajitu.com',
        'brand'  => 'Betslots88',
        'links' => [
            'login'    => 'https://yuklah.me/betslots88',
            'promo'    => 'https://yuklah.me/LuckySpin-Betslots88',
            'rtp'      => 'https://yuklah.me/rtp-betslots88',
            'bukti'    => 'https://yuklah.me/BuktiJp-Betslots88',
            'telegram' => 'https://yuklah.me/Tele-Betslots88',
            'livechat' => 'https://yuklah.me/Betslots88-LC',
            'whatsapp' => 'https://yuklah.me/Bts88-Whatsapp',
            'apk'      => 'https://yuklah.me/APKBetslots88',
        ],
        'assets' => [
            'icon'    => 'https://media.mediatelekomunikasisejahtera.com/template/alpha/desktop/assets/betslots88/img/logo/favicon.webp?v=1.0',
            'logo'    => 'https://media.mediatelekomunikasisejahtera.com/template/alpha/desktop/assets/betslots88/img/logo/logo.webp',
            'banner1' => 'https://buatbanner.com/assets/betslots88/img/menu/slider/betslots88_cashback%20vip_Slider2026.webp',
            'banner2' => 'https://buatbanner.com/assets/betslots88/img/menu/slider/betslots88_Anti%20Rungkad_slider.webp',
            'slider'  => 'https://buatbanner.com/assets/betslots88/img/menu/slider/betslots88_THR%20Antam%20Series_slider.webp',
        ],
    ],
    'kingliga' => [
        'domain' => 'kingliga.info-angkajitu.com',
        'brand'  => 'Kingliga',
        'links' => [
            'login'    => 'https://yuklah.me/kingliga',
            'promo'    => 'https://yuklah.me/Luckyspin-kingliga',
            'rtp'      => 'https://yuklah.me/rtp-Kingliga',
            'bukti'    => 'https://yuklah.me/BuktiJp-Kingliga',
            'telegram' => 'https://yuklah.me/Tele-Kingliga',
            'livechat' => 'https://yuklah.me/Kingliga-LC',
            'whatsapp' => 'https://yuklah.me/Kingliga-WA',
            'apk'      => 'https://yuklah.me/APKKingliga',
        ],
        'assets' => [
            'icon'    => 'https://kingliga-image.idnsp.net/uploads/frontend-site/siteImage/favicon.ico',
            'logo'    => 'https://kingliga-image.idnsp.net/uploads/frontend-site/siteImage/logo_full_light.webp',
            'banner1' => 'https://kingliga-image.idnsp.net/uploads/content-management/2025081720530524.webp',
            'banner2' => 'https://kingliga-image.idnsp.net/uploads/content-management/202508200603443442.webp',
            'slider'  => 'https://kingliga-image.idnsp.net/uploads/content-management/202508172059191344.webp',
        ],
    ],
];

function buildReplacements(array $site): array
{
    $brand  = $site['brand'];
    $links  = $site['links'] ?? [];
    $assets = array_merge([
        'icon'    => '',
        'logo'    => '',
        'banner1' => '',
        'banner2' => '',
        'slider'  => '',
    ], $site['assets'] ?? []);

    return [
        // title / meta / text panjang
        'Inatogel | Blog Pasaran Terlengkap' => $brand . ' | Blog Pasaran Terlengkap dan Terpercaya',
        'Totowin88 | Blog Pasaran Terlengkap dan Terpercaya' => $brand . ' | Blog Pasaran Terlengkap dan Terpercaya',
        'Inatogel prediksi terlengkap' => $brand . ' prediksi terlengkap dan terpercaya',
        'Totowin88 prediksi terlengkap dan terpercaya' => $brand . ' prediksi terlengkap dan terpercaya',

        'Selamat datang di Inatogel Situs Games Online Terpercaya | Data Result Angka Terlengkap | Prediksi Angka Jitu Online | Paito Warna Terlengkap'
            => 'Selamat datang di ' . $brand . ' Situs Togel dengan Pasaran Terlengkap dan Terpercaya | Result Angka Togel Terlengkap | Prediksi Togel Angka Jitu Online Terpercaya | Paito Warna Terlengkap 2026',
        'Selamat datang di Totowin88 Situs Togel dengan Pasaran Terlengkap dan Terpercaya | Result Angka Togel Terlengkap | Prediksi Togel Angka Jitu Online Terpercaya | Paito Warna Terlengkap 2026'
            => 'Selamat datang di ' . $brand . ' Situs Togel dengan Pasaran Terlengkap dan Terpercaya | Result Angka Togel Terlengkap | Prediksi Togel Angka Jitu Online Terpercaya | Paito Warna Terlengkap 2026',

        // footer
        'Copyright © <span id="footer-year">2026</span> Totowin88 Agen Togel Online Terpercaya.'
            => 'Copyright © <span id="footer-year">2026</span> ' . $brand . ' Agen Togel Online Terpercaya.',
        '2022</span> Inatogel Agen Games Online Terpercaya.</div>'
            => '2026</span> ' . $brand . ' Agen Togel Online Terpercaya.</div>',
        '© 2026. Livedraw Togel Singapore Totowin88 Bandar'
            => '© 2026. Livedraw Togel Singapore ' . $brand . ' Bandar',

        // source links inatogel
        'https://blog8.inatips.com/' => '/',
        'https://sorty.bio/apkina' => $links['apk'] ?? '',
        'https://sorty.bio/ina1'   => $links['login'] ?? '',
        'https://sorty.bio/ina'    => $links['login'] ?? '',
        'https://t.me/inatogel88_official' => $links['telegram'] ?? '',
        'https://secure.livechatinc.com/customer/action/open_chat?license_id=13079895' => $links['livechat'] ?? '',
        'https://api.whatsapp.com/send?phone=6281389114046' => $links['whatsapp'] ?? '',

        // source links totowin
        'https://yuklah.me/totowin88' => $links['login'] ?? '',
        'https://yuklah.me/LuckySpin-Totowin88' => $links['promo'] ?? '',
        'https://yuklah.me/rtp-totowin88' => $links['rtp'] ?? '',
        'https://yuklah.me/BuktiJp-Totowin88' => $links['bukti'] ?? '',
        'https://yuklah.me/Totowin88-Tele' => $links['telegram'] ?? '',
        'https://yuklah.me/Totowin88-LC' => $links['livechat'] ?? '',
        'https://yuklah.me/Totowin88-WA' => $links['whatsapp'] ?? '',
        'https://yuklah.me/APKtotowin88' => $links['apk'] ?? '',

        // normalize internal absolute links
        'https://info-angkajitu.com/client/blog/liveDraw/?id=' => '/client/blog/liveDraw?id=',
        'http://info-angkajitu.com/client/blog/liveDraw/?id='  => '/client/blog/liveDraw?id=',
        'https://info-angkajitu.com/client/blog/liveDraw?id='  => '/client/blog/liveDraw?id=',
        'http://info-angkajitu.com/client/blog/liveDraw?id='   => '/client/blog/liveDraw?id=',

        'https://info-angkajitu.com/client/blog/result/?id='   => '/client/blog/result?id=',
        'http://info-angkajitu.com/client/blog/result/?id='    => '/client/blog/result?id=',
        'https://info-angkajitu.com/client/blog/result?id='    => '/client/blog/result?id=',
        'http://info-angkajitu.com/client/blog/result?id='     => '/client/blog/result?id=',

        'https://info-angkajitu.com/client/blog/prediksi/?id=' => '/client/blog/prediksi?id=',
        'http://info-angkajitu.com/client/blog/prediksi/?id='  => '/client/blog/prediksi?id=',
        'https://info-angkajitu.com/client/blog/prediksi?id='  => '/client/blog/prediksi?id=',
        'http://info-angkajitu.com/client/blog/prediksi?id='   => '/client/blog/prediksi?id=',

        '/client/blog/liveDraw/?id=' => '/client/blog/liveDraw?id=',
        '/client/blog/result/?id='   => '/client/blog/result?id=',
        '/client/blog/prediksi/?id=' => '/client/blog/prediksi?id=',

        'https://info-angkajitu.com/client/blog/' => '/client/blog/',
        'http://info-angkajitu.com/client/blog/'  => '/client/blog/',
        'https://info-angkajitu.com/client/blog'  => '/client/blog',
        'http://info-angkajitu.com/client/blog'   => '/client/blog',

        'https://info-angkajitu.com/' => '/',
        'http://info-angkajitu.com/'  => '/',
        'https://info-angkajitu.com'  => '/',
        'http://info-angkajitu.com'   => '/',

        // asset inatogel
        'https://paito3.acakina.com/assets/frontend/img/logo.png' => $assets['logo'],
        '/storage/gambarGlobal/blog/p0Dvjjy2UkslgvNdY2rG4ogBuUFFslblEfYkFyCA.png' => $assets['icon'],
        '/storage/gambarGlobal/blog/7wEI1zIVYeWdm1NoIVjlOepcXBEDX2h533KFkd9E.png' => $assets['banner1'],
        'https://cdn.harimauterbang.xyz/inatogel/Image/4tiprize1234.jpg' => $assets['banner2'],
        '/storage/gambarGlobal/blog/lrt1E8spjaAA9tGiWuWp5PzVPORyKDJklHN9ReNe.jpg' => $assets['slider'],

        // asset totowin
        'https://imagizer.imageshack.com/img923/7031/Kc4ulM.png' => $assets['icon'],
        'https://imagizer.imageshack.com/img921/2258/mXKOxK.png' => $assets['logo'],
        'https://buatbanner.com/assets/totowin88/img/banner/promo/totowin88_BonusDeposit10v2.webp' => $assets['banner1'],
        'https://buatbanner.com/assets/totowin88/img/banner/promo/totowin88_antirungkatv2.webp' => $assets['banner2'],
        'https://buatbanner.com/assets/totowin88/img/banner/promo/Totowin88_Lucky_Spin_Slider.webp' => $assets['slider'],

        // heading uppercase
        'DATA PREDIKSI TOGEL INATOGEL' => 'DATA PREDIKSI TOGEL ' . strtoupper($brand),
        'Data Prediksi Togel Inatogel' => 'Data Prediksi Togel ' . $brand,
        'data prediksi togel inatogel' => 'data prediksi togel ' . strtolower($brand),

        'DATA RESULT TOGEL INATOGEL'   => 'DATA RESULT TOGEL ' . strtoupper($brand),
        'Data Result Togel Inatogel'   => 'Data Result Togel ' . $brand,
        'data result togel inatogel'   => 'data result togel ' . strtolower($brand),

        'JADWAL TOGEL INATOGEL'        => 'JADWAL TOGEL ' . strtoupper($brand),
        'Jadwal Togel Inatogel'        => 'Jadwal Togel ' . $brand,
        'jadwal togel inatogel'        => 'jadwal togel ' . strtolower($brand),

        'LIVE DRAW PASARAN TOGEL ONLINE LENGKAP' => 'LIVE DRAW PASARAN TOGEL ONLINE LENGKAP',
        'NEXT DRAW IN' => 'NEXT DRAW IN',

        // generic pendek taruh paling bawah
        'INATOGEL'  => strtoupper($brand),
        'Inatogel'  => $brand,
        'inatogel'  => strtolower($brand),

        'TOTOWIN88' => strtoupper($brand),
        'Totowin88' => $brand,
        'totowin88' => strtolower($brand),
    ];
}

function normalizeBlogLinks(string $content): string
{
    $patterns = [
        '#/client/blog/liveDraw/\?id=([0-9]+)#i' => '/client/blog/liveDraw?id=$1',
        '#/client/blog/result/\?id=([0-9]+)#i'   => '/client/blog/result?id=$1',
        '#/client/blog/prediksi/\?id=([0-9]+)#i' => '/client/blog/prediksi?id=$1',
    ];

    foreach ($patterns as $pattern => $replacement) {
        $content = preg_replace($pattern, $replacement, $content);
    }

    return $content;
}

function applyReplacements(string $content, array $map): string
{
    uksort($map, static fn($a, $b) => strlen($b) <=> strlen($a));

    foreach ($map as $from => $to) {
        if ($to === null || $to === '') {
            continue;
        }
        $content = str_replace($from, (string) $to, $content);
    }

    return normalizeBlogLinks($content);
}

function shouldProcessFile(string $filename): bool
{
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    return $ext === 'html';
}

$results = [];

foreach ($sites as $key => $site) {
    $root = '/home/berihdjs/' . $site['domain'];
    $clientBlogDir = $root . '/client/blog';

    $siteResult = [
        'site' => $key,
        'domain' => $site['domain'],
        'processed' => [],
        'errors' => [],
    ];

    if (!is_dir($clientBlogDir)) {
        $siteResult['errors'][] = "Folder tidak ditemukan: {$clientBlogDir}";
        $results[] = $siteResult;
        continue;
    }

    $replaceMap = buildReplacements($site);

    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($clientBlogDir, FilesystemIterator::SKIP_DOTS)
    );

    foreach ($iterator as $file) {
        if (!$file->isFile()) {
            continue;
        }

        $path = $file->getPathname();
        if (!shouldProcessFile($path)) {
            continue;
        }

        try {
            $before = file_get_contents($path);
            if ($before === false) {
                throw new RuntimeException("Gagal baca file: {$path}");
            }

            $after = applyReplacements($before, $replaceMap);

            if ($after !== $before) {
                if (file_put_contents($path, $after) === false) {
                    throw new RuntimeException("Gagal tulis file: {$path}");
                }

                $siteResult['processed'][] = str_replace($root . '/', '', $path);
            }
        } catch (Throwable $e) {
            $siteResult['errors'][] = $path . ' => ' . $e->getMessage();
        }
    }

    $results[] = $siteResult;
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode([
    'success' => true,
    'message' => 'sync_blog_build_brand.php selesai (HTML only, live link normalized)',
    'results' => $results,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);