<?php
/**
 * Tunnel 4 — Static Directory Generator
 *
 * Usage (web):
 *   builder.php?generate=all   → Mass generate all 18 brand folders
 *   builder.php?generate=dry   → Dry run (no files written)
 *   builder.php?folder=BRAND   → Generate single brand folder (via .htaccess)
 *
 * Usage (CLI):
 *   php builder.php --generate=all [--output=Deploy/]
 *   php builder.php --generate=dry [--output=Deploy/]
 */

$is_cli = (php_sapi_name() === 'cli');

if ($is_cli) {
    $args = getopt('', ['generate::', 'folder::', 'output::']);
    $mode = isset($args['generate']) ? 'generate' : (isset($args['folder']) ? 'folder' : null);
    $mode_value = $args['generate'] ?? ($args['folder'] ?? null);
    $cli_output = $args['output'] ?? null;
} else {
    $mode = isset($_GET['generate']) ? 'generate' : (isset($_GET['folder']) ? 'folder' : null);
    $mode_value = $_GET['generate'] ?? ($_GET['folder'] ?? null);
    $cli_output = null;
}

if ($mode === null || ($mode === 'generate' && !in_array($mode_value, ['all', 'dry'])) || ($mode === 'folder' && empty($mode_value))) {
    $usage = $is_cli
        ? "Usage:\n  php builder.php --generate=all|dry [--output=Deploy/]\n  php builder.php --folder=BRAND\n"
        : "Usage: ?generate=all | ?generate=dry | ?folder=BRAND";
    die($usage);
}

$config_path = 'config.php';
if (!file_exists($config_path)) die("ERROR: config.php not found\n");
$config = include $config_path;

$output_dir = ($cli_output !== null)
    ? rtrim($cli_output, '/') . '/'
    : (isset($config['output_dir']) ? rtrim($config['output_dir'], '/') . '/' : './');
$domain = rtrim($config['domain'], '/');
$login_url = $config['login_url'];
$brands = $config['brands'];

if ($mode === 'folder') {
    $target = trim($mode_value);
    $valid = false;
    foreach ($brands as $b) {
        if (strtolower($target) === strtolower($b)) { $target = $b; $valid = true; break; }
    }
    if (!$valid) {
        if (!$is_cli) header("HTTP/1.1 404 Not Found");
        die("IZIN YA KOKO");
    }
}

$template_path = 'temp11.html';
if (!file_exists($template_path)) die("ERROR: temp11.html not found\n");
$lp_template = file_get_contents($template_path);

// Pre-process template: convert ?id= param links to directory style
$lp_template = str_replace('{{ u }}?id={{ BRAND }}"', '{{ u }}/{{ BRAND }}/"', $lp_template);
$lp_template = str_replace("{{ u }}?id={{ BRAND }}'", "{{ u }}/{{ BRAND }}/'", $lp_template);
$lp_template = str_replace('{{ AMP }}?id={{ BRAND }}"', '{{ u }}/{{ BRAND }}/amp.html"', $lp_template);
$lp_template = str_replace("{{ AMP }}?id={{ BRAND }}'", "{{ u }}/{{ BRAND }}/amp.html'", $lp_template);

// Fix asset paths to root-relative (pages live in /BRAND/ subfolders)
$asset_patterns = [
    'src="logo-slotgacor.png"'  => 'src="/logo-slotgacor.png"',
    "src='logo-slotgacor.png'"  => "src='/logo-slotgacor.png'",
    'href="icon-slotgacor.gif"'  => 'href="/icon-slotgacor.gif"',
    "href='icon-slotgacor.gif'"  => "href='/icon-slotgacor.gif'",
    'src="izin-ya-koko.jpeg"'  => 'src="/izin-ya-koko.jpeg"',
    "src='izin-ya-koko.jpeg'"  => "src='/izin-ya-koko.jpeg'",
    'content="izin-ya-koko.jpeg"'  => 'content="/izin-ya-koko.jpeg"',
    "content='izin-ya-koko.jpeg'"  => "content='/izin-ya-koko.jpeg'",
    'url("logo-slotgacor.png")' => 'url("/logo-slotgacor.png")',
    "url('logo-slotgacor.png')" => "url('/logo-slotgacor.png')",
    'url("izin-ya-koko.jpeg")'  => 'url("/izin-ya-koko.jpeg")',
    "url('izin-ya-koko.jpeg')"  => "url('/izin-ya-koko.jpeg')",
];
$lp_template = str_replace(array_keys($asset_patterns), array_values($asset_patterns), $lp_template);

// Load titles
$td_sets = [];
$titles_path = 'titles.txt';
if (file_exists($titles_path)) {
    $lines = file($titles_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
        if (empty($line)) continue;
        $parts = explode('|||', $line);
        if (count($parts) >= 2) {
            $td_sets[] = [
                'title'       => trim($parts[0]),
                'description' => trim($parts[1]),
                'p1'          => isset($parts[2]) ? trim($parts[2]) : '',
                'p2'          => isset($parts[3]) ? trim($parts[3]) : '',
                'p3'          => isset($parts[4]) ? trim($parts[4]) : '',
            ];
        }
    }
}

$brands_to_process = ($mode === 'folder') ? [$target] : $brands;
$is_dry = ($mode === 'generate' && $mode_value === 'dry');
$generated = [];
$skipped = [];
$errors = [];

if (!$is_dry) {
    if (!is_dir($output_dir)) {
        if (!@mkdir($output_dir, 0755, true)) die("ERROR: Cannot create output directory: $output_dir\n");
    }
    if (!is_writable($output_dir)) die("ERROR: Output directory not writable: $output_dir\n");
}

$asset_warnings = [];
foreach (['logo-slotgacor.png', 'icon-slotgacor.gif', 'izin-ya-koko.jpeg'] as $af) {
    if (!file_exists($af)) $asset_warnings[] = $af;
}

$current_dir = getcwd();

foreach ($brands_to_process as $index => $brand) {
    $brand_folder = $output_dir . $brand . '/';
    $index_html = $brand_folder . 'index.html';
    $amp_html = $brand_folder . 'amp.html';

    if (file_exists($index_html)) {
        $skipped[] = $brand;
        continue;
    }

    if (!empty($td_sets)) {
        $td = $td_sets[$index % count($td_sets)];
        $title       = $td['title'];
        $description = $td['description'];
        $p1 = $td['p1'];
        $p2 = $td['p2'];
        $p3 = $td['p3'];
    } else {
        $title = "{{ BRAND }} — Jangan Asal Main Sebelum Pahami Karakter Tiap Provider";
        $description = "Setiap provider punya karakter berbeda. {{ BRAND }} kupas perbedaan volatilitas, RTP, dan pola gameplay biar kamu nggak salah pilih.";
        $p1 = ''; $p2 = ''; $p3 = '';
    }

    $title       = str_replace(['{{ BRAND }}', '{ BRAND }'], $brand, $title);
    $description = str_replace(['{{ BRAND }}', '{ BRAND }'], $brand, $description);
    $p1 = str_replace(['{{ BRAND }}', '{ BRAND }'], $brand, $p1);
    $p2 = str_replace(['{{ BRAND }}', '{ BRAND }'], $brand, $p2);
    $p3 = str_replace(['{{ BRAND }}', '{ BRAND }'], $brand, $p3);

    $p1 = str_replace('{{ u }}?id={{ BRAND }}', $domain . '/' . $brand . '/', $p1);
    $p2 = str_replace('{{ u }}?id={{ BRAND }}', $domain . '/' . $brand . '/', $p2);
    $p3 = str_replace('{{ u }}?id={{ BRAND }}', $domain . '/' . $brand . '/', $p3);
    $p1 = str_replace('{{ u }}', $domain, $p1);
    $p2 = str_replace('{{ u }}', $domain, $p2);
    $p3 = str_replace('{{ u }}', $domain, $p3);

    $html = $lp_template;
    $brand_url = $domain . '/' . $brand . '/';

    $html = str_replace('{{ u }}', $domain, $html);
    $html = str_replace('{{ BRAND }}', $brand, $html);
    $html = str_replace('{ BRAND }', $brand, $html);
    $html = str_replace('{{ URL }}', $brand_url, $html);
    $html = str_replace('{{ AMP }}', $domain, $html);
    $html = str_replace('{{ t }}', htmlspecialchars($title, ENT_QUOTES, 'UTF-8'), $html);
    $html = str_replace('{{ d }}', htmlspecialchars($description, ENT_QUOTES, 'UTF-8'), $html);
    $html = str_replace('{{ p1 }}', $p1, $html);
    $html = str_replace('{{ p2 }}', $p2, $html);
    $html = str_replace('{{ p3 }}', $p3, $html);
    $html = str_replace($domain . '?id=' . $brand, $brand_url, $html);

    $amp = generate_amp($brand, $title, $description, $brand_url, $domain, $login_url);

    if ($is_dry) {
        $generated[] = $brand;
    } else {
        if (!is_dir($brand_folder)) {
            if (!@mkdir($brand_folder, 0755, true)) {
                $errors[] = "mkdir failed: $brand_folder";
                continue;
            }
        }
        if (@file_put_contents($index_html, $html) === false) $errors[] = "write failed: $index_html";
        if (@file_put_contents($amp_html, $amp) === false) $errors[] = "write failed: $amp_html";
        $generated[] = $brand;
    }
}

if (!$is_dry && empty($errors)) {
    generate_sitemap($brands, $domain, $output_dir);
    generate_htaccess($output_dir);
}

if (!$is_cli) header('Content-Type: text/plain; charset=utf-8');

$label = $is_dry ? 'DRY RUN (No files written)' : 'BUILD COMPLETE';
echo "=== Tunnel 4 — $label ===\n";
echo "Domain: $domain\n";
echo "Brands: " . count($brands) . " | Title sets: " . count($td_sets) . "\n";
echo "Output: $output_dir\n";
if (!empty($asset_warnings)) echo "WARNING: Missing assets — " . implode(', ', $asset_warnings) . "\n";
echo "\nGenerated: " . count($generated) . "\n";
foreach ($generated as $b) echo "  ✓ /$b/\n";
if (!empty($skipped)) {
    echo "\nSkipped (already exists): " . count($skipped) . "\n";
    foreach ($skipped as $b) echo "  ⊘ /$b/\n";
}
if (!empty($errors)) {
    echo "\nERRORS: " . count($errors) . "\n";
    foreach ($errors as $e) echo "  ✗ $e\n";
}
if (!$is_dry) echo "\nSitemap: sitemap.xml ✓\n";
if ($is_dry) echo "\n>> Set --generate=all to execute.\n";
echo "\n=== Done ===\n";


function generate_amp($brand, $title, $description, $canonical_url, $domain, $login_url) {
    $t = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
    $d = htmlspecialchars($description, ENT_QUOTES, 'UTF-8');
    $canon = htmlspecialchars($canonical_url, ENT_QUOTES, 'UTF-8');
    $dom = htmlspecialchars($domain, ENT_QUOTES, 'UTF-8');
    $login = htmlspecialchars($login_url, ENT_QUOTES, 'UTF-8');

    return <<<AMP
<!DOCTYPE html>
<html amp lang="id">
<head>
    <meta charset="utf-8" />
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>$t</title>
    <meta name="description" content="$d" />
    <link href="/icon-slotgacor.gif" rel="icon" type="image/x-icon" />
    <link rel="canonical" href="$canon" />
    <meta name="robots" content="max-snippet:0">
    <meta property="og:url" content="$canon" />
    <meta property="og:site_name" content="SLOT GACOR" />
    <meta property="og:image:alt" content="SLOT GACOR" />
    <meta property="og:image" content="/izin-ya-koko.jpeg" />
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
    <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <style amp-custom>
        *{box-sizing:border-box}
        body{font-family:'Orbitron',monospace;position:relative;background:#000;background-image:radial-gradient(circle at 10% 20%,rgba(255,216,0,0.15) 2%,transparent 2.5%),radial-gradient(circle at 80% 70%,rgba(255,200,0,0.1) 1.5%,transparent 2%);background-size:40px 40px,30px 30px;background-attachment:fixed}
        .container{max-width:450px;height:100vh;margin:0 auto;padding:15px;display:flex;flex-direction:column;justify-content:center;overflow:hidden}
        .welcome{max-width:350px;margin:0 auto;text-align:center}
        .welcome h3{font-size:14px;color:#ffd800;overflow:hidden;border-right:.15em solid #ffd800;white-space:nowrap;letter-spacing:.09em;animation:typing 3.5s steps(40,end),blink-caret .75s step-end infinite;text-shadow:0 0 5px #fa0}
        @keyframes typing{from{width:0}to{width:100%}}
        @keyframes blink-caret{from,to{border-color:transparent}50%{border-color:#ffd800}}
        .banner{border-radius:10px;box-shadow:0 0 20px rgba(255,216,0,0.3);transition:transform .3s ease}
        .banner:hover{transform:scale(1.02);box-shadow:0 0 30px rgba(255,216,0,0.5)}
        .btn-login,.btn-daftar{padding:15px;font-size:18px;font-weight:bold;text-decoration:none;text-align:center;margin-top:20px;border-radius:50px;transition:all .3s ease}
        .btn-login{background:linear-gradient(135deg,#ffd800,#fa0);color:#000;box-shadow:0 5px 15px rgba(255,216,0,0.4)}
        .btn-login:hover{background:linear-gradient(135deg,#ffea00,#fc0);transform:translateY(-3px);box-shadow:0 8px 20px rgba(255,216,0,0.6)}
        .btn-daftar{background:linear-gradient(135deg,#222,#111);color:#ffd800;border:1px solid #ffd800;box-shadow:0 0 10px rgba(255,216,0,0.3)}
        .btn-daftar:hover{background:linear-gradient(135deg,#333,#222);transform:translateY(-3px);box-shadow:0 0 20px rgba(255,216,0,0.5)}
        .copyright{text-align:center;color:#000;font-size:20px;margin-top:20px}
        .glow-on-hover{border:none;outline:none;color:#ffd800;background:#111;cursor:pointer;position:relative;z-index:0;border-radius:50px;font-weight:bold;transition:all .3s ease}
        .glow-on-hover:before{content:'';background:linear-gradient(88deg,#ffd800,#fa0,#ffd800,#f60,#ffd800,#fa0,#ffd800,#f60);position:absolute;top:-2px;left:-2px;background-size:400%;z-index:-1;filter:blur(8px);width:calc(100% + 4px);height:calc(100% + 4px);animation:glowing 20s linear infinite;opacity:0;transition:opacity .3s ease-in-out;border-radius:50px}
        .glow-on-hover:before{opacity:1}
        .glow-on-hover:after{z-index:-1;content:'';position:absolute;width:100%;height:100%;background:linear-gradient(135deg,#1a1a1a,#0a0a0a);left:0;top:0;border-radius:50px}
        .glow-on-hover:hover{transform:scale(1.05);color:#fff}
        @keyframes glowing{0%{background-position:0 0}50%{background-position:400% 0}100%{background-position:0 0}}
        @keyframes slotFlash{0%{opacity:0.5}100%{opacity:1}}
        .slot-effect{animation:slotFlash .5s ease infinite alternate}
    </style>
</head>
<body>
    <div class="container">
        <header>
            <center>
                <a href="$dom">
                    <amp-img id="image" src="/logo-slotgacor.png" alt="SLOT GACOR" width="250" height="80" layout="intrinsic" style="margin-bottom:10px;"></amp-img>
                </a>
            </center>
        </header>
        <div class="welcome">
            <h3>Langsung Spin Tanpa Ribet</h3>
        </div>
        <amp-img src="/izin-ya-koko.jpeg" width="600" height="600" layout="intrinsic" class="banner"></amp-img>
        <a href="$login" target="_blank" rel="noreferrer noopener" role="button" class="btn-login glow-on-hover">LOGIN</a>
        <a href="$login" target="_blank" rel="noreferrer noopener" role="button" class="btn-daftar glow-on-hover">DAFTAR</a>
        <p>
        <p class="copyright"><a href="$dom" rel="noopener noreferrer" style="color:#ffbb00;">CEO BLEK</a></p>
    </div>
</body>
</html>
AMP;
}


function generate_htaccess($output_dir) {
    $htaccess = <<<HTA
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-z0-9]+)/?$ builder.php?folder=$1 [L,QSA]
HTA;
    @file_put_contents($output_dir . '.htaccess', $htaccess);
}


function generate_sitemap($brands, $domain, $output_dir) {
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->formatOutput = true;

    $urlset = $dom->createElement('urlset');
    $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
    $dom->appendChild($urlset);

    foreach ($brands as $brand) {
        $url = $domain . '/' . $brand . '/';
        $urlElement = $dom->createElement('url');
        $urlElement->appendChild($dom->createElement('loc', htmlspecialchars($url)));
        $urlElement->appendChild($dom->createElement('lastmod', date('Y-m-d')));
        $urlElement->appendChild($dom->createElement('changefreq', 'daily'));
        $urlset->appendChild($urlElement);
    }

    $dom->save($output_dir . 'sitemap.xml');
}
