<?php
$currentPage = basename($_SERVER['PHP_SELF'], '.php');
// Ensure getSetting is available
if(!function_exists('getSetting')) {
    require_once __DIR__ . '/config.php';
}
// Load site colors from DB
$_primary   = getSetting('color_primary')   ?: '#1a3c8f';
$_secondary = getSetting('color_secondary') ?: '#f5a623';
$_dark      = getSetting('color_dark')      ?: '#0d1f4e';
// Ensure SITE_NAME is defined
if(!defined('SITE_NAME')) {
    $__n = getSetting('site_name');
    define('SITE_NAME', $__n ?: 'Priyo Telecom');
}
$_siteParts = explode(' ', trim(SITE_NAME), 2);

// Auto-refresh pin session on each page load if still valid
if(!empty($_SESSION['pin_verified'])) {
    $_SESSION['pin_last_time'] = time(); // keep alive
}
?>
<style>
/* Dynamic site colors — override all pages */
:root{
    --primary:<?= $_primary ?> !important;
    --secondary:<?= $_secondary ?> !important;
    --dark:<?= $_dark ?> !important;
}
/* Bottom Nav */
.bottom-nav{position:fixed;bottom:0;left:0;right:0;background:white;border-top:1px solid #eef0f5;z-index:1000;padding-bottom:env(safe-area-inset-bottom)}
.bottom-nav-inner{display:flex;max-width:480px;margin:0 auto}
.nav-item{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:10px 4px 8px;text-decoration:none;color:#aaa;-webkit-tap-highlight-color:transparent;cursor:pointer}
.nav-item.active{color:<?= $_primary ?>}
.nav-item i{font-size:20px;margin-bottom:3px;display:block}
.nav-item span{font-size:10px;font-weight:600;line-height:1}

/* Page transition */
html,body{background:#f5f7fa !important}
@keyframes pgFadeIn{from{opacity:0}to{opacity:1}}
body{animation:pgFadeIn 0.3s ease both;}
body > *:not(.bottom-nav):not(#pgBar):not(#noInternetOverlay):not(#pgLoadOverlay):not(script):not(style){}

/* Loading overlay — 4 panels */
#pgLoadOverlay{
    position:fixed;inset:0;
    z-index:99998;
    display:flex;flex-direction:column;align-items:center;justify-content:center;
    pointer-events:none;
    opacity:0;
    transition:opacity 0.2s;
}
#pgLoadOverlay.show{ opacity:1; pointer-events:all; }

/* Water wave panels */
.pg-panel{ display:none; }

#pgWaveOverlay{
    position:fixed;inset:0;
    z-index:99997;
    pointer-events:none;
    opacity:0;
    transition:opacity 0.2s;
    backdrop-filter:blur(20px);
    -webkit-backdrop-filter:blur(20px);
    background:rgba(255,255,255,0.05);
}
#pgWaveOverlay.show{ opacity:1; pointer-events:all; }
#pgWaveOverlay.hide{ opacity:0; transition:opacity 0.5s 0.2s; }

.wave-svg{
    position:absolute;
    width:100%;height:100%;
}

/* Top wave */
#waveTop{
    top:0;left:0;
    transform:translateY(-100%);
    transition:transform 0.7s cubic-bezier(0.34,1.2,0.64,1);
}
#waveTop.show{ transform:translateY(0); }
#waveTop.hide{ transform:translateY(-100%); transition:transform 0.6s cubic-bezier(0.4,0,0.2,1) 0.1s; }

/* Bottom wave */
#waveBottom{
    bottom:0;left:0;
    transform:translateY(100%);
    transition:transform 0.7s cubic-bezier(0.34,1.2,0.64,1) 0.05s;
}
#waveBottom.show{ transform:translateY(0); }
#waveBottom.hide{ transform:translateY(100%); transition:transform 0.6s cubic-bezier(0.4,0,0.2,1) 0.05s; }

@keyframes waveMove{
    0%  { d:path("M0,40 C150,80 350,0 500,40 C650,80 850,0 1000,40 L1000,0 L0,0 Z"); }
    50% { d:path("M0,20 C150,60 350,10 500,20 C650,60 850,10 1000,20 L1000,0 L0,0 Z"); }
    100%{ d:path("M0,40 C150,80 350,0 500,40 C650,80 850,0 1000,40 L1000,0 L0,0 Z"); }
}

/* Center content on top */
.pg-loader-wrap{
    position:relative;z-index:99999;
    display:flex;align-items:center;justify-content:center;
}
/* Spinning ring */
.pg-ring{
    position:absolute;
    width:120px;height:120px;
    border-radius:50%;
    border:3px solid transparent;
    border-top-color:<?= $_primary ?>;
    border-right-color:<?= $_primary ?>55;
    animation:pgSpin 1s linear infinite;
}
.pg-ring-2{
    position:absolute;
    width:100px;height:100px;
    border-radius:50%;
    border:2px solid transparent;
    border-bottom-color:<?= $_secondary ?>;
    border-left-color:<?= $_secondary ?>55;
    animation:pgSpin 1.5s linear infinite reverse;
}
@keyframes pgSpin{ to{ transform:rotate(360deg); } }
#pgLoadOverlay .app-logo{
    font-size:24px;font-weight:800;color:<?= $_dark ?>;letter-spacing:1px;
    position:relative;z-index:99999;text-align:center;
}
#pgLoadOverlay .app-logo span{color:<?= $_primary ?>}

/* Top progress bar */
#pgBar{position:fixed;top:0;left:0;right:0;height:3px;z-index:99999;pointer-events:none;background:linear-gradient(90deg,<?= $_dark ?>,<?= $_secondary ?>,<?= $_primary ?>);transform:scaleX(0);transform-origin:left;transition:transform 0.3s ease;opacity:0}
#pgBar.show{opacity:1}

/* No Internet */
#noInternetOverlay{position:fixed;inset:0;background:#f5f7fa;z-index:99999;display:none;flex-direction:column;align-items:center;justify-content:center;padding:32px;text-align:center}
#noInternetOverlay.show{display:flex}
.no-net-icon{width:100px;height:100px;background:linear-gradient(135deg,#e8ecf4,#f5f7fa);border-radius:50%;display:flex;align-items:center;justify-content:center;margin-bottom:24px;position:relative}
.no-net-icon i{font-size:44px;color:#c5cdd8}
.no-net-icon:after{content:'!';position:absolute;bottom:2px;right:2px;width:26px;height:26px;background:#e53e3e;color:white;border-radius:50%;font-size:14px;font-weight:900;display:flex;align-items:center;justify-content:center;border:3px solid #f5f7fa}
.retry-btn{background:linear-gradient(135deg,<?= $_dark ?>,<?= $_primary ?>);color:white;border:none;padding:16px 40px;border-radius:50px;font-size:15px;font-weight:800;cursor:pointer;display:flex;align-items:center;gap:10px}
@keyframes pgSpin{to{transform:rotate(360deg)}}
/* PIN Lock Screen */
#pinLock{
    position:fixed;inset:0;z-index:999999;
    background:linear-gradient(135deg,<?= $_dark ?>,<?= $_primary ?>);
    display:flex;flex-direction:column;align-items:center;justify-content:center;
    padding:30px 24px;
    opacity:0;pointer-events:none;
    transition:opacity 0.3s ease;
}
#pinLock.show{opacity:1;pointer-events:all;}
.pin-avatar{width:70px;height:70px;background:rgba(255,255,255,0.15);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:28px;margin-bottom:12px;backdrop-filter:blur(10px);}
.pin-name{font-size:18px;font-weight:800;color:white;margin-bottom:4px;}
.pin-subtitle{font-size:13px;color:rgba(255,255,255,0.6);margin-bottom:32px;}
.pin-dots{display:flex;gap:14px;margin-bottom:32px;}
.pin-dot{width:14px;height:14px;border-radius:50%;border:2px solid rgba(255,255,255,0.5);transition:0.2s;}
.pin-dot.filled{background:white;border-color:white;}
.pin-dot.error{background:#ff6b6b;border-color:#ff6b6b;animation:pinShake 0.4s ease;}
@keyframes pinShake{0%,100%{transform:translateX(0)}25%{transform:translateX(-5px)}75%{transform:translateX(5px)}}
.pin-pad{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;width:240px;}
.pin-btn{height:64px;background:rgba(255,255,255,0.12);border:none;border-radius:16px;font-size:22px;font-weight:700;color:white;cursor:pointer;transition:0.15s;backdrop-filter:blur(8px);}
.pin-btn:active{background:rgba(255,255,255,0.25);transform:scale(0.95);}
.pin-btn.del{font-size:18px;}
.pin-btn.empty{visibility:hidden;}
.pin-error{font-size:12px;color:#ff9f9f;margin-bottom:12px;min-height:18px;text-align:center;}
.pin-logout{color:rgba(255,255,255,0.5);font-size:13px;margin-top:20px;cursor:pointer;text-decoration:underline;}
</style>

<!-- Water wave overlay -->
<div id="pgWaveOverlay">
    <!-- Top wave -->
    <svg id="waveTop" viewBox="0 0 1000 600" preserveAspectRatio="none" style="position:absolute;top:0;left:0;width:100%;height:55%">
    <defs>
            <filter id="blur1"><feGaussianBlur stdDeviation="20"/></filter>
        </defs>
        <path id="wavePathTop" fill="rgba(255,255,255,0.35)" filter="url(#blur1)"
            d="M0,520 C200,480 400,560 600,520 C800,480 900,540 1000,520 L1000,0 L0,0 Z"/>
        <path id="wavePathTop2" fill="rgba(255,255,255,0.25)"
            d="M0,540 C250,500 450,570 700,535 C850,510 950,550 1000,540 L1000,0 L0,0 Z"/>
    </svg>
    <!-- Bottom wave -->
    <svg id="waveBottom" viewBox="0 0 1000 600" preserveAspectRatio="none" style="position:absolute;bottom:0;left:0;width:100%;height:55%">
        <path id="wavePathBottom" fill="rgba(255,255,255,0.2)" filter="url(#blur1)"
            d="M0,80 C200,120 400,40 600,80 C800,120 900,60 1000,80 L1000,600 L0,600 Z"/>
        <path id="wavePathBottom2" fill="rgba(255,255,255,0.12)"
            d="M0,60 C250,100 450,30 700,65 C850,90 950,50 1000,60 L1000,600 L0,600 Z"/>
    </svg>
</div>

<!-- 4 blur panels (hidden, replaced by wave) -->
<div class="pg-panel" id="pgPanelTop"></div>
<div class="pg-panel" id="pgPanelBottom"></div>
<div class="pg-panel" id="pgPanelLeft"></div>
<div class="pg-panel" id="pgPanelRight"></div>

<!-- Center loader -->
<div id="pgLoadOverlay">
    <div class="pg-loader-wrap">
        <div class="pg-ring"></div>
        <div class="pg-ring-2"></div>
        <div class="app-logo">
            <?= htmlspecialchars($_siteParts[0]) ?><?php if(isset($_siteParts[1])): ?><br><span><?= htmlspecialchars($_siteParts[1]) ?></span><?php endif; ?>
        </div>
    </div>
</div>

<!-- Progress bar -->
<div id="pgBar"></div>

<!-- No Internet -->
<div id="noInternetOverlay">
    <div class="no-net-icon"><i class="fas fa-wifi"></i></div>
    <div style="font-size:22px;font-weight:800;color:#1a1a2e;margin-bottom:10px">No Internet</div>
    <div style="font-size:14px;color:#888;line-height:1.7;margin-bottom:30px">WiFi বা Mobile Data চালু করুন</div>
    <button class="retry-btn" onclick="retryNet()">
        <i class="fas fa-redo" id="retryIcon"></i> আবার চেষ্টা করুন
    </button>
</div>

<!-- PIN Lock Screen -->
<?php
$pinRow2 = null;
try {
    if(isset($user) && $user) {
        $s2 = $db->prepare("SELECT is_enabled FROM user_pins WHERE user_id=? LIMIT 1");
        $s2->execute([$user['id']]); $pinRow2 = $s2->fetch();
    }
} catch(Exception $e){}
$pinEnabled = $pinRow2 && $pinRow2['is_enabled'];
$userName = isset($user) ? ($user['name'] ?? 'User') : 'User';
?>
<div id="pinLock">
    <div class="pin-avatar">👤</div>
    <div class="pin-name"><?= htmlspecialchars($userName) ?></div>
    <div class="pin-subtitle">Enter your PIN</div>
    <div class="pin-dots">
        <div class="pin-dot" id="pd0"></div>
        <div class="pin-dot" id="pd1"></div>
        <div class="pin-dot" id="pd2"></div>
        <div class="pin-dot" id="pd3"></div>
    </div>
    <div class="pin-error" id="pinError"></div>
    <div class="pin-pad">
        <?php foreach([1,2,3,4,5,6,7,8,9,'','0','⌫'] as $k): ?>
        <button class="pin-btn <?= $k===''?'empty':($k==='⌫'?'del':'') ?>"
            onclick="<?= $k==='⌫'?'pinDel()':($k!==''?'pinPress('.$k.')':'')?>"><?= $k ?></button>
        <?php endforeach; ?>
    </div>
    <div class="pin-logout" onclick="if(confirm('Logout?')) location.href='logout.php'">Logout</div>
</div>

<!-- Bottom Nav -->
<div class="bottom-nav">
    <div class="bottom-nav-inner">
        <a href="history.php" class="nav-item <?= $currentPage==='history'?'active':'' ?>">
            <i class="fas fa-history"></i><span>History</span>
        </a>
        <a href="international.php" class="nav-item <?= $currentPage==='international'?'active':'' ?>">
            <i class="fas fa-globe"></i><span>Intl</span>
        </a>
        <a href="dashboard.php" class="nav-item <?= $currentPage==='dashboard'?'active':'' ?>">
            <div style="width:50px;height:50px;background:linear-gradient(135deg,<?= $_dark ?>,<?= $_primary ?>);border-radius:50%;display:flex;align-items:center;justify-content:center;margin-bottom:2px;margin-top:-18px;box-shadow:0 4px 15px <?= $_primary ?>88">
                <i class="fas fa-home" style="color:white;font-size:20px;margin:0"></i>
            </div>
            <span style="color:<?= $currentPage==='dashboard'?'var(--primary)':'#aaa' ?>;font-weight:700">Home</span>
        </a>
        <a href="cards.php" class="nav-item <?= $currentPage==='cards'?'active':'' ?>">
            <i class="fas fa-credit-card"></i><span>Cards</span>
        </a>
        <a href="topup.php" class="nav-item <?= $currentPage==='topup'?'active':'' ?>">
            <i class="fas fa-mobile-alt"></i><span>Topup</span>
        </a>
    </div>
</div>

<script>
// ── Page enter animation ──
// CSS handles it via body > * animation

// ── Progress bar ──
const pgBar = document.getElementById('pgBar');
function pgShow(){ pgBar.classList.add('show'); pgBar.style.transform='scaleX(0.7)'; setTimeout(()=>pgBar.style.transform='scaleX(0.9)',400); }
function pgHide(){ pgBar.style.transform='scaleX(1)'; setTimeout(()=>{ pgBar.classList.remove('show'); pgBar.style.transform='scaleX(0)'; },300); }
window.addEventListener('load', pgHide);
window.addEventListener('pageshow', pgHide);

const pgOverlay  = document.getElementById('pgLoadOverlay');
const pgWave     = document.getElementById('pgWaveOverlay');
const waveTop    = document.getElementById('waveTop');
const waveBottom = document.getElementById('waveBottom');
const pgPanels   = ['pgPanelTop','pgPanelBottom','pgPanelLeft','pgPanelRight'].map(id=>document.getElementById(id));
const __fl = document.getElementById('__fl');
if(__fl) __fl.remove();

// Animate wave paths
let waveAnim = null;
function startWave(){
    const paths = [
        document.getElementById('wavePathTop'),
        document.getElementById('wavePathTop2'),
        document.getElementById('wavePathBottom'),
        document.getElementById('wavePathBottom2'),
    ];
    let t = 0;
    waveAnim = setInterval(()=>{
        t += 0.04;
        const s = Math.sin(t) * 20;
        const s2 = Math.sin(t + 1) * 15;
        if(paths[0]) paths[0].setAttribute('d',`M0,${520+s} C200,${480-s} 400,${560+s2} 600,${520+s} C800,${480-s2} 900,${540+s} 1000,${520-s} L1000,0 L0,0 Z`);
        if(paths[1]) paths[1].setAttribute('d',`M0,${540+s2} C250,${500-s} 450,${570+s} 700,${535-s2} C850,${510+s} 950,${550-s} 1000,${540+s2} L1000,0 L0,0 Z`);
        if(paths[2]) paths[2].setAttribute('d',`M0,${80-s} C200,${120+s} 400,${40-s2} 600,${80+s} C800,${120-s} 900,${60+s2} 1000,${80-s} L1000,600 L0,600 Z`);
        if(paths[3]) paths[3].setAttribute('d',`M0,${60-s2} C250,${100+s} 450,${30-s} 700,${65+s2} C850,${90-s} 950,${50+s} 1000,${60-s2} L1000,600 L0,600 Z`);
    }, 30);
}
function stopWave(){ if(waveAnim){ clearInterval(waveAnim); waveAnim=null; } }

function showLoader(){
    pgWave.classList.remove('hide'); pgWave.classList.add('show');
    waveTop.classList.add('show'); waveBottom.classList.add('show');
    pgOverlay.classList.add('show');
    startWave();
}
function hideLoader(){
    // First show content (make pgWave transparent but keep wave visible briefly)
    pgOverlay.classList.remove('show');
    // Then animate wave out after short delay
    setTimeout(()=>{
        stopWave();
        waveTop.classList.remove('show'); waveTop.classList.add('hide');
        waveBottom.classList.remove('show'); waveBottom.classList.add('hide');
        pgWave.style.pointerEvents='none';
        setTimeout(()=>{
            pgWave.classList.remove('show','hide');
            pgWave.style.pointerEvents='';
            waveTop.classList.remove('hide');
            waveBottom.classList.remove('hide');
        }, 700);
    }, 300);
}
window.addEventListener('load', function(){
    requestAnimationFrame(()=>{ requestAnimationFrame(()=>{ hideLoader(); }); });
});
window.addEventListener('pageshow', function(e){ if(e.persisted) hideLoader(); });
window.pageReady = function(){};

// ── Navigation ──
let leaving = false;

function goTo(href) {
    if (leaving) return;
    leaving = true;
    showLoader();
    setTimeout(()=>{ window.location.href = href; }, 150);
}

// Intercept clicks on links
document.addEventListener('click', function(e) {
    const a = e.target.closest('a[href]');
    if (!a) return;
    const href = a.getAttribute('href');
    if (!href || href === '#' || href.startsWith('javascript') || href.startsWith('mailto') || href.startsWith('tel')) return;
    if (a.target === '_blank') return;
    if (href.startsWith('http') && !href.includes(window.location.hostname)) return;
    // Don't intercept if inside a form with submit button
    if (e.target.closest('form') && e.target.type === 'submit') return;
    e.preventDefault();
    goTo(href);
}, true); // use capture to catch all

// Form submits — prevent double submit + show overlay
document.addEventListener('submit', function(e) {
    const form = e.target;
    if (form.dataset.submitting === '1') { e.preventDefault(); return; }
    form.dataset.submitting = '1';
    showLoader();
    setTimeout(() => { delete form.dataset.submitting; }, 10000);
});

// ── No Internet ──
function retryNet() {
    const icon = document.getElementById('retryIcon');
    icon.style.animation = 'pgSpin 0.7s linear infinite';
    setTimeout(() => {
        icon.style.animation = '';
        if (navigator.onLine) { document.getElementById('noInternetOverlay').classList.remove('show'); location.reload(); }
    }, 1000);
}
window.addEventListener('offline', () => document.getElementById('noInternetOverlay').classList.add('show'));
window.addEventListener('online',  () => document.getElementById('noInternetOverlay').classList.remove('show'));
if (!navigator.onLine) document.getElementById('noInternetOverlay').classList.add('show');

// ── PIN Lock System ──
const PIN_TIMEOUT = 5 * 60 * 1000; // 5 minutes
const pinLock     = document.getElementById('pinLock');
let pinEnabled    = <?= $pinEnabled ? 'true' : 'false' ?>;
let pinVerified   = <?= !empty($_SESSION['pin_verified']) ? 'true' : 'false' ?>;
const PIN_BASE    = '<?= defined('SITE_URL') ? SITE_URL.'/pin.php' : '/telecom/pin.php' ?>';let pinInput      = '';

function pinPress(n){
    if(pinInput.length >= 4) return;
    pinInput += n;
    updatePinDots();
    if(pinInput.length === 4) setTimeout(verifyPin, 100);
}
function pinDel(){
    pinInput = pinInput.slice(0,-1);
    updatePinDots();
    document.getElementById('pinError').textContent='';
    document.querySelectorAll('.pin-dot').forEach(d=>d.classList.remove('error'));
}
function updatePinDots(){
    for(let i=0;i<4;i++){
        document.getElementById('pd'+i).classList.toggle('filled', i < pinInput.length);
        document.getElementById('pd'+i).classList.remove('error');
    }
}
function verifyPin(){
    const fd = new FormData();
    fd.append('action','verify');
    fd.append('pin', pinInput);
    fetch(PIN_BASE,{method:'POST',body:fd})
    .then(r=>r.json()).then(d=>{
        if(d.ok){
            pinLock.classList.remove('show');
            pinVerified = true;
        } else if(d.logout){
            location.href='logout.php';
        } else {
            document.querySelectorAll('.pin-dot').forEach(d=>d.classList.add('error'));
            document.getElementById('pinError').textContent = d.message || 'Wrong PIN';
            pinInput = '';
            setTimeout(()=>{ updatePinDots(); document.getElementById('pinError').textContent=''; }, 800);
        }
    });
}
function showPinLock(){
    if(!pinEnabled) return;
    pinInput = '';
    updatePinDots();
    document.getElementById('pinError').textContent='';
    pinLock.classList.add('show');
}

// Show PIN only if not verified — skip if in iframe (preload)
if(pinEnabled && !pinVerified && window.self === window.top){
    showPinLock();
}

// Lock only after 5 min background — not on every tab switch
let _hiddenAt = 0;
document.addEventListener('visibilitychange',()=>{
    if(document.hidden){
        _hiddenAt = Date.now();
    } else if(pinEnabled && _hiddenAt > 0){
        if((Date.now() - _hiddenAt) > 5*60*1000){
            fetch(PIN_BASE,{method:'POST',body:new URLSearchParams({action:'lock'})})
            .then(()=>{ location.reload(); });
        }
        _hiddenAt = 0;
    }
});

// PWA Service Worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/telecom/sw.js').catch(()=>{});
}
</script>

