<?php
// rebuild_modals.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$base_dir = __DIR__;
$templates_dir = "$base_dir/templates";
$landingpages_dir = "$base_dir/landingpages";

$php_header = <<<'PHP'
<?php
// templates/landing{ID}.php
$site_settings = get_site_settings($pdo);
$landing_title = $site_settings['landing_title'] ?? 'UTAMU';
$favicon = $site_settings['site_favicon'] ?? 'assets/images/favicon.png';

if (!$featured && !empty($videos)) {
    $featured = $videos[0];
}
?>

PHP;

$universal_js = <<<'JS'
<script>
const SITE = '<?= SITE_URL ?>';
let paymentCheckInterval = null;
let customModalId = ''; 
window.currentCheckoutId = null;
window.currentCheckoutTitle = 'Customer';
window.currentCheckoutPrice = 0;
window.originalBtnHtml = '';

function openPaymentModal(event, price, id) {
    if (event && event.preventDefault) event.preventDefault();
    customModalId = 'paymentModal';
    document.getElementById(customModalId).style.display = 'flex';
    setupModalData(price, id, '');
}
function openPaymentSheet(price, id) {
    customModalId = 'paymentModal';
    document.getElementById(customModalId).classList.add('open');
    setupModalData(price, id, '');
}
function openCyberModal(price, id) {
    customModalId = 'paymentModal';
    document.getElementById(customModalId).style.display = 'grid';
    setupModalData(price, id, '');
}
function openSheet(price, id) {
    customModalId = 'sheet';
    document.getElementById(customModalId).classList.add('show');
    document.getElementById('overlay').style.display = 'block';
    setupModalData(price, id, '');
}
function handleVideoClick(el, isPaid, url) { 
    if(isPaid) { window.location.href = url; return; }
    customModalId = 'paymentModal';
    document.getElementById(customModalId).classList.add('active');
    setupModalData(el.getAttribute('data-price'), el.getAttribute('data-id'), el.getAttribute('data-title'));
}

function closeCyberModal() { closeModalUniversal(); }
function closeSheet() { closeModalUniversal(); }
function closePaymentModal() { closeModalUniversal(); }
function closeModal() { closeModalUniversal(); }

function closeModalUniversal() {
    if(!customModalId) customModalId = 'paymentModal';
    const m = document.getElementById(customModalId);
    if(m) {
        m.style.display = 'none';
        m.classList.remove('open', 'active', 'show');
    }
    const sheet = document.getElementById('sheet');
    if(sheet) Object.assign(sheet.style, {bottom: '-100%'}) || sheet.classList.remove('show');
    
    const overlay = document.getElementById('overlay');
    if(overlay) overlay.style.display = 'none';
    if(paymentCheckInterval) clearInterval(paymentCheckInterval);
    resetPayButtonUniversal();
}

function setupModalData(price, id, title) {
    const vidInput = document.getElementById('videoID');
    if(vidInput) vidInput.value = id;
    
    window.currentCheckoutId = id;
    window.currentCheckoutTitle = title || 'Customer';
    window.currentCheckoutPrice = price;

    const priceEl = document.getElementById('modalPrice') || document.querySelector('.price-amount');
    if(priceEl) {
        if (priceEl.innerText.includes('TSH')) {
            priceEl.innerText = 'TSH ' + parseInt(price).toLocaleString();
        } else {
            priceEl.innerText = parseInt(price).toLocaleString();
        }
    }
}

async function processPayment() { 
    const phoneInput = document.querySelector('input[type="tel"]') || document.getElementById('phoneInput') || document.getElementById('phoneNumber');
    let phone = phoneInput ? phoneInput.value.replace(/[\s-]/g, '') : '';
    
    if (phone.length === 9 && !phone.startsWith('0')) phone = '0' + phone; 

    if (!phone || phone.length < 10) {
        alert("Weka namba sahihi ya simu, ianzie na 0");
        return;
    }

    const amount = window.currentCheckoutPrice;
    const videoID = window.currentCheckoutId || (document.getElementById('videoID') ? document.getElementById('videoID').value : null);
    
    const payBtn = document.querySelector('.btn-full') || document.querySelector('.btn-neon') || document.querySelector('.pay-btn-final') || document.getElementById('payBtn') || document.querySelector('.pay-btn');
    
    if(!window.originalBtnHtml) window.originalBtnHtml = payBtn.innerHTML;
    payBtn.innerHTML = 'INACHAKATA...';
    payBtn.disabled = true;

    try {
        const response = await fetch(SITE.replace(/\/+$/, '') + '/api/pay.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
            body: JSON.stringify({
                phone: phone,
                amount: parseInt(amount),
                videoID: videoID,
                name: window.currentCheckoutTitle,
                token: <?= json_encode($store_api_key) ?> || ''
            })
        });

        const data = await response.json();
        if (data.success) {
            payBtn.innerHTML = 'ANGALIA SIMU YAKO...';
            pollStatus(data.transaction_id);
        } else {
            alert(data.message || 'Hitilafu imetokea.');
            resetPayButtonUniversal();
        }
    } catch (e) {
        alert('Kuna tatizo la mtandao.');
        resetPayButtonUniversal();
    }
}

function submitPayment() { processPayment(); } 

function pollStatus(transactionId) {
    if (paymentCheckInterval) clearInterval(paymentCheckInterval);
    const payBtn = document.querySelector('.btn-full') || document.querySelector('.btn-neon') || document.querySelector('.pay-btn-final') || document.getElementById('payBtn') || document.querySelector('.pay-btn');
    
    paymentCheckInterval = setInterval(async () => {
        try {
            const token = <?= json_encode($store_api_key) ?> || '';
            const query = new URLSearchParams({ tran_id: transactionId, token: token, _: new Date().getTime() }).toString();
            const res = await fetch(SITE.replace(/\/+$/, '') + '/api/check_status.php?' + query);
            const data = await res.json();
            
            const s = (data.status || '').toLowerCase();
            const rs = (data.raw_status || '').toLowerCase();

            if (s === 'success' || s === 'completed' || rs === 'success' || rs === 'completed') {
                clearInterval(paymentCheckInterval);
                payBtn.innerHTML = 'IMEKUBALIWA! INAFUNGUA...';
                setTimeout(() => {
                    window.location.href = <?= json_encode($store_redirect_url) ?>; 
                }, 1500);
            } else if (s === 'failed' || s === 'cancelled') {
                clearInterval(paymentCheckInterval);
                alert('Malipo yameshindwa (' + (data.raw_status || s) + ')');
                resetPayButtonUniversal();
            }
        } catch(e) {}
    }, 5000);
}

function resetPayButtonUniversal() {
    const payBtn = document.querySelector('.btn-full') || document.querySelector('.btn-neon') || document.querySelector('.pay-btn-final') || document.getElementById('payBtn') || document.querySelector('.pay-btn');
    if(payBtn && window.originalBtnHtml) {
        payBtn.innerHTML = window.originalBtnHtml;
        payBtn.disabled = false;
    }
}

document.querySelectorAll('.modal-close, .fa-times').forEach(el => {
    el.addEventListener('click', closeModalUniversal);
});
</script>
JS;

function processHtmlFile($id, $html, $php_header, $universal_js) {
    // Basic setup from earlier
    $html = str_replace('../cdnjs.cloudflare.com', 'https://cdnjs.cloudflare.com', $html);
    $html = preg_replace('/<title>.*?<\/title>/s', '<title><?= htmlspecialchars($landing_title) ?> | Premium</title>', $html);

    // Strip out all old scripts at bottom
    $html = preg_replace('/<script>[\s\S]*?<\/script>/', '', $html);
    $html = preg_replace('/<script defer.*?<\/script>/', '', $html);

    // Dynamic Loop Builder based on specific template structure
    if ($id == 2) {
        // Find grid
        $parts = explode('<div class="movie-grid">', $html);
        $top = $parts[0] . '<div class="movie-grid">' . "\n";
        $loop = <<<'PHP'
            <?php foreach ($videos as $vid): ?>
            <div class="movie-card" onclick="openPaymentModal(null, '<?= (int)$vid['price'] ?>', '<?= htmlspecialchars($vid['id']) ?>')">
                <div class="card-thumb">
                    <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: SITE_URL.'/assets/placeholder.jpg') ?>" alt="">
                    <span class="badge-premium">PREMIUM</span>
                </div>
                <div class="card-info">
                    <h3><?= htmlspecialchars($vid['title']) ?></h3>
                    <p><?= number_format($vid['views'] ?? rand(50, 500)) ?> views • Just added</p>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </main>
PHP;
        // Strip everything between the grid and modal
        // Find modal
        preg_match('/<div class="modal-overlay" id="paymentModal">[\s\S]*?<\/div>\s*<\/div>/', $html, $m);
        $modalHtml = $m[0] ?? '';

        // Hero 
        $hero = <<<'PHP'
    <?php if ($featured): ?>
    <header class="hero" style="background: linear-gradient(to right, var(--bg) 0%, rgba(15, 23, 30, 0.4) 50%, transparent 100%), linear-gradient(to top, var(--bg) 0%, transparent 20%), url('<?= htmlspecialchars($featured['thumbnail_url'] ?: SITE_URL.'/assets/landing4.jpg') ?>') center/cover;">
        <div class="hero-content">
            <h1 class="hero-title"><?= htmlspecialchars($featured['title']) ?></h1>
            <p class="hero-desc">Connections zote mpya hapa angalia</p>
        </div>
    </header>
    <?php else: ?>
    <header class="hero">
        <div class="hero-content">
            <h1 class="hero-title">Bongo Videos</h1>
            <p class="hero-desc">Connections zote mpya hapa angalia</p>
        </div>
    </header>
    <?php endif; ?>
PHP;
        $top = preg_replace('/<header class="hero">.*?<\/header>/s', $hero, $top);

        $final = str_replace('{ID}', '2', $php_header) . $top . $loop . "\n" . $modalHtml . "\n" . $universal_js . "\n</body>\n</html>";
        return $final;
    }

    if ($id == 3) {
        $parts = explode('<main class="feed-container">', $html);
        $top = $parts[0] . '<main class="feed-container">' . "\n";
        $loop = <<<'PHP'
            <?php foreach ($videos as $vid): ?>
            <div class="post-card" onclick="openPaymentSheet('<?= (int)$vid['price'] ?>', '<?= htmlspecialchars($vid['id']) ?>')">
                <div class="post-thumb">
                    <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: SITE_URL.'/assets/placeholder.jpg') ?>" alt="">
                    <span class="price-chip">TSH <?= number_format($vid['price']) ?></span>
                    <span class="floating-badge"><i class="fas fa-lock"></i></span>
                    <div class="post-overlay">
                        <h3 class="post-title"><?= htmlspecialchars($vid['title']) ?></h3>
                        <div class="post-stats">
                            <span><i class="fas fa-eye"></i> <?= number_format($vid['views'] ?? rand(500, 5000)) ?></span>
                            <span><i class="fas fa-heart"></i> <?= rand(50, 500) ?></span>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </main>
PHP;
        preg_match('/<div class="bottom-nav">[\s\S]*?<\/div>\s*<\/div>/', $html, $m_nav); // doesn't matter, we can just grab everything from bottom nav down
        $bottom_start = strpos($html, '<div class="bottom-nav">');
        $bottom_html = substr($html, $bottom_start);
        
        $final = str_replace('{ID}', '3', $php_header) . $top . $loop . "\n" . $bottom_html . "\n" . $universal_js . "\n</body>\n</html>";
        return $final;
    }

    if ($id == 4) {
        $parts = explode('<div class="neon-grid">', $html);
        $top = $parts[0] . '<div class="neon-grid">' . "\n";
        $loop = <<<'PHP'
            <?php foreach ($videos as $vid): ?>
            <div class="neon-card" onclick="openCyberModal('<?= (int)$vid['price'] ?>', '<?= htmlspecialchars($vid['id']) ?>')">
                <div class="card-inner">
                    <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: SITE_URL.'/assets/placeholder.jpg') ?>" alt="">
                    <div style="position: absolute; top: 15px; left: 15px; background: rgba(0,0,0,0.8); padding: 5px 12px; border-radius: 8px; font-size: 0.7rem;">
                        4K HDR
                    </div>
                </div>
                <div class="card-meta">
                    <div>
                        <h3 style="font-size: 1rem; margin-bottom: 5px;"><?= htmlspecialchars($vid['title']) ?></h3>
                    </div>
                    <div class="lock-shield">
                        <i class="fas fa-fingerprint"></i>
                    </div>
                </div>
                <div style="position: absolute; bottom: -10px; left: 50%; transform: translateX(-50%); background: var(--neon-pink); font-size: 0.6rem; padding: 4px 15px; border-radius: 4px; font-weight: 800;">
                    <?= number_format($vid['price']) ?> TSH
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </main>
PHP;
        // Hero
        $hero = <<<'PHP'
        <?php if ($featured): ?>
        <section class="spotlight">
            <div class="spotlight-content">
                <span style="color: var(--neon-pink); font-weight: 700; font-size: 0.8rem; letter-spacing: 2px;">EXCLUSIVE PREMIERE</span>
                <h1 style="font-size: 3rem; font-family: 'Syncopate'; margin: 10px 0 20px;"><?= htmlspecialchars($featured['title']) ?></h1>
                <button class="btn-neon" onclick="openCyberModal('<?= (int)$featured['price'] ?>', '<?= htmlspecialchars($featured['id']) ?>'); return false;">UNLOCK ACCESS - <?= number_format($featured['price']) ?> TSH</button>
            </div>
            <div class="spotlight-visual" style="background: url('<?= htmlspecialchars($featured['thumbnail_url'] ?: SITE_URL.'/assets/landing3.jpg') ?>') center/cover;"></div>
        </section>
        <?php else: ?>
        <section class="spotlight">
            <div class="spotlight-content">
                <span style="color: var(--neon-pink); font-weight: 700; font-size: 0.8rem; letter-spacing: 2px;">EXCLUSIVE PREMIERE</span>
                <h1 style="font-size: 3rem; font-family: 'Syncopate'; margin: 10px 0 20px;">BONGO LEAKS</h1>
                <button class="btn-neon">UNLOCK ACCESS NOW</button>
            </div>
            <div class="spotlight-visual"></div>
        </section>
        <?php endif; ?>
PHP;
        $top = preg_replace('/<section class="spotlight">.*?<\/section>/s', $hero, $top);
        
        $bottom_start = strpos($html, '<div class="modal-overlay" id="paymentModal">');
        $bottom_html = substr($html, $bottom_start);

        $final = str_replace('{ID}', '4', $php_header) . $top . $loop . "\n" . $bottom_html . "\n" . $universal_js . "\n</body>\n</html>";
        return $final;
    }

    if ($id == 5) {
        $parts = explode('<div class="video-list">', $html);
        $top = $parts[0] . '<div class="video-list">' . "\n";
        $loop = <<<'PHP'
            <?php foreach ($videos as $vid): ?>
            <div class="video-row" onclick="openSheet('<?= (int)$vid['price'] ?>', '<?= htmlspecialchars($vid['id']) ?>')">
                <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: SITE_URL.'/assets/placeholder.jpg') ?>" class="video-img" alt="Video">
                <div class="video-info">
                    <div>
                        <h3><?= htmlspecialchars($vid['title']) ?></h3>
                        <span class="price-chip">TSH <?= number_format($vid['price']) ?></span>
                    </div>
                    <div class="stats">
                        <i class="fas fa-eye"></i> <?= number_format($vid['views'] ?? rand(10,100)) ?> • <i class="fas fa-clock"></i> Leo
                    </div>
                </div>
                <div style="display: flex; align-items: center;">
                    <i class="fas fa-chevron-right" style="color: #333;"></i>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
PHP;
        // Hero
        $hero = <<<'PHP'
    <?php if ($featured): ?>
    <div class="promo-banner" onclick="openSheet('<?= (int)$featured['price'] ?>', '<?= htmlspecialchars($featured['id']) ?>');" style="cursor: pointer;">
        <span class="badge-live">HOT NEW</span>
        <h2 style="margin-top: 10px;"><?= htmlspecialchars($featured['title']) ?></h2>
        <p>Watch full exclusive leaks.</p>
        <button style="background: white; color: black; border: none; padding: 8px 15px; border-radius: 6px; font-weight: 800; font-size: 0.7rem; pointer-events: none;">ANGALIA TSH <?= number_format($featured['price']) ?></button>
    </div>
    <?php endif; ?>
PHP;
        $top = preg_replace('/<div class="promo-banner">.*?<\/div>/s', $hero, $top);

        $bottom_start = strpos($html, '<div class="bottom-nav">');
        $bottom_html = substr($html, $bottom_start);

        $final = str_replace('{ID}', '5', $php_header) . $top . $loop . "\n" . $bottom_html . "\n" . $universal_js . "\n</body>\n</html>";
        return $final;
    }

    if ($id == 6) {
        $parts = explode('<div class="movie-grid">', $html);
        $top = $parts[0] . '<div class="movie-grid">' . "\n";
        $loop = <<<'PHP'
            <?php foreach ($videos as $vid): ?>
            <div class="movie-card" data-id="<?= htmlspecialchars($vid['id']) ?>" data-title="<?= htmlspecialchars($vid['title']) ?>"
                data-price="<?= (int)$vid['price'] ?>"
                onclick="handleVideoClick(this, false, '')">
                <div class="card-poster">
                    <video playsinline poster="<?= htmlspecialchars($vid['thumbnail_url'] ?: SITE_URL.'/assets/placeholder.jpg') ?>"></video>
                    <div class="card-badges">
                        <span class="badge badge-new">PREMIUM</span>
                        <span class="badge badge-hd">HD</span>
                    </div>
                    <div class="preview-timer" style="display: block;">Lipia ku-play full video</div>
                    <span class="card-price">TSH <?= number_format($vid['price']) ?></span>
                </div>
                <div class="card-info">
                    <h3><?= htmlspecialchars($vid['title']) ?></h3>
                    <p><?= rand(10, 100) ?> views • <i class="fas fa-star" style="color:#ffd700;font-size:0.7rem;"></i> 9.8</p>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
PHP;
        // Hero
        $hero = <<<'PHP'
    <?php if ($featured): ?>
    <section class="hero" style="background: linear-gradient(to right, rgba(0, 0, 0, 0.7) 0%, rgba(0, 0, 0, 0.3) 50%, rgba(0, 0, 0, 0.1) 100%), linear-gradient(to top, #141414 0%, transparent 30%), url('<?= htmlspecialchars($featured['thumbnail_url'] ?: SITE_URL.'/assets/landing2.jpg') ?>') center/cover no-repeat; background-color: #141414;">
        <div class="hero-content">
            <span class="hero-tag">#1 IN TRENDING</span>
            <h1 class="hero-title"><?= htmlspecialchars($featured['title']) ?></h1>
            <div class="hero-meta">
                <span class="match">99% Match</span>
                <span class="year">2024</span>
                <span class="rating">18+</span>
                <span class="duration">1h 24m</span>
                <span style="border: 1px solid #aaa; padding: 0 4px; border-radius: 2px;">HD</span>
            </div>
            <p class="hero-desc">Watch the most trending piece and unreleased scenes globally. Action, Drama and more...</p>
            <div class="hero-buttons">
                <button class="btn btn-white" onclick="document.querySelector('.movie-card').click(); return false;">
                    <i class="fas fa-play"></i> Unlock TSH <?= number_format($featured['price']) ?>
                </button>
            </div>
        </div>
        <div class="hero-fade"></div>
    </section>
    <?php endif; ?>
PHP;
        $top = preg_replace('/<section class="hero".*?<\/section>/s', $hero, $top);

        $bottom_start = strpos($html, '<!-- Footer -->');
        $bottom_html = substr($html, $bottom_start);

        $final = str_replace('{ID}', '6', $php_header) . $top . $loop . "\n" . $bottom_html . "\n" . $universal_js . "\n</body>\n</html>";
        return $final;
    }
}

for ($i = 2; $i <= 6; $i++) {
    $html = file_get_contents("$landingpages_dir/landing$i.html");
    $res = processHtmlFile($i, $html, $php_header, $universal_js);
    file_put_contents("$templates_dir/landing$i.php", $res);
    echo "Rebuilt templates/landing$i.php\n";
}

