<?php
/**
 * swap_assets_exact_clean.php
 *
 * Exact replacement + clean browser "view-source saved page" wrapper
 */

declare(strict_types=1);

$replacements = [
    'Inatogel | Blog Pasaran Terlengkap' => 'Totowin88 | Blog Pasaran Terlengkap dan Terpercaya',
    '/storage/gambarGlobal/blog/p0Dvjjy2UkslgvNdY2rG4ogBuUFFslblEfYkFyCA.png' => 'https://imagizer.imageshack.com/img923/7031/Kc4ulM.png',
    'Inatogel prediksi terlengkap' => 'Totowin88 prediksi terlengkap dan terpercaya',
    'https://sorty.bio/rtpina/' => 'https://yuklah.me/rtp-totowin88',
    'https://sorty.bio/buktiina/' => 'https://yuklah.me/BuktiJp-Totowin88',
    'https://sorty.bio/Inapromo' => 'https://yuklah.me/LuckySpin-Totowin88',
    'https://blog8.inatips.com/' => '/',
    'https://sorty.bio/apkina' => 'https://yuklah.me/APKtotowin88',
    'https://t.me/inatogel88_official' => 'https://yuklah.me/totowin88',
    'https://secure.livechatinc.com/customer/action/open_chat?license_id=13079895' => 'https://yuklah.me/Totowin88-LC',
    'https://api.whatsapp.com/send?phone=6281389114046' => 'https://yuklah.me/Totowin88-WA',
    'https://paito3.acakina.com/assets/frontend/img/logo.png' => 'https://imagizer.imageshack.com/img921/2258/mXKOxK.png',
    'Selamat datang di Inatogel Situs Games Online Terpercaya | Data Result Angka Terlengkap | Prediksi Angka Jitu Online | Paito Warna Terlengkap' => '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',
    '/storage/gambarGlobal/blog/7wEI1zIVYeWdm1NoIVjlOepcXBEDX2h533KFkd9E.png' => 'https://buatbanner.com/assets/totowin88/img/banner/promo/totowin88_BonusDeposit10v2.webp',
    'https://cdn.harimauterbang.xyz/inatogel/Image/4tiprize1234.jpg' => 'https://buatbanner.com/assets/totowin88/img/banner/promo/totowin88_antirungkatv2.webp',
    '/storage/gambarGlobal/blog/lrt1E8spjaAA9tGiWuWp5PzVPORyKDJklHN9ReNe.jpg' => 'https://buatbanner.com/assets/totowin88/img/banner/promo/Totowin88_Lucky_Spin_Slider.webp',
    'https://sorty.bio/ina' => 'https://yuklah.me/totowin88',
    '2022</span> Inatogel Agen Games Online Terpercaya.</div>' => '2026</span> Totowin88 Agen Togel Online Terpercaya.</div>',
];

function normalize_saved_source_html(string $raw, array &$report): string
{
    // If this is a browser "view-source" saved page, extract real HTML from td.line-content cells.
    if (stripos($raw, 'class="line-content"') !== false || stripos($raw, "class='line-content'") !== false) {
        if (preg_match_all('/<td class="line-content">(.*?)<\/td>/is', $raw, $matches)) {
            $pieces = [];
            foreach ($matches[1] as $piece) {
                $piece = preg_replace('/<br\s*\/?>/i', "\n", $piece);
                $piece = html_entity_decode(strip_tags($piece), ENT_QUOTES | ENT_HTML5, 'UTF-8');
                $pieces[] = $piece;
            }
            $joined = implode("\n", $pieces);
            if (stripos($joined, '<!DOCTYPE html>') !== false || stripos($joined, '<html') !== false) {
                $report['normalization'] = [
                    'detected_saved_view_source' => true,
                    'message' => 'Browser source-view wrapper dibersihkan jadi HTML asli.'
                ];
                return $joined;
            }
        }
    }

    $report['normalization'] = [
        'detected_saved_view_source' => false,
        'message' => 'Tidak perlu normalisasi source-view wrapper.'
    ];
    return $raw;
}

function apply_replacements(string $html, array $replacements, array &$report): string
{
    $normalizeReport = [];
    $html = normalize_saved_source_html($html, $normalizeReport);

    $report = [
        'total_rules' => count($replacements),
        'matched_rules' => 0,
        'total_replacements' => 0,
        'details' => [],
        'normalization' => $normalizeReport['normalization'] ?? null,
    ];

    foreach ($replacements as $from => $to) {
        $count = 0;
        $html = str_replace($from, $to, $html, $count);

        $report['details'][] = [
            'from' => $from,
            'to' => $to,
            'count' => $count
        ];

        if ($count > 0) {
            $report['matched_rules']++;
            $report['total_replacements'] += $count;
        }
    }

    return $html;
}

function output_report_json(array $report): string
{
    return json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}

// CLI
if (PHP_SAPI === 'cli') {
    $argv = $_SERVER['argv'] ?? [];
    $source = $argv[1] ?? null;

    if (!$source || !is_file($source)) {
        fwrite(STDERR, "Pakai:\nphp swap_assets_exact_clean.php source.html -o hasil.html\n");
        exit(1);
    }

    $output = null;
    for ($i = 2; $i < count($argv); $i++) {
        if ($argv[$i] === '-o' && isset($argv[$i + 1])) {
            $output = $argv[$i + 1];
            break;
        }
    }

    if (!$output) {
        $dir = dirname($source);
        $name = pathinfo($source, PATHINFO_FILENAME);
        $output = $dir . DIRECTORY_SEPARATOR . $name . '_totowin88_clean.html';
    }

    $reportPath = preg_replace('/\.html?$/i', '', $output) . '_report.json';

    $html = file_get_contents($source);
    if ($html === false) {
        fwrite(STDERR, "Gagal baca file source.\n");
        exit(1);
    }

    $report = [];
    $result = apply_replacements($html, $replacements, $report);

    file_put_contents($output, $result);
    file_put_contents($reportPath, output_report_json($report));

    echo "OK HTML   : {$output}\n";
    echo "OK Report : {$reportPath}\n";
    exit(0);
}

// WEB
$error = null;
$success = null;
$result_html = null;
$result_report = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!isset($_FILES['source_html']) || $_FILES['source_html']['error'] !== UPLOAD_ERR_OK) {
            throw new RuntimeException('Source HTML wajib diupload.');
        }

        $html = file_get_contents($_FILES['source_html']['tmp_name']);
        if ($html === false) {
            throw new RuntimeException('Gagal membaca source HTML.');
        }

        $report = [];
        $result_html = apply_replacements($html, $replacements, $report);
        $result_report = output_report_json($report);
        $success = 'Selesai. HTML sudah dibersihkan lalu diproses exact replacement.';
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exact Replacement Totowin88 Clean</title>
    <style>
        body{font-family:Arial,sans-serif;background:#081226;color:#e5e7eb;margin:0;padding:24px}
        .wrap{max-width:1100px;margin:0 auto}
        .card{background:#0d1b34;border:1px solid #27406f;border-radius:16px;padding:20px;margin-bottom:20px}
        h1,h2{margin-top:0}
        input[type=file],button,textarea{width:100%;box-sizing:border-box;margin-bottom:16px}
        textarea{min-height:260px;background:#030712;color:#e5e7eb;border:1px solid #334155;border-radius:12px;padding:12px}
        button{background:#22c55e;color:#052e16;border:0;border-radius:12px;padding:14px 16px;font-weight:bold;cursor:pointer}
        .alert{padding:14px 16px;border-radius:12px;margin-bottom:16px}
        .ok{background:#14532d;color:#dcfce7}
        .err{background:#7f1d1d;color:#fee2e2}
        .grid{display:grid;grid-template-columns:1fr 1fr;gap:20px}
        .btn{display:inline-block;padding:10px 14px;background:#1d4ed8;color:#fff;text-decoration:none;border-radius:10px}
        @media (max-width:900px){.grid{grid-template-columns:1fr}}
    </style>
</head>
<body>
<div class="wrap">
    <div class="card">
        <h1>Exact Replacement Totowin88 Clean</h1>
        <p>Versi ini membersihkan file hasil save dari view-source browser, lalu menjalankan exact replacement.</p>
    </div>

    <?php if ($success): ?><div class="alert ok"><?= htmlspecialchars($success, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert err"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>

    <form method="post" enctype="multipart/form-data">
        <div class="card">
            <label>Source HTML</label>
            <input type="file" name="source_html" accept=".html,.htm" required>
            <button type="submit">Proses Exact Replacement + Clean</button>
        </div>
    </form>

    <?php if ($result_html !== null && $result_report !== null): ?>
    <div class="grid">
        <div class="card">
            <h2>Hasil HTML</h2>
            <p><a class="btn" href="data:text/html;charset=utf-8,<?= rawurlencode($result_html) ?>" download="result_totowin88_clean.html">Download HTML</a></p>
            <textarea readonly><?= htmlspecialchars($result_html, ENT_QUOTES, 'UTF-8') ?></textarea>
        </div>
        <div class="card">
            <h2>Report JSON</h2>
            <p><a class="btn" href="data:application/json;charset=utf-8,<?= rawurlencode($result_report) ?>" download="result_totowin88_clean_report.json">Download Report</a></p>
            <textarea readonly><?= htmlspecialchars($result_report, ENT_QUOTES, 'UTF-8') ?></textarea>
        </div>
    </div>
    <?php endif; ?>
</div>
</body>
</html>
