<?php
// rebuild_landing3.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/landing3.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 closePaymentSheet() { 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') || document.querySelector('button[onclick="processPayment()"]');
    
    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') || document.querySelector('button[onclick="processPayment()"]');
    
    paymentCheckInterval = setInterval(async () => {
        try {
            const token = <?= json_encode($store_api_key) ?> || '';
            const query = new URLSearchParams({ tran_id: transactionId, token: token }).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') || document.querySelector('button[onclick="processPayment()"]');
    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;

$html = file_get_contents("$landingpages_dir/landing3.html");

// 1. Clean HTML
$html = str_replace('../cdnjs.cloudflare.com', 'https://cdnjs.cloudflare.com', $html);
$html = preg_replace('/<title>.*?<\/title>/s', '<title><?= htmlspecialchars($landing_title) ?> | Premium</title>', $html);
$html = preg_replace('/<script>[\s\S]*?<\/script>/', '', $html);
$html = preg_replace('/<script defer.*?<\/script>/', '', $html);

// We need to stop right after the FIRST </html> or basically not include duplicate doctypes
$parts = explode('<!DOCTYPE html>', $html);
if (count($parts) > 2) {
    // Only keep the first block of HTML
    $html = '<!DOCTYPE html>' . $parts[1]; 
}

// 2. Extract Top (before stories)
$parts_feed = explode('<div class="stories-container">', $html);
$top = $parts_feed[0] . '<div class="stories-container">' . "\n";

// 3. Dynamic Stories Loop (using top 8 videos)
$stories_loop = <<<'PHP'
    <?php foreach (array_slice($videos, 0, 8) as $vid): ?>
    <div class="story-item" onclick="openPaymentSheet('<?= (int)$vid['price'] ?>', '<?= htmlspecialchars($vid['id']) ?>')">
        <div class="story-circle">
            <img src="<?= htmlspecialchars($vid['thumbnail_url'] ?: SITE_URL.'/assets/placeholder.jpg') ?>" alt="">
        </div>
        <div class="story-label"><?= htmlspecialchars(substr($vid['title'], 0, 10)) ?>...</div>
    </div>
    <?php endforeach; ?>
</div>

<main class="feed-container">
PHP;

// 4. Dynamic Feed Loop
$feed_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;

// 5. Extract Bottom (Nav + Modal)
// Find the <nav class="bottom-nav">
$bottom_start = strpos($html, '<nav class="bottom-nav">');
$bottom_html = substr($html, $bottom_start);

$final = $php_header . $top . $stories_loop . "\n" . $feed_loop . "\n" . $bottom_html . "\n" . $universal_js . "\n</body>\n</html>";

file_put_contents("$templates_dir/landing3.php", $final);
echo "SUCCESS";

