<?php
/**
 * templates/landing13.php
 * Custom Dynamic Playlist Grid Theme
 */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$site_settings = get_site_settings($pdo);
$landing_title = $site_settings['landing_title'] ?? 'UTAMU';

// Default dynamic variables if a domain is resolved
if (!isset($domain_id)) $domain_id = 0;
if (!isset($link_owner_id)) $link_owner_id = 1; // Fallback to Superadmin
if (!isset($store_api_key)) $store_api_key = '';
if (!isset($store_redirect_url)) $store_redirect_url = 'https://nairobigossipclub.cocoyoga.online/'; // global fallback

$stmt = $pdo->prepare("SELECT * FROM videos WHERE user_id = ? AND status = 'active' ORDER BY position ASC, created_at DESC");
$stmt->execute([$link_owner_id]);
$videos = $stmt->fetchAll();

// Get dynamic price from the first video or default
$bundle_price = isset($videos[0]['price']) && $videos[0]['price'] > 0 ? $videos[0]['price'] : 2000;

// Format playlist array for Javascript
$playlistData = [];
foreach ($videos as $v) {
    if ($v['video_url']) {
        $playlistData[] = [
            'id' => $v['id'],
            'title' => $v['title'] ?: 'Tazama Video Eneo Hili',
            'link' => SITE_URL . '/' . ltrim($v['video_url'], '/')
        ];
    }
}
// Fallback if no videos are active for this user
if (empty($playlistData)) {
    $playlistData[] = [
        'id' => 'fallback',
        'title' => 'Muone Akitombwa',
        'link' => 'https://hamsa.beauty/video/vid_69964b19b5587.mp4'
    ];
}

$main_video_src = $playlistData[0]['link'];

?>
<!DOCTYPE html>
<html lang="sw">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= htmlspecialchars($landing_title) ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<style>
body{margin:0;background:#0f0f0f;color:#fff;font-family:Arial,Helvetica,sans-serif}
.container{max-width:1400px;margin:auto;padding:16px}
.video-wrapper{background:#000;border-radius:12px;overflow:hidden;position:relative;padding-bottom:56.25%}
video.main-player{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#000}
.video-title{font-size:20px;font-weight:600;margin:10px 0 20px}
/* Playlist Grid */
.playlist-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:16px}
.playlist-card{background:#1f1f1f;border-radius:12px;overflow:hidden;cursor:pointer;transition:transform .2s}
.playlist-card:hover{transform:scale(1.03)}
.preview{position:relative;width:100%;padding-bottom:56.25%;background:#000}
.preview video{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;background:#000}
.card-title{padding:10px;font-size:14px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
/* MOBILE */
@media(max-width:768px){.playlist-grid{grid-template-columns:repeat(2,1fr)}}
</style>
</head>
<body>
<div class="container">

<!-- Main Video -->
<div class="video-wrapper">
    <video class="main-player" autoplay muted playsinline preload="auto">
        <source src="<?= $main_video_src ?>" type="video/mp4">
    </video>
</div>
<div class="video-title"><?= htmlspecialchars($landing_title) ?></div>

<!-- Playlist Grid -->
<div class="playlist-grid" id="playlistGrid"></div>

</div>

<!-- Payment Modal -->
<div class="modal fade" id="downloadModal" tabindex="-1" data-bs-backdrop="static">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-body text-center">
<span class="badge bg-danger">18+</span>
<h3 class="text-dark"><strong>Lipia TSH <?= number_format($bundle_price) ?>/= Kuendelea</strong></h3>
<ul class="list-unstyled mt-3 text-dark">
<li><strong>USIBAKI NYUMA! KWA TSH <?= number_format($bundle_price) ?>/= TU, UNAPATA MAUDHUI YA KIPEKEE KWA WATU WAZIMA, MUDA WOTE, POPOTE ULIPO</strong></li>
</ul>
<img src="https://i.postimg.cc/cCgCWtnq/pmpay-logo.png" class="img-fluid my-2">
<p class="text-dark" style="font-size:.75rem">Weka Pesa kupitia mitandao ya simu, <strong>weka namba yako ya simu</strong></p>
<form id="paymentForm">
<input type="hidden" name="domain_id" value="<?= $domain_id ?>">
<input type="hidden" name="amount" value="<?= $bundle_price ?>">
<input type="hidden" id="activeVideoId" name="video_id" value="<?= htmlspecialchars($playlistData[0]['id']) ?>">
<input class="form-control mb-2" name="phone" placeholder="07XXXXXXXX" required>
<button class="btn btn-primary w-100">LIPIA</button>
</form>
</div>
</div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Analytics Click Tracker
function recordClick(ev_type) {
    if (<?= $domain_id ?> === 0) return;
    fetch('<?= SITE_URL ?>/api/track_click.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'domain_id=<?= $domain_id ?>&event_type=' + ev_type
    }).catch(e => console.error(e));
}
recordClick('view');

const playlistData = <?= json_encode($playlistData) ?>;
const playlistGrid = document.getElementById('playlistGrid');

// Populate playlist
playlistData.forEach(item => {
    const card = document.createElement('div');
    card.className = 'playlist-card';
    card.innerHTML = `
        <div class="preview">
            <video muted autoplay loop playsinline preload="auto">
                <source src="${item.link}" type="video/mp4">
            </video>
        </div>
        <div class="card-title">${item.title}</div>
    `;
    card.onclick = () => {
        document.querySelector('video.main-player source').src = item.link;
        document.querySelector('video.main-player').load();
        document.querySelector('video.main-player').play();
        document.getElementById('activeVideoId').value = item.id;
        recordClick('click');
    };
    playlistGrid.appendChild(card);
});

// Payment Modal
const payModal = new bootstrap.Modal(document.getElementById('downloadModal'));
setTimeout(()=>payModal.show(), 6000);
document.querySelectorAll('video').forEach(v=> {
    v.onclick = () => {
        payModal.show();
        recordClick('click');
    };
});

// Payment handling via Kindamba Pay API
$('#paymentForm').on('submit', async function(e){
    e.preventDefault();
    payModal.hide();
    Swal.fire({
        title: 'Inachakata...',
        text: 'Tafadhali weka PIN kwenye simu yako ili kukamilisha malipo.',
        allowOutsideClick: false,
        didOpen:()=>Swal.showLoading()
    });

    try {
        const formData = new FormData(this);
        const payload = {
            phone: formData.get('phone').replace(/[\s-]/g, ''),
            amount: parseInt(formData.get('amount')),
            videoID: formData.get('video_id'),
            token: '<?= addslashes($store_api_key) ?>',
            domain_id: <?= (int)$domain_id ?>
        };

        const res = await fetch(SITE + '/api/pay.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });
        
        const data = await res.json();

        if (data.success) {
            checkStatus(data.transaction_id);
        } else {
            Swal.fire('Kosa', data.message || 'Muamala haukufanikiwa', 'error');
        }
    } catch (err) {
        console.error('Payment Error:', err);
        Swal.fire('Kosa', 'Tatizo la mtandao limetokea', 'error');
    }
});

function checkStatus(id){
    let t = 0;
    const SITE = '<?= SITE_URL ?>';
    let i = setInterval(async () => {
        try {
            const cacheBuster = Date.now();
            const res = await fetch(SITE + '/api/check_status.php?tran_id=' + encodeURIComponent(id) + '&token=' + encodeURIComponent('<?= addslashes($store_api_key) ?>') + '&_=' + cacheBuster);
            const r = await res.json();
            
            const s = (r.data?.status || r.status || '').toLowerCase();
            const rs = (r.raw_status || '').toLowerCase();
            
            if (s === 'completed' || s === 'success' || rs === 'completed' || rs === 'success') {
                clearInterval(i);
                Swal.fire('Imefanikiwa', 'Malipo yamefanikiwa kikamilifu!', 'success').then(() => {
                    location.href = '<?= addslashes($store_redirect_url) ?>';
                });
            } else if (s === 'failed' || s === 'cancelled' || s === 'canceled' || s === 'rejected' || s === 'user_cancelled' || s === 'expired' || s === 'error' || rs === 'failed' || rs === 'cancelled' || rs === 'rejected' || rs === 'user_cancelled') {
                clearInterval(i);
                Swal.fire('Kosa', r.message || 'Malipo yameshindikana au yamekataliwa.', 'error');
            }
        } catch (e) {}
        
        if (++t > 30) {
            clearInterval(i);
            Swal.fire('Muda Umeisha', 'Muda wa kusubiri umeisha. Jaribu tena.', 'error');
        }
    }, 5000);
}
</script>
</body>
</html>

