<?php
require_once 'includes/config.php';
requireLogin();
$user = getCurrentUser();
$db = getDB();

// User's preferred secondary currency
$userCurrency = null;
try {
    if (!empty($user['preferred_currency']) && $user['preferred_currency'] !== 'BDT') {
        $stmt = $db->prepare("SELECT * FROM currencies WHERE code=? AND is_active=1");
        $stmt->execute([$user['preferred_currency']]);
        $userCurrency = $stmt->fetch() ?: null;
    }
} catch(Exception $e) { $userCurrency = null; }

$balanceBDT = floatval($user['balance']);
$balanceConverted = ($userCurrency && floatval($userCurrency['rate']) > 0)
    ? round($balanceBDT * floatval($userCurrency['rate']), 2) : null;

$txns = $db->prepare("SELECT t.*, o.name as op_name FROM transactions t LEFT JOIN operators o ON t.operator_id=o.id WHERE t.user_id=? ORDER BY t.created_at DESC LIMIT 5");
$txns->execute([$user['id']]);
$transactions = $txns->fetchAll();

// Load banners
$banners = [];
try {
    $db->exec("CREATE TABLE IF NOT EXISTS banners (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200) DEFAULT '', subtitle VARCHAR(300) DEFAULT '', image VARCHAR(255) DEFAULT NULL, bg_color VARCHAR(50) DEFAULT 'linear-gradient(135deg,#1a3c8f,#2856c8)', pills TEXT DEFAULT NULL, link_url VARCHAR(255) DEFAULT NULL, is_active TINYINT(1) DEFAULT 1, sort_order INT DEFAULT 0) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    if($db->query("SELECT COUNT(*) FROM banners")->fetchColumn()==0) {
        $db->exec("INSERT INTO banners (title,subtitle,pills,sort_order) VALUES ('Recharge All Bangladesh Operators!','Complete recharge in just 5 seconds','Grameenphone,Robi,Banglalink,Teletalk',1)");
    }
    $banners = $db->query("SELECT * FROM banners WHERE is_active=1 ORDER BY sort_order,id")->fetchAll();
} catch(Exception $e) {}

// Service on/off settings (user-specific + global)
require_once 'includes/service_check.php';
$svcOn = getUserServices($user['id']);

$txnTotal = $db->prepare("SELECT COUNT(*) FROM transactions WHERE user_id=?");
$txnTotal->execute([$user['id']]);
$txnTotal = $txnTotal->fetchColumn();

$notifs = $db->prepare("SELECT * FROM notifications WHERE (user_id=? OR is_global=1) AND is_read=0 ORDER BY created_at DESC LIMIT 5");
$notifs->execute([$user['id']]);
$notifications = $notifs->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Dashboard - <?= SITE_NAME ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        *{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
        :root{
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
        body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;color:#333;padding-bottom:85px}

        /* Header */
        .hdr{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px;position:sticky;top:0;z-index:100}
        .hdr-in{display:flex;align-items:center;justify-content:space-between;height:58px;max-width:480px;margin:0 auto}
        .menu-btn{background:none;border:none;color:white;font-size:20px;cursor:pointer;width:36px;height:36px;display:flex;align-items:center;justify-content:center}
        .hdr-logo{color:white;font-size:18px;font-weight:800}
        .hdr-logo span{color:var(--secondary)}
        .notif-btn{background:none;border:none;color:white;font-size:20px;cursor:pointer;position:relative;width:36px;height:36px;display:flex;align-items:center;justify-content:center}
        .notif-badge{position:absolute;top:2px;right:2px;background:#e53e3e;color:white;font-size:9px;width:15px;height:15px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:700}

        /* Ticker */
        .ticker-wrap{padding:14px 18px 0;max-width:480px;margin:0 auto}
        .ticker{background:white;border-radius:30px;padding:9px 16px;overflow:hidden;box-shadow:0 2px 10px rgba(26,60,143,0.10);border:1.5px solid #e8ecf4}
        .ticker-in{display:flex;align-items:center;gap:8px;overflow:hidden}
        .ticker-ic{color:var(--primary);font-size:12px;flex-shrink:0}
        .ticker-scroll{overflow:hidden;flex:1}
        .ticker span{font-size:12px;white-space:nowrap;animation:tick 25s linear infinite;color:var(--primary);font-weight:600;display:inline-block}
        @keyframes tick{0%{transform:translateX(100%)}100%{transform:translateX(-100%)}}

        /* Hero/Balance */
        .hero{background:linear-gradient(135deg,var(--dark),var(--primary));padding:18px 18px 40px;position:relative}
        .hero-in{max-width:480px;margin:0 auto}
        .bal-label{color:rgba(255,255,255,0.65);font-size:12px;font-weight:600;letter-spacing:0.5px;margin-bottom:4px}
        .bal-amount{color:white;font-size:34px;font-weight:800;margin-bottom:14px}
        .bal-card{background:rgba(255,255,255,0.12);border-radius:14px;padding:13px 16px;display:flex;align-items:center;justify-content:space-between}
        .bal-due-txt{color:rgba(255,255,255,0.8);font-size:13px}
        .add-btn{background:var(--secondary);color:var(--dark);border:none;padding:8px 18px;border-radius:10px;font-weight:700;font-size:13px;cursor:pointer}

        /* Main */
        .main{max-width:480px;margin:0 auto;padding:0 18px}

        /* Services */
        .sec{padding:18px 0 0}
        .sec-hdr{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px}
        .sec-title{font-size:15px;font-weight:800;color:var(--dark);border-left:4px solid var(--secondary);padding-left:10px}
        .see-more{color:var(--primary);font-size:13px;font-weight:600;text-decoration:none;cursor:pointer;background:none;border:none;display:flex;align-items:center;gap:4px}

        .services-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
        .extra-services{display:none;grid-template-columns:repeat(4,1fr);gap:10px;margin-top:10px}
        .extra-services.show{display:grid}
        .service-item{background:white;border-radius:14px;padding:14px 6px;text-align:center;box-shadow:0 2px 10px rgba(0,0,0,0.06);cursor:pointer;text-decoration:none;transition:0.2s;display:block}
        .service-item:active{transform:scale(0.95)}
        .svc-icon{width:46px;height:46px;border-radius:12px;display:flex;align-items:center;justify-content:center;margin:0 auto 7px;font-size:19px}
        .svc-icon.blue{background:#eef2ff;color:var(--primary)}
        .svc-icon.yellow{background:#fff8e6;color:#d69e2e}
        .svc-icon.green{background:#f0fff4;color:#38a169}
        .svc-icon.red{background:#fff5f5;color:#e53e3e}
        .svc-icon.purple{background:#faf5ff;color:#805ad5}
        .svc-icon.teal{background:#e6fffa;color:#319795}
        .service-item span{font-size:11px;color:#555;font-weight:600;display:block;line-height:1.2}

        /* Extra services - hidden by default */
        .extra-services{display:none;grid-template-columns:repeat(4,1fr);gap:10px;margin-top:10px}
        .extra-services.show{display:grid}

        /* Banner */
        .banner{background:linear-gradient(135deg,var(--primary),#2856c8);border-radius:16px;padding:18px;margin-top:18px;position:relative;overflow:hidden}
        .banner::after{content:'';position:absolute;right:-20px;top:-20px;width:100px;height:100px;background:rgba(255,255,255,0.07);border-radius:50%}
        .banner h3{color:white;font-size:15px;font-weight:700;margin-bottom:4px}
        .banner p{color:rgba(255,255,255,0.75);font-size:12px;margin-bottom:12px}
        .op-pills{display:flex;gap:7px;flex-wrap:wrap}
        .op-pill{background:rgba(255,255,255,0.18);color:white;padding:4px 11px;border-radius:20px;font-size:11px;font-weight:600}

        /* Recent Transactions */
        .txn-list{display:flex;flex-direction:column;gap:10px}
        .txn-item{background:white;border-radius:12px;padding:13px 14px;display:flex;align-items:center;gap:12px;box-shadow:0 2px 8px rgba(0,0,0,0.05)}
        .txn-ic{width:42px;height:42px;border-radius:11px;display:flex;align-items:center;justify-content:center;font-size:17px;flex-shrink:0}
        .txn-ic.success{background:#f0fff4;color:#38a169}
        .txn-ic.failed{background:#fff5f5;color:#e53e3e}
        .txn-ic.pending{background:#fffaf0;color:#d69e2e}
        .txn-info{flex:1;min-width:0}
        .txn-title{font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .txn-sub{font-size:11px;color:#999;margin-top:2px}
        .txn-amt{font-size:14px;font-weight:800;flex-shrink:0}
        .txn-amt.minus{color:#e53e3e}
        .txn-amt.plus{color:#38a169}
        .see-all{text-align:center;margin-top:14px;padding-bottom:4px}
        .see-all a{color:var(--primary);font-size:13px;font-weight:700;text-decoration:none}

        /* Sidebar */
        .sb-ov{position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:300;display:none}
        .sb-ov.on{display:block}
        .sidebar{position:fixed;top:0;left:-290px;bottom:0;width:280px;background:white;z-index:301;transition:0.3s;overflow-y:auto;box-shadow:4px 0 20px rgba(0,0,0,0.15)}
        .sidebar.on{left:0}
        .sb-hdr{background:linear-gradient(135deg,var(--dark),var(--primary));padding:40px 20px 20px;color:white}
        .sb-avatar{width:52px;height:52px;background:rgba(255,255,255,0.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:22px;margin-bottom:10px}
        .sb-name{font-size:16px;font-weight:700}
        .sb-info{font-size:12px;opacity:0.7;margin-top:3px}
        .sb-menu{padding:8px 0}
        .sb-menu a{display:flex;align-items:center;gap:14px;padding:13px 20px;color:#444;text-decoration:none;font-size:14px;transition:0.2s}
        .sb-menu a:hover{background:#f0f4ff;color:var(--primary)}
        .sb-menu a i{width:20px;color:var(--primary);font-size:15px}
        .sb-div{height:1px;background:#f0f0f0;margin:6px 20px}
        .sb-badge{background:var(--secondary);color:white;font-size:10px;font-weight:700;padding:2px 7px;border-radius:10px;margin-left:auto}
        @keyframes sp{to{transform:rotate(360deg)}}
    </style>
</head>
<body>

<!-- Sidebar -->
<div class="sb-ov" id="sbOv" onclick="closeSB()"></div>
<div class="sidebar" id="sidebar">
    <div class="sb-hdr">
        <div class="sb-avatar"><i class="fas fa-user"></i></div>
        <div class="sb-name"><?= htmlspecialchars($user['name']) ?></div>
        <div class="sb-info"><?= $user['phone'] ?> &bull; <?= ucfirst($user['role']) ?></div>
    </div>
    <div class="sb-menu">
        <a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a>
        <a href="topup.php"><i class="fas fa-mobile-alt"></i> Topup / Recharge</a>
        <a href="drive.php"><i class="fas fa-bolt"></i> Drive</a>
        <a href="international.php"><i class="fas fa-globe"></i> International</a>
        <a href="cards.php"><i class="fas fa-credit-card"></i> Cards</a>
        <?php if (isReseller()): ?>
        <a href="reseller.php"><i class="fas fa-users"></i> Reseller Panel</a>
        <?php endif; ?>
        <div class="sb-div"></div>
        <a href="deposit.php"><i class="fas fa-plus-circle"></i> Add Balance</a>
        <a href="history.php"><i class="fas fa-history"></i> Transaction History</a>
        <a href="profile.php"><i class="fas fa-user-cog"></i> Profile Settings</a>
        <div class="sb-div"></div>
        <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
</div>

<!-- Header -->
<div class="hdr">
    <div class="hdr-in">
        <button class="menu-btn" onclick="openSB()"><i class="fas fa-bars"></i></button>
        <div class="hdr-logo"><?php
            $parts = explode(' ', trim(SITE_NAME), 2);
            echo htmlspecialchars($parts[0]);
            if(isset($parts[1])) echo ' <span>'.htmlspecialchars($parts[1]).'</span>';
        ?></div>
        <button class="notif-btn" onclick="openNotif()">
            <i class="fas fa-bell"></i>
            <?php if (count($notifications) > 0): ?>
            <span class="notif-badge" id="notifBadge"><?= count($notifications) ?></span>
            <?php endif; ?>
        </button>
    </div>
</div>

<!-- Notification Panel -->
<div id="notifOverlay" onclick="closeNotif()" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0);z-index:999;transition:background 0.3s"></div>
<div id="notifPanel" style="display:none;position:fixed;top:0;right:0;width:100%;max-width:380px;height:100%;background:white;z-index:1000;box-shadow:-4px 0 20px rgba(0,0,0,0.15);flex-direction:column;overflow:hidden;transform:translateX(100%);transition:transform 0.35s cubic-bezier(0.4,0,0.2,1)">
    <div style="background:linear-gradient(135deg,#0d1f4e,#1a3c8f);padding:16px 18px;display:flex;align-items:center;justify-content:space-between">
        <span style="color:white;font-size:16px;font-weight:700">🔔 Notifications</span>
        <button onclick="closeNotif()" style="background:rgba(255,255,255,0.2);border:none;color:white;width:32px;height:32px;border-radius:50%;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center">✕</button>
    </div>
    <div style="flex:1;overflow-y:auto;padding:12px">
        <?php
        // Load all notifications (read + unread)
        $allNotifs = $db->prepare("SELECT * FROM notifications WHERE (user_id=? OR is_global=1) ORDER BY created_at DESC LIMIT 20");
        $allNotifs->execute([$user['id']]);
        $allNotifications = $allNotifs->fetchAll();
        if(empty($allNotifications)):
        ?>
        <div style="text-align:center;padding:40px 20px;color:#aaa">
            <div style="font-size:36px;margin-bottom:10px">🔔</div>
            <div style="font-size:14px">কোনো notification নেই</div>
        </div>
        <?php else: foreach($allNotifications as $n):
            $typeColors = ['success'=>'#38a169','error'=>'#e53e3e','warning'=>'#d69e2e','info'=>'#3182ce'];
            $typeBg     = ['success'=>'#f0fff4','error'=>'#fff5f5','warning'=>'#fffaf0','info'=>'#ebf8ff'];
            $tc = $typeColors[$n['type']] ?? '#3182ce';
            $tb = $typeBg[$n['type']] ?? '#ebf8ff';
        ?>
        <div style="background:<?= $n['is_read']?'#fafafa':$tb ?>;border-radius:12px;padding:12px 14px;margin-bottom:8px;border-left:3px solid <?= $n['is_read']?'#e8ecf4':$tc ?>">
            <div style="font-size:13px;font-weight:700;color:<?= $n['is_read']?'#555':$tc ?>;margin-bottom:3px"><?= htmlspecialchars($n['title']) ?></div>
            <div style="font-size:12px;color:#666;line-height:1.5"><?= htmlspecialchars($n['message']) ?></div>
            <div style="font-size:10px;color:#aaa;margin-top:5px"><?= date('d M Y, h:i A',strtotime($n['created_at'])) ?></div>
        </div>
        <?php endforeach; endif; ?>
    </div>
    <?php if(count($notifications) > 0): ?>
    <div style="padding:12px 16px;border-top:1px solid #f0f0f0">
        <button onclick="markAllRead()" style="width:100%;padding:11px;background:#f0f4ff;color:var(--primary);border:none;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer">
            ✓ Mark All as Read
        </button>
    </div>
    <?php endif; ?></div>

<!-- Balance Hero -->
<div class="hero">
    <div class="hero-in">
        <div class="bal-label" id="balLabel">MAIN BALANCE</div>

        <!-- Balance swap container -->
        <div style="position:relative;overflow:hidden;height:48px;margin-bottom:4px">
            <!-- Primary (BDT) -->
            <div id="balPrimary" style="position:absolute;width:100%;transition:all 0.5s cubic-bezier(0.4,0,0.2,1);transform:translateY(0);opacity:1">
                <div class="bal-amount"><?= CURRENCY ?> <?= number_format($user['balance'], 2) ?></div>
            </div>
            <?php if ($userCurrency && $balanceConverted !== null): ?>
            <!-- Secondary currency -->
            <div id="balSecondary" style="position:absolute;width:100%;transition:all 0.5s cubic-bezier(0.4,0,0.2,1);transform:translateY(100%);opacity:0">
                <div class="bal-amount"><?= htmlspecialchars($userCurrency['symbol']) ?><?= number_format($balanceConverted, 2) ?> <span style="font-size:16px;opacity:0.8"><?= $userCurrency['code'] ?></span></div>
            </div>
            <?php endif; ?>
        </div>

        <div class="bal-card">
            <span class="bal-due-txt">Due Balance: <?= CURRENCY ?> <?= number_format($user['due_balance'] ?? 0, 2) ?></span>
            <button class="add-btn" onclick="location.href='deposit.php'">+ Add</button>
        </div>
    </div>

    <!-- Ticker inside hero, overlapping bottom border -->
    <?php $ticker = getSetting('ticker_message'); if ($ticker): ?>
    <div id="tickerBar" style="position:absolute;bottom:-18px;left:50%;transform:translateX(-50%);width:calc(100% - 36px);max-width:480px;cursor:pointer;z-index:10">
        <div style="background:white;border-radius:30px;padding:9px 16px;overflow:hidden;display:flex;align-items:center;gap:8px;box-shadow:0 4px 16px rgba(26,60,143,0.15);border:1.5px solid #e8ecf4">
            <i class="fas fa-bullhorn" style="color:var(--primary);font-size:12px;flex-shrink:0;pointer-events:none"></i>
            <div style="overflow:hidden;flex:1;pointer-events:none">
                <span style="font-size:12px;white-space:nowrap;animation:tick 25s linear infinite;color:var(--primary);font-weight:600;display:inline-block"><?= htmlspecialchars($ticker) ?></span>
            </div>
            <i class="fas fa-chevron-right" style="color:#ccc;font-size:10px;flex-shrink:0;pointer-events:none"></i>
        </div>
    </div>

    <!-- Ticker Modal -->
    <div id="tickerModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0);z-index:9999;align-items:flex-end;justify-content:center;padding:0;transition:background 0.3s">
    <div id="tickerModalBox" style="background:white;border-radius:20px 20px 0 0;width:100%;max-width:480px;padding:24px;position:relative;transform:translateY(100%);transition:transform 0.35s cubic-bezier(0.34,1.1,0.64,1)">
        <div style="width:36px;height:4px;background:#e8ecf4;border-radius:4px;margin:0 auto 18px"></div>
        <button id="tickerClose" style="position:absolute;top:14px;right:14px;background:#f5f5f5;border:none;width:30px;height:30px;border-radius:50%;font-size:14px;cursor:pointer;color:#666;display:flex;align-items:center;justify-content:center">✕</button>
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px">
            <div style="width:38px;height:38px;background:#f0f4ff;border-radius:10px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
                <i class="fas fa-bullhorn" style="color:var(--primary);font-size:16px"></i>
            </div>
            <div style="font-size:16px;font-weight:800;color:var(--dark)">Notice</div>
        </div>
        <div style="font-size:14px;color:#444;line-height:1.8;background:#f8fafc;border-radius:12px;padding:16px;border-left:3px solid var(--primary)">
            <?= nl2br(htmlspecialchars($ticker)) ?>
        </div>
        <button id="tickerOk" style="width:100%;margin-top:16px;padding:13px;background:var(--primary);color:white;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer">OK</button>
    </div>
    </div>
    <?php endif; ?>
</div>

<div class="main" style="<?= $ticker ? 'margin-top:28px' : '' ?>">
    <!-- Services -->
    <div class="sec">
        <div class="sec-hdr">
            <div class="sec-title">Services</div>
            <button class="see-more" onclick="toggleMore(this)">
                See More <i class="fas fa-chevron-down" id="moreIcon"></i>
            </button>
        </div>

        <!-- Services grid — auto fill active only -->
        <?php
        $allSvcs = [];
        if($svcOn['topup'])        $allSvcs[] = ['topup.php',        'blue',   'fa-mobile-alt', 'Topup'];
        if($svcOn['drive'])        $allSvcs[] = ['drive.php',        'yellow', 'fa-bolt',        'Drive'];
        if($svcOn['international'])$allSvcs[] = ['international.php','blue',   'fa-globe',       'International'];
        if($svcOn['cards'])        $allSvcs[] = ['cards.php',        'yellow', 'fa-credit-card', 'Cards'];
        if($svcOn['manual_drive']) $allSvcs[] = ['manual-drive.php', 'green',  'fa-desktop',     'Manual Drive'];
        if($svcOn['mbanking'])     $allSvcs[] = ['mbanking.php',     'teal',   'fa-university',  'M.Banking'];
        if($svcOn['deposit'])      $allSvcs[] = ['deposit.php',      'green',  'fa-plus-circle', 'Deposit'];
        if($svcOn['bill_pay'])     $allSvcs[] = ['bill-pay.php',     'teal',   'fa-receipt',     'Bill Pay'];
        $allSvcs[]                             = ['history.php',      'purple', 'fa-history',     'History'];
        if (isReseller())          $allSvcs[] = ['reseller.php',     'yellow', 'fa-users',       'Reseller'];
        $allSvcs[]                             = ['profile.php',      'red',    'fa-user',        'Profile'];

        $showSvcs  = array_slice($allSvcs, 0, 4);
        $extraSvcs = array_slice($allSvcs, 4);
        ?>
        <div class="services-grid" id="mainSvcGrid">
            <?php foreach($showSvcs as [$href,$color,$icon,$label]): ?>
            <a href="<?= $href ?>" class="service-item">
                <div class="svc-icon <?= $color ?>"><i class="fas <?= $icon ?>"></i></div>
                <span><?= $label ?></span>
            </a>
            <?php endforeach; ?>
        </div>

        <?php if(!empty($extraSvcs)): ?>
        <div class="extra-services" id="extraSvc">
            <?php foreach($extraSvcs as [$href,$color,$icon,$label]): ?>
            <a href="<?= $href ?>" class="service-item">
                <div class="svc-icon <?= $color ?>"><i class="fas <?= $icon ?>"></i></div>
                <span><?= $label ?></span>
            </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <?php if($error): ?><div class="alert alert-err">❌ <?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if(isset($_GET['svc_off'])): ?>
<div style="background:#fff5f5;border:1px solid #fed7d7;border-radius:12px;padding:12px 16px;margin-bottom:14px;font-size:13px;color:#c53030;font-weight:600">
    ⚠️ This service is currently unavailable.
</div>
<?php endif; ?>
    <!-- Banner Slideshow -->
    <?php if(!empty($banners)): ?>
    <div style="margin-top:18px;overflow:hidden;border-radius:16px" id="bannerSlider">
        <div id="bannerTrack" style="display:flex;transition:transform 0.45s cubic-bezier(0.4,0,0.2,1);will-change:transform">
        <?php foreach($banners as $bi=>$b):
            $pills=array_filter(array_map('trim',explode(',',$b['pills']??'')));
        ?>
        <div class="banner-slide" id="bslide<?= $bi ?>" style="min-width:100%;background:<?= htmlspecialchars($b['bg_color']) ?>;border-radius:16px;padding:18px;position:relative;overflow:hidden;cursor:<?= $b['link_url']?'pointer':'default' ?>;box-sizing:border-box"
            <?= $b['link_url']?'onclick="location.href=\''.htmlspecialchars($b['link_url'],ENT_QUOTES).'\'"':'' ?>>
            <div style="position:absolute;right:-20px;top:-20px;width:100px;height:100px;background:rgba(255,255,255,0.07);border-radius:50%"></div>
            <?php if($b['image']): ?>
            <img src="<?= SITE_URL ?>/<?= htmlspecialchars($b['image']) ?>" style="position:absolute;right:0;top:0;height:100%;width:45%;object-fit:cover;opacity:0.25;z-index:0;border-radius:0 16px 16px 0">
            <?php endif; ?>
            <div style="position:relative;z-index:1">
                <?php if($b['title']): ?><h3 style="color:white;font-size:15px;font-weight:700;margin-bottom:4px"><?= htmlspecialchars($b['title']) ?></h3><?php endif; ?>
                <?php if($b['subtitle']): ?><p style="color:rgba(255,255,255,0.75);font-size:12px;margin-bottom:12px"><?= htmlspecialchars($b['subtitle']) ?></p><?php endif; ?>
                <?php if($pills): ?>
                <div class="op-pills"><?php foreach($pills as $pill): ?><span class="op-pill"><?= htmlspecialchars($pill) ?></span><?php endforeach; ?></div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
        <?php if(count($banners)>1): ?>
        <div style="display:flex;justify-content:center;gap:6px;margin-top:8px" id="bannerDots">
            <?php foreach($banners as $bi=>$b): ?>
            <div class="bdot" id="bdot<?= $bi ?>" onclick="goSlide(<?= $bi ?>)" style="width:<?= $bi===0?'20':'8' ?>px;height:8px;border-radius:4px;background:<?= $bi===0?'var(--primary)':'#ddd' ?>;cursor:pointer;transition:all 0.3s"></div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Recent Transactions -->
    <div class="sec">
        <div class="sec-hdr">
            <div class="sec-title">Recent Transactions</div>
        </div>
        <div class="txn-list">
            <?php if (empty($transactions)): ?>
            <div style="text-align:center;padding:30px;color:#aaa;background:white;border-radius:14px;box-shadow:0 2px 8px rgba(0,0,0,0.05)">
                <i class="fas fa-inbox" style="font-size:28px;margin-bottom:8px;display:block;color:#ddd"></i>
                No transactions yet
            </div>
            <?php else: ?>
            <?php foreach ($transactions as $t): 
                $typeMap = [
                    'topup'         => ['icon'=>'mobile-alt',   'label'=>'Mobile Recharge', 'emoji'=>'📱', 'plus'=>false],
                    'drive'         => ['icon'=>'bolt',          'label'=>'Drive',            'emoji'=>'⚡', 'plus'=>false],
                    'deposit'       => ['icon'=>'plus-circle',   'label'=>'Deposit',          'emoji'=>'💰', 'plus'=>true],
                    'international' => ['icon'=>'globe',         'label'=>'Intl Recharge',    'emoji'=>'🌍', 'plus'=>false],
                    'pin'           => ['icon'=>'key',           'label'=>'Recharge PIN',     'emoji'=>'🔑', 'plus'=>false],
                    'gift'          => ['icon'=>'gift',          'label'=>'Gift Card',        'emoji'=>'🎁', 'plus'=>false],
                    'card'          => ['icon'=>'credit-card',   'label'=>'Calling Card',     'emoji'=>'🎴', 'plus'=>false],
                    'commission'    => ['icon'=>'percent',       'label'=>'Commission',       'emoji'=>'💸', 'plus'=>true],
                    'refund'        => ['icon'=>'undo',          'label'=>'Refund',           'emoji'=>'↩️', 'plus'=>true],
                    'package_fee'   => ['icon'=>'tags',          'label'=>'Package Upgrade',  'emoji'=>'🎯', 'plus'=>false],
                    'mbanking'      => ['icon'=>'university',    'label'=>'M.Banking',        'emoji'=>'🏦', 'plus'=>false],
                    'manual_drive'  => ['icon'=>'hand-paper',    'label'=>'Manual Drive',     'emoji'=>'📦', 'plus'=>false],
                ];
                $cfg    = $typeMap[$t['type']] ?? ['icon'=>'exchange-alt','label'=>ucfirst($t['type']),'emoji'=>'💳','plus'=>false];
                $isPlus = $cfg['plus'];
                $title  = $cfg['emoji'].' '.$cfg['label'];
                if (!empty($t['op_name'])) $title .= ' — '.$t['op_name'];
                $sub = $t['phone_number'] ?? '';
                if (!$sub && !empty($t['note'])) {
                    // For card/commission, note may have Bengali — show reference instead
                    if(in_array($t['type'], ['card','commission','manual_drive'])) {
                        $sub = $t['reference'] ?? '';
                    } else {
                        $parts = explode('|', $t['note']);
                        $sub = trim($parts[0]);
                        if (strlen($sub) > 35) $sub = substr($sub, 0, 35).'...';
                    }
                }
                // Status color
                $icClass = $t['status']==='success'?'success':($t['status']==='pending'?'pending':'failed');
                if($t['type']==='commission') $icClass='success';
            ?>
            <div class="txn-item" onclick="location.href='history.php'" style="cursor:pointer">
                <div class="txn-ic <?= $icClass ?>">
                    <i class="fas fa-<?= $cfg['icon'] ?>"></i>
                </div>
                <div class="txn-info">
                    <div class="txn-title"><?= $title ?></div>
                    <div class="txn-sub">
                        <?= $sub ? htmlspecialchars($sub).' &bull; ' : '' ?>
                        <?= date('M d, h:i A', strtotime($t['created_at'])) ?>
                        &bull; <span style="color:<?= $t['status']==='success'?'#38a169':($t['status']==='pending'?'#d69e2e':'#e53e3e') ?>"><?= ucfirst($t['status']) ?></span>
                    </div>
                </div>
                <div class="txn-amt <?= $isPlus?'plus':'minus' ?>">
                    <?= $isPlus?'+':'-' ?><?= CURRENCY ?><?= number_format($t['amount'],2) ?>
                    <?php if($userCurrency && floatval($userCurrency['rate'])>0): ?>
                    <div style="font-size:11px;color:#888;font-weight:500;margin-top:1px">
                        ≈ <?= htmlspecialchars($userCurrency['symbol']) ?><?= number_format($t['amount']*floatval($userCurrency['rate']),2) ?> <?= $userCurrency['code'] ?>
                    </div>
                    <?php endif; ?>
                </div>
                <i class="fas fa-chevron-right" style="color:#e8ecf4;font-size:10px;flex-shrink:0"></i>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <div class="see-all">
            <a href="history.php">
                View all transactions <i class="fas fa-arrow-right" style="font-size:12px"></i>
            </a>
        </div>
    </div>
</div>

<?php include 'includes/bottom_nav.php'; ?>

<script>
// Banner slideshow — right to left slide
(function(){
    const total = <?= count($banners) ?>;
    if(total <= 1) return;
    let cur = 0;
    const track = document.getElementById('bannerTrack');
    function goSlide(n) {
        document.getElementById('bdot'+cur).style.width='8px';
        document.getElementById('bdot'+cur).style.background='#ddd';
        cur = ((n % total) + total) % total;
        track.style.transform = 'translateX(-' + (cur * 100) + '%)';
        document.getElementById('bdot'+cur).style.width='20px';
        document.getElementById('bdot'+cur).style.background='var(--primary)';
    }
    window.goSlide = goSlide;
    setInterval(()=>goSlide(cur+1), 6000);
})();

// Balance swap animation
<?php if ($userCurrency && $balanceConverted !== null): ?>
(function() {
    const primary   = document.getElementById('balPrimary');
    const secondary = document.getElementById('balSecondary');
    const label     = document.getElementById('balLabel');
    if (!primary || !secondary) return;

    let showingPrimary = true;

    setInterval(function() {
        if (showingPrimary) {
            // Slide primary up & out, secondary up & in
            primary.style.transform   = 'translateY(-100%)';
            primary.style.opacity     = '0';
            secondary.style.transform = 'translateY(0)';
            secondary.style.opacity   = '1';
            label.textContent = '<?= htmlspecialchars($userCurrency['code']) ?> BALANCE';
        } else {
            // Slide secondary down & out, primary down & in
            secondary.style.transform = 'translateY(100%)';
            secondary.style.opacity   = '0';
            primary.style.transform   = 'translateY(0)';
            primary.style.opacity     = '1';
            label.textContent = 'MAIN BALANCE';
        }
        showingPrimary = !showingPrimary;
    }, 3000);
})();
<?php endif; ?>

// Ticker modal
document.addEventListener('DOMContentLoaded', function() {
    const bar   = document.getElementById('tickerBar');
    const modal = document.getElementById('tickerModal');
    const box   = document.getElementById('tickerModalBox');
    const close = document.getElementById('tickerClose');
    const ok    = document.getElementById('tickerOk');

    function openTicker() {
        modal.style.display = 'flex';
        requestAnimationFrame(() => {
            modal.style.background = 'rgba(0,0,0,0.5)';
            box.style.transform = 'translateY(0)';
        });
    }
    function closeTicker() {
        modal.style.background = 'rgba(0,0,0,0)';
        box.style.transform = 'translateY(100%)';
        setTimeout(() => { modal.style.display = 'none'; }, 350);
    }

    if(bar)   bar.addEventListener('click', openTicker);
    if(close) close.addEventListener('click', closeTicker);
    if(ok)    ok.addEventListener('click', closeTicker);
    if(modal) modal.addEventListener('click', function(e) {
        if(e.target === modal) closeTicker();
    });
});

function openNotif() {
    const panel   = document.getElementById('notifPanel');
    const overlay = document.getElementById('notifOverlay');
    panel.style.display   = 'flex';
    overlay.style.display = 'block';
    requestAnimationFrame(() => {
        panel.style.transform     = 'translateX(0)';
        overlay.style.background  = 'rgba(0,0,0,0.4)';
    });
}
function closeNotif() {
    const panel   = document.getElementById('notifPanel');
    const overlay = document.getElementById('notifOverlay');
    panel.style.transform    = 'translateX(100%)';
    overlay.style.background = 'rgba(0,0,0,0)';
    setTimeout(() => {
        panel.style.display   = 'none';
        overlay.style.display = 'none';
    }, 350);
}
function markAllRead() {
    fetch('api/mark_notifications.php', {method:'POST'})
    .then(r=>r.json())
    .then(d=>{
        if(d.success) {
            const badge = document.getElementById('notifBadge');
            if(badge) badge.remove();
            // Update notification items to read style
            document.querySelectorAll('#notifPanel [style*="border-left"]').forEach(el => {
                el.style.background = '#fafafa';
                el.style.borderLeftColor = '#e8ecf4';
                el.querySelectorAll('div').forEach(d => {
                    if(d.style.fontWeight === '700') d.style.color = '#555';
                });
            });
            // Hide mark read button
            document.querySelector('#notifPanel button[onclick="markAllRead()"]')
                ?.closest('div')?.remove();
        }
    }).catch(()=>{});
}
function openSB(){ document.getElementById('sidebar').classList.add('on'); document.getElementById('sbOv').classList.add('on'); }
function closeSB(){ document.getElementById('sidebar').classList.remove('on'); document.getElementById('sbOv').classList.remove('on'); }

function toggleMore(btn) {
    const extra = document.getElementById('extraSvc');
    const icon  = document.getElementById('moreIcon');
    const isShown = extra.classList.contains('show');
    extra.classList.toggle('show');
    icon.className = isShown ? 'fas fa-chevron-down' : 'fas fa-chevron-up';
    btn.childNodes[0].textContent = isShown ? 'See More ' : 'See Less ';
}
</script>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
