<?php
declare(strict_types=1);

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

$sourceBase = 'https://blog8.inatips.com/client/blog';

/*
|--------------------------------------------------------------------------
| HANYA BETSLOTS88 + KINGLIGA
| Totowin88 jangan disentuh lagi
|--------------------------------------------------------------------------
*/
$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',
        ],
    ],
];

/*
|--------------------------------------------------------------------------
| Halaman root / tools yang mau disync
|--------------------------------------------------------------------------
*/
$pages = [
    ''             => 'client/blog/index.html',
    'totosgp'      => 'client/blog/totosgp/index.html',
    'liveDraw'     => 'client/blog/liveDraw/index.html',
    'jadwalTogel'  => 'client/blog/jadwalTogel/index.html',
    'bbfs'         => 'client/blog/bbfs/index.html',
    'bukuMimpi'    => 'client/blog/bukuMimpi/index.html',
    'paito'        => 'client/blog/paito/index.html',       // <-- baru
    'contackMe'    => 'client/blog/contackMe/index.html',   // <-- baru
    // tambah nanti kalau perlu:
    // 'bukumimpi'  => 'client/blog/bukumimpi/index.html',
    // 'paitowarna' => 'client/blog/paitowarna/index.html',
];

function fetchUrl(string $url): string
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_CONNECTTIMEOUT => 20,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_USERAGENT => 'Mozilla/5.0 SyncBlogRootTools/1.0',
    ]);

    $body = curl_exec($ch);
    $http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($body === false || $http >= 400) {
        throw new RuntimeException("Gagal fetch {$url} | HTTP {$http} | {$err}");
    }

    return (string) $body;
}

function ensureDir(string $dir): void
{
    if (!is_dir($dir) && !mkdir($dir, 0777, true) && !is_dir($dir)) {
        throw new RuntimeException("Gagal buat folder: {$dir}");
    }
}

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

    return [
        // =========================
        // BRAND / TITLE / TEXT
        // =========================
        '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',

        '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>',

        // pakai setelah string panjang supaya aman
        'Inatogel'  => $brand,
        'Totowin88' => $brand,

        // =========================
        // LINKS SOURCE LAMA
        // =========================
        'https://blog8.inatips.com/' => '/',
        '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'] ?? '',
        'https://sorty.bio/apkina' => $links['apk'] ?? '',
        'https://sorty.bio/ina1'   => $links['login'] ?? '',
        'https://sorty.bio/rtpina/'   => $links['rtp'] ?? '',
        'https://sorty.bio/buktiina/'   => $links['bukti'] ?? '',
        'https://sorty.bio/Inapromo'   => $links['promo'] ?? '',

        // =========================
        // LINKS SOURCE TOTOWIN LAMA
        // =========================
        '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'] ?? '',

        // =========================
        // ASSET SOURCE 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 SOURCE 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'],
    ];
}

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

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

    return $html;
}

$results = [];

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

    foreach ($pages as $slug => $targetRel) {
        $sourceUrl  = rtrim($sourceBase, '/') . ($slug !== '' ? '/' . $slug . '/' : '/');
        $targetFile = $root . '/' . $targetRel;
        $targetDir  = dirname($targetFile);

        try {
            $html = fetchUrl($sourceUrl);
            $html = applyReplacements($html, buildReplacements($site));

            ensureDir($targetDir);
            file_put_contents($targetFile, $html);

            $results[] = [
                'site'   => $key,
                'page'   => $slug === '' ? 'blog-root' : $slug,
                'ok'     => true,
                'target' => $targetFile,
            ];
        } catch (Throwable $e) {
            $results[] = [
                'site'  => $key,
                'page'  => $slug === '' ? 'blog-root' : $slug,
                'ok'    => false,
                'error' => $e->getMessage(),
            ];
        }
    }
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode([
    'success' => true,
    'results' => $results,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);