<?php
// FILE: public_html/dashboard.php (USER DASHBOARD)
require_once 'db.php'; 
require_once 'notifications.php'; 

session_start();

// 1. SESSION CHECK
if (!isset($_SESSION['user_id'])) { header("Location: index.php"); exit(); }
$user_id = $_SESSION['user_id'];

// 2. FETCH USER
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user_res = $stmt->get_result();
$user = $user_res->fetch_assoc();

// Prevent Null Variables
$first_name = !empty($user['first_name']) ? $user['first_name'] : 'User';
$username   = !empty($user['username']) ? $user['username'] : 'User';

// CHECK PIN STATUS (For JS Logic)
$has_pin = !empty($user['trans_pin']) ? 1 : 0; 

// 3. FETCH WALLET
$wallet = $conn->query("SELECT * FROM wallets WHERE user_id = $user_id")->fetch_assoc();
$balance = $wallet['balance'] ?? 0.00;
$ref_count = $wallet['referral_count'] ?? 0;
$ref_earn = $wallet['referral_commission'] ?? 0.00;

// 4. FETCH SETTINGS
$settings = [];
$sq = $conn->query("SELECT * FROM settings");
while($r=$sq->fetch_assoc()){ $settings[$r['name']]=$r['value']; }

// 5. VIRTUAL ACCOUNT
$vacc = $conn->query("SELECT * FROM virtual_accounts WHERE user_id = $user_id LIMIT 1")->fetch_assoc();

// 6. TRANSACTIONS
$txns = $conn->query("SELECT * FROM transactions WHERE user_id = $user_id ORDER BY created_at DESC LIMIT 5");
?>
<!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 - Nagarta Data Sub</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* --- PREMIUM THEME --- */
        :root { 
            --primary: #2c5364;      
            --secondary: #203a43;    
            --accent: #00d2ff;       
            --bg: #f4f7f6;           
            --text: #334155; 
            --white: #ffffff;
            --sidebar-width: 260px;
        }

        * { margin:0; padding:0; box-sizing:border-box; font-family:'Poppins', sans-serif; -webkit-tap-highlight-color: transparent; }
        body { background:var(--bg); display:flex; min-height:100vh; color:var(--text); overflow-x: hidden; }

        /* --- MODERN SCROLLBAR --- */
        ::-webkit-scrollbar { width: 8px; height: 8px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 20px; border: 3px solid transparent; background-clip: content-box; }
        ::-webkit-scrollbar-thumb:hover { background-color: var(--primary); }
        html { scrollbar-width: thin; scrollbar-color: #cbd5e1 transparent; }

        /* --- SIDEBAR STYLES --- */
        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, var(--secondary) 0%, var(--primary) 100%); color: white; display: flex; flex-direction: column; position: fixed; height: 100%; z-index: 1000; transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1); left: 0; box-shadow: 5px 0 15px rgba(0,0,0,0.1); padding: 20px 15px; }
        .sidebar-header { display: flex; flex-direction: column; align-items: center; justify-content: center; margin-bottom: 30px; padding-top: 10px; }
        .logo-box { width: 100%; display: flex; justify-content: center; align-items: center; }
        .logo-box img { max-height: 50px; width: auto; filter: drop-shadow(0 2px 4px rgba(0,0,0,0.3)); }
        
        .nav-links { list-style: none; padding: 0; flex: 1; overflow-y: auto; width: 100%; scrollbar-color: rgba(255,255,255,0.2) transparent; }
        .nav-links::-webkit-scrollbar-thumb { background-color: rgba(255,255,255,0.2); }
        .nav-links a { display: flex; align-items: center; padding: 14px 15px; color: rgba(255,255,255,0.8); text-decoration: none; border-radius: 12px; margin-bottom: 8px; transition: all 0.3s ease; font-size: 0.95rem; font-weight: 500; }
        .nav-links a:hover, .nav-links a.active { background: rgba(255,255,255,0.15); color: white; box-shadow: 0 4px 15px rgba(0,0,0,0.1); transform: translateX(5px); }
        .nav-links i { width: 35px; text-align: center; font-size: 1.1rem; margin-right: 8px; }

        /* --- MAIN CONTENT --- */
        .main-content { flex:1; margin-left: var(--sidebar-width); padding: 25px; width: calc(100% - var(--sidebar-width)); transition: 0.3s; }
        .header { background:white; padding:15px 20px; border-radius:15px; display:flex; justify-content:space-between; align-items:center; margin-bottom:25px; box-shadow:0 4px 15px rgba(0,0,0,0.03); position: sticky; top: 0; z-index: 90; }
        .menu-toggle { display:none; font-size:1.4rem; cursor:pointer; color: var(--primary); padding: 5px; }
        
        /* --- SLIDER & WELCOME CARD STYLES --- */
        .welcome-card { 
            background: linear-gradient(135deg, #0f2027, #203a43, #2c5364); 
            color: white; padding: 25px; border-radius: 20px; 
            margin-bottom: 30px; position: relative; overflow: hidden; 
            box-shadow: 0 10px 25px rgba(32, 58, 67, 0.2); 
            display: flex; align-items: center; justify-content: space-between; 
            height: 160px; /* Fixed height for consistency */
        }
        .welcome-content { z-index: 2; max-width: 75%; }
        .welcome-icon { font-size: 80px; opacity: 0.1; position: absolute; right: 20px; top: 50%; transform: translateY(-50%); }
        .btn-welcome { background: rgba(255,255,255,0.15); color: white; border: 1px solid rgba(255,255,255,0.2); padding: 8px 20px; border-radius: 30px; text-decoration: none; font-size: 0.85rem; display: inline-block; margin-top: 15px; transition: 0.3s; }

        /* Mobile Slider Styles */
        .slider-container { display: none; } /* Hidden on desktop */
        
        .mobile-slide {
            position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            opacity: 0; transition: opacity 1s ease-in-out;
            border-radius: 20px; overflow: hidden;
        }
        .mobile-slide.active { opacity: 1; z-index: 1; }
        
        /* Text Slide (The original welcome content) */
        .slide-text { 
            background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
            padding: 25px; display: flex; align-items: center; justify-content: space-between;
            height: 100%; width: 100%;
        }
        
        /* Image Slide */
        .slide-img img { 
            width: 100%; height: 100%; object-fit: cover; border-radius: 20px; 
        }

        /* --- UPDATED BALANCE CARD (Image Replication) --- */
        .balance-card { 
            background: #34495e; /* Dark blue container */
            color:white; 
            padding: 15px; 
            border-radius: 20px; 
            margin-bottom: 30px; 
            position: relative; 
            overflow: hidden; 
            box-shadow: 0 10px 25px rgba(52, 73, 94, 0.25);
            /* height: 160px;  Removed fixed height to fit content */
        }

        .acc-bar {
            background: #bdc3c7; /* Grey bar */
            padding: 10px 15px;
            border-radius: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .acc-info {
            display: flex;
            align-items: center;
            gap: 10px;
            color: #2c3e50;
            font-weight: 600;
        }

        .acc-icon {
            width: 30px; height: 30px; background: #34495e; color: white;
            border-radius: 50%; display: flex; align-items: center; justify-content: center;
            font-size: 1rem; font-weight: bold;
        }

        .btn-copy {
            background: #34495e; color: white; padding: 8px 12px;
            border-radius: 10px; border: none; cursor: pointer; font-size: 0.9rem;
        }
        
        .balance-info {
            background: #bdc3c7; /* Grey bar */
            padding: 15px 20px;
            border-radius: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .bal-section {
            flex: 1;
        }
        
        .bal-label {
            font-size: 0.85rem; opacity: 0.9; margin-bottom: 5px;
        }

        .amt { font-size: 1.8rem; font-weight:700; margin: 0; letter-spacing: -1px; line-height: 1; }

        /* GRIDS & TABLES */
        .stats-grid { display:grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap:20px; margin-bottom:30px; }
        .stat-card { background:white; padding:20px; border-radius:16px; text-align:center; box-shadow:0 5px 15px rgba(0,0,0,0.03); }
        .referral-box { background: white; padding: 20px; border-radius: 16px; margin-bottom: 30px; box-shadow: 0 5px 15px rgba(0,0,0,0.03); border: 1px dashed var(--primary); }
        
        .services-grid { display:grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap:15px; margin-bottom:30px; }
        .service-card { background:white; padding:15px; border-radius:16px; text-align:center; box-shadow:0 5px 15px rgba(0,0,0,0.03); transition: 0.3s; cursor: pointer; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; }
        .service-card:hover { transform: translateY(-5px); border-color: var(--accent); }
        .service-card h4 { font-size: 0.8rem; margin: 0; }
        .s-icon { width:45px; height:45px; margin-bottom: 8px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:1.3rem; }
        
        .table-container { background:white; border-radius:16px; overflow-x:auto; box-shadow: 0 5px 15px rgba(0,0,0,0.03); padding: 5px; }
        table { width:100%; border-collapse:collapse; min-width: 500px; }
        th, td { padding:15px; text-align:left; border-bottom:1px solid #f1f5f9; font-size:0.9rem; }
        th { background:#f8fafc; color:var(--secondary); font-weight: 600; font-size: 0.8rem; }
        .badge { padding:5px 10px; border-radius:20px; font-size:0.75rem; font-weight:600; }
        .success { background:#dcfce7; color:#166534; } 
        .failed { background:#fee2e2; color:#991b1b; }

        /* MODALS & FORMS */
        .modal { display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(15, 23, 42, 0.8); z-index:2000; align-items:center; justify-content:center; backdrop-filter:blur(3px); }
        .modal-box { background:white; width:95%; max-width:420px; padding:25px; border-radius:20px; position:relative; max-height:90vh; overflow-y:auto; animation:zoomUp 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        @keyframes zoomUp { from{transform:scale(0.9);opacity:0} to{transform:scale(1);opacity:1} }
        .close-btn { position:absolute; top:20px; right:20px; font-size:1.5rem; cursor:pointer; color:#94a3b8; }
        .form-group { margin-bottom:15px; }
        .form-group label { display:block; margin-bottom:8px; font-weight:600; font-size:0.85rem; color:#475569; }
        .form-control { width:100%; padding:14px; border:1px solid #e2e8f0; border-radius:12px; outline:none; background: #f8fafc; font-size: 1rem; transition: 0.3s; }
        .form-control:focus { border-color: var(--accent); background: white; }
        .btn-main { width:100%; background:var(--primary); color:white; padding:15px; border:none; border-radius:12px; font-weight:600; font-size: 1rem; cursor:pointer; margin-top:10px; box-shadow: 0 5px 15px rgba(44, 83, 100, 0.2); }
        .network-grid { display:flex; gap:12px; justify-content:center; margin-bottom:20px; }
        .net-opt { width:60px; height:60px; border-radius:50%; border:3px solid #f1f5f9; padding:5px; cursor:pointer; opacity:0.6; transition:0.3s; background: white; }
        .net-opt.active { opacity:1; border-color:var(--accent); transform:scale(1.1); box-shadow:0 5px 15px rgba(0,210,255,0.2); }
        .net-opt img { width:100%; height:100%; object-fit:contain; border-radius:50%; }
        #price_display { margin-top:10px; font-weight:bold; color: var(--primary); text-align:right; display:none; }
        .overlay-bg { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 900; }

        @media (max-width: 991px) {
            .sidebar { left: -280px; } .sidebar.active { left: 0; }
            .main-content { margin-left: 0; width: 100%; padding: 15px; }
            .menu-toggle { display: block; } .overlay-bg.active { display: block; }
        }

        /* MOBILE OPTIMIZATION */
        @media (max-width: 768px) {
            .welcome-card-desktop { display: none !important; }
            .slider-container { 
                display: block; position: relative; width: 100%; height: 160px; 
                margin-bottom: 30px; border-radius: 20px; box-shadow: 0 10px 25px rgba(32, 58, 67, 0.2);
            }
            .stats-grid { grid-template-columns: 1fr; } 
            .services-grid { grid-template-columns: repeat(3, 1fr); }
            
            /* --- UPDATED BALANCE CARD MOBILE --- */
            .balance-card { padding: 15px; }
            .acc-bar { padding: 8px 12px; }
            .acc-info { font-size: 0.9rem; }
            .acc-icon { width: 25px; height: 25px; font-size: 0.8rem; }
            .btn-copy { padding: 6px 10px; font-size: 0.8rem; }
            .balance-info { padding: 12px 15px; }
            .amt { font-size: 1.5rem; } /* Reduced size for mobile */
            
            .net-opt { width: 50px; height: 50px; }
        }
    </style>
</head>
<body>

<div class="overlay-bg" onclick="toggleSidebar()"></div>

<div class="sidebar">
    <div class="sidebar-header">
        <div class="logo-box">
            <img src="assets/images/logo.png" alt="Nagarta Data">
        </div>
    </div>

    <ul class="nav-links">
        <li><a href="dashboard.php" class="active"><i class="fas fa-home"></i> Dashboard</a></li>
        <li><a href="javascript:void(0)" onclick="openModal('dataModal'); toggleSidebar()"><i class="fas fa-wifi"></i> Buy Data</a></li>
        <li><a href="javascript:void(0)" onclick="openModal('airtimeModal'); toggleSidebar()"><i class="fas fa-phone"></i> Airtime</a></li>
        <li><a href="javascript:void(0)" onclick="openModal('cableModal'); toggleSidebar()"><i class="fas fa-tv"></i> Cable TV</a></li>
        <li><a href="javascript:void(0)" onclick="openModal('electricModal'); toggleSidebar()"><i class="fas fa-bolt"></i> Electricity</a></li>
        <li><a href="transactions.php"><i class="fas fa-history"></i> Transactions</a></li>
        <li><a href="javascript:void(0)" onclick="openModal('supportModal'); toggleSidebar()"><i class="fas fa-headset"></i> Support</a></li>
        <li><a href="developer.php"><i class="fas fa-code"></i> Developer API</a></li>
        <li><a href="javascript:void(0)" onclick="openModal('settingsModal'); toggleSidebar()"><i class="fas fa-cog"></i> Settings</a></li>
        <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
    </ul>
</div>

<div class="main-content">
    
    <div class="header">
        <div class="menu-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></div>
        <div>
            <h3 style="color:var(--primary); font-size: 1.2rem; margin:0;">Hi, <?php echo htmlspecialchars(explode(' ', $first_name)[0]); ?></h3>
            <small style="color:#64748b;">Welcome back</small>
        </div>
        <div style="width:40px; height:40px; background:var(--primary); color:white; border-radius:50%; display:flex; align-items:center; justify-content:center; font-weight:bold; box-shadow: 0 4px 10px rgba(0,0,0,0.1);">
            <?php echo strtoupper(substr($first_name, 0, 1)); ?>
        </div>
    </div>

    <?php
    $chk_table = $conn->query("SHOW TABLES LIKE 'user_notifications'");
    if($chk_table->num_rows > 0) {
        $notif_q = $conn->query("SELECT * FROM user_notifications WHERE user_id = $user_id AND is_read = 0 ORDER BY created_at DESC");
        if ($notif_q && $notif_q->num_rows > 0):
    ?>
    <div style="margin-bottom: 20px;">
        <?php while($note = $notif_q->fetch_assoc()): ?>
        <div class="alert-box" id="notif-<?php echo $note['id']; ?>" 
             style="background: #dcfce7; border-left: 5px solid #10b981; color: #166534; padding: 15px; border-radius: 8px; margin-bottom: 10px; display: flex; align-items: flex-start; justify-content: space-between; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
            <div style="display: flex; gap: 15px;">
                <i class="fas fa-check-circle" style="font-size: 1.5rem; margin-top: 2px;"></i>
                <div>
                    <h4 style="margin: 0 0 2px 0; font-size: 0.95rem; font-weight: 700;"><?php echo htmlspecialchars($note['title']); ?></h4>
                    <p style="margin: 0; font-size: 0.85rem; opacity: 0.9;"><?php echo htmlspecialchars($note['message']); ?></p>
                </div>
            </div>
            <button onclick="dismissNotif(<?php echo $note['id']; ?>)" style="background: none; border: none; font-size: 1.2rem; color: #166534; cursor: pointer; opacity: 0.6;">&times;</button>
        </div>
        <?php endwhile; ?>
    </div>
    <?php endif; } ?>

    <div class="welcome-card welcome-card-desktop">
        <div class="welcome-content">
            <h3 style="margin: 0 0 5px;">🚀 We are officially LIVE!</h3>
            <p style="opacity: 0.9; margin: 0; font-size: 0.9rem;">Enjoy instant funding and automated delivery.</p>
            <a href="#" onclick="openModal('fundModal')" class="btn-welcome">Fund Wallet <i class="fas fa-arrow-right" style="margin-left:5px;"></i></a>
        </div>
        <div class="welcome-icon"><i class="fas fa-rocket"></i></div>
    </div>

    <div class="slider-container">
        <div class="mobile-slide active" data-type="text">
            <div class="slide-text">
                <div class="welcome-content" style="z-index: 2; max-width: 100%;">
                    <h3 style="margin: 0 0 5px; color:white;">🚀 We are officially LIVE!</h3>
                    <p style="opacity: 0.9; margin: 0; font-size: 0.9rem; color:white;">Enjoy instant funding.</p>
                    <a href="#" onclick="openModal('fundModal')" class="btn-welcome">Fund Wallet <i class="fas fa-arrow-right" style="margin-left:5px;"></i></a>
                </div>
            </div>
        </div>
        <div class="mobile-slide" data-type="image"><div class="slide-img"><img src="assets/images/slide1.png" alt="Promo 1"></div></div>
        <div class="mobile-slide" data-type="image"><div class="slide-img"><img src="assets/images/slide2.png" alt="Promo 2"></div></div>
        <div class="mobile-slide" data-type="image"><div class="slide-img"><img src="assets/images/slide3.png" alt="Promo 3"></div></div>
    </div>

    <div class="balance-card">
        <div class="acc-bar">
            <div class="acc-info">
                <div class="acc-icon">P</div>
                <div>
                    <?php if($vacc): ?>
                        <span>Palmpay</span> <span style="margin-left: 10px;"><?php echo $vacc['account_number']; ?></span>
                    <?php else: ?>
                        <span>No Account</span>
                    <?php endif; ?>
                </div>
            </div>
            <?php if($vacc): ?>
                <button class="btn-copy" onclick="navigator.clipboard.writeText('<?php echo $vacc['account_number']; ?>'); alert('Copied!')"><i class="far fa-copy"></i></button>
            <?php else: ?>
                <button class="btn-copy" onclick="generateAccount()">Generate</button>
            <?php endif; ?>
        </div>
        
        <div class="balance-info">
            <div class="bal-section">
                <div class="bal-label">Wallet Balance</div>
                <div class="amt">₦<?php echo number_format($balance, 2); ?> <i class="far fa-eye" style="font-size: 1rem; margin-left: 5px; cursor: pointer;"></i></div>
            </div>
            <div class="bal-section" style="text-align: right;">
                <div class="bal-label">Commission</div>
                <div class="amt">₦<?php echo number_format($ref_earn, 2); ?></div>
            </div>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div style="width:45px; height:45px; background:#e0f2fe; color:#0284c7; border-radius:50%; display:flex; align-items:center; justify-content:center; margin:0 auto 10px; font-size:1.1rem;"><i class="fas fa-users"></i></div>
            <div style="font-size:1.5rem; font-weight:700; color:var(--primary);"><?php echo $ref_count; ?></div>
            <small style="color:#64748b;">Referrals</small>
        </div>
        <div class="stat-card">
            <div style="width:45px; height:45px; background:#dcfce7; color:#166534; border-radius:50%; display:flex; align-items:center; justify-content:center; margin:0 auto 10px; font-size:1.1rem;"><i class="fas fa-wallet"></i></div>
            <div style="font-size:1.5rem; font-weight:700; color:var(--primary);">₦<?php echo number_format($ref_earn, 2); ?></div>
            <small style="color:#64748b;">Earnings</small>
        </div>
    </div>

    <div class="referral-box">
        <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px;">
            <div>
                <h4 style="margin:0; color:var(--primary);">Refer & Earn</h4>
                <p style="margin:5px 0 0; font-size:0.85rem; color:#64748b;">Share your link and earn bonuses!</p>
            </div>
            <div style="display:flex; gap:10px; flex:1; min-width:280px;">
                <?php
                    $my_protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                    $my_host = $_SERVER['HTTP_HOST'] ?? 'yourwebsite.com';
                    $my_ref_id = !empty($username) ? $username : $user_id;
                    $actual_ref_link = "$my_protocol://$my_host/index.php?ref=$my_ref_id";
                ?>
                <input type="text" value="<?php echo htmlspecialchars($actual_ref_link); ?>" id="myRefLink" readonly style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px; background:#f8fafc; color:#64748b;">
                <button onclick="copyRef()" style="background:var(--primary); color:white; border:none; padding:0 20px; border-radius:8px; cursor:pointer; font-weight:600;">Copy</button>
            </div>
        </div>
    </div>

    <h3 style="margin-bottom: 15px; color: var(--secondary); font-size: 1.1rem;">Quick Services</h3>
    <div class="services-grid">
        <div class="service-card" onclick="openModal('dataModal')">
            <div class="s-icon" style="background:#e0f2fe; color:#0284c7;"><i class="fas fa-wifi"></i></div>
            <h4>Data</h4>
        </div>
        <div class="service-card" onclick="openModal('airtimeModal')">
            <div class="s-icon" style="background:#dcfce7; color:#166534;"><i class="fas fa-phone"></i></div>
            <h4>Airtime</h4>
        </div>
        <div class="service-card" onclick="openModal('cableModal')">
            <div class="s-icon" style="background:#fae8ff; color:#86198f;"><i class="fas fa-tv"></i></div>
            <h4>Cable</h4>
        </div>
        <div class="service-card" onclick="openModal('electricModal')">
            <div class="s-icon" style="background:#fff7ed; color:#c2410c;"><i class="fas fa-bolt"></i></div>
            <h4>Power</h4>
        </div>
        
        <div class="service-card" onclick="alert('Exam Pins Coming Soon!')">
            <div class="s-icon" style="background:#fef9c3; color:#ca8a04;"><i class="fas fa-graduation-cap"></i></div>
            <h4>Exam Pin</h4>
        </div>
        
        <div class="service-card" onclick="alert('Marketplace Coming Soon!')">
            <div class="s-icon" style="background:#f3f4f6; color:#4b5563;"><i class="fas fa-shopping-bag"></i></div>
            <h4>Products</h4>
        </div>
    </div>

    <h3 style="margin-bottom: 15px; color: var(--secondary); font-size: 1.1rem;">Recent Activity</h3>
    <div class="table-container">
        <table>
            <thead><tr><th>Service</th><th>Amount</th><th>Status</th></tr></thead>
            <tbody>
                <?php while($r=$txns->fetch_assoc()): ?>
                <tr>
                    <td>
                        <div style="font-weight: 600; font-size: 0.9rem;"><?php echo strtoupper(str_replace('_', ' ', $r['transaction_type'])); ?></div>
                        <small style="color: #94a3b8; font-size: 0.75rem;"><?php echo date('d/m H:i', strtotime($r['created_at'])); ?></small>
                    </td>
                    <td style="font-weight: 600;">₦<?php echo number_format($r['amount'],2); ?></td>
                    <td><span class="badge <?php echo $r['status']=='success'?'success':'failed'; ?>"><?php echo ucfirst($r['status']); ?></span></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="dataModal" class="modal">
    <div class="modal-box">
        <span class="close-btn" onclick="closeModal('dataModal')">&times;</span>
        <h3 style="text-align:center; margin-bottom:20px; color:var(--primary);">Buy Data</h3>
        <form id="dataForm">
            <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
            <input type="hidden" name="purchase_data" value="1">
            <input type="hidden" name="amount" id="hidden_amount">
            <input type="hidden" name="plan_name" id="hidden_plan_name">
            
            <div class="network-grid">
                <div class="net-opt" onclick="selIcon(this, 'dataNet', '1')"><img src="assets/images/mtn.png"><div class="net-label"></div></div>
                <div class="net-opt" onclick="selIcon(this, 'dataNet', '3')"><img src="assets/images/airtel.png"><div class="net-label"></div></div>
                <div class="net-opt" onclick="selIcon(this, 'dataNet', '2')"><img src="assets/images/glo.png"><div class="net-label"></div></div>
                <div class="net-opt" onclick="selIcon(this, 'dataNet', '4')"><img src="assets/images/9mobile.png"><div class="net-label"></div></div>
            </div>
            <input type="hidden" name="network" id="dataNet">
            
            <div class="form-group">
                <label>Category</label>
                <select name="category" id="dataCategory" class="form-control" onchange="populatePlans()" disabled>
                    <option value="">Select Network First</option>
                </select>
            </div>

            <div class="form-group"><label>Phone</label><input type="tel" name="phone" class="form-control" placeholder="080..." required></div>
            
            <div class="form-group">
                <label>Plan</label>
                <select name="plan" id="dataPlan" class="form-control" onchange="updatePrice()" disabled>
                    <option value="">Select Category First</option>
                </select>
                <div id="price_display"></div>
            </div>
            
            <div class="form-group"><label>PIN</label><input type="password" name="pin" class="form-control" maxlength="4" style="text-align:center; letter-spacing:5px;" required></div>
            <button type="button" class="btn-main" onclick="buy('dataForm', 'api/buy_data.php')">Buy Data</button>
        </form>
    </div>
</div>

<div id="airtimeModal" class="modal">
    <div class="modal-box">
        <span class="close-btn" onclick="closeModal('airtimeModal')">&times;</span>
        <h3 style="text-align:center; margin-bottom:20px; color:var(--primary);">Buy Airtime</h3>
        <form id="airtimeForm">
            <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
            <input type="hidden" name="airtime_type" value="VTU">
            <div class="network-grid">
                <div class="net-opt" onclick="selIcon(this, 'airNet', 'MTN')"><img src="assets/images/mtn.png"></div>
                <div class="net-opt" onclick="selIcon(this, 'airNet', 'AIRTEL')"><img src="assets/images/airtel.png"></div>
                <div class="net-opt" onclick="selIcon(this, 'airNet', 'GLO')"><img src="assets/images/glo.png"></div>
                <div class="net-opt" onclick="selIcon(this, 'airNet', '9MOBILE')"><img src="assets/images/9mobile.png"></div>
            </div>
            <input type="hidden" name="network" id="airNet">
            <div class="form-group"><label>Phone</label><input type="tel" name="mobile_number" class="form-control" placeholder="080..." onkeyup="detectNet(this.value, 'airtimeModal')" required></div>
            <div class="form-group"><label>Amount</label><input type="number" name="amount" class="form-control" placeholder="500" required></div>
            <div class="form-group"><label>PIN</label><input type="password" name="pin" class="form-control" maxlength="4" style="text-align:center; letter-spacing:5px;" required></div>
            <button type="button" class="btn-main" onclick="buy('airtimeForm', 'api/buy_airtime.php')">Buy Airtime</button>
        </form>
    </div>
</div>

<div id="cableModal" class="modal">
    <div class="modal-box">
        <span class="close-btn" onclick="closeModal('cableModal')">&times;</span>
        <h3 style="text-align:center; margin-bottom:20px; color:var(--primary);">Cable TV</h3>
        <form id="cableForm">
            <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
            <div class="network-grid">
                <div class="net-opt" onclick="selIcon(this, 'cableProv', 'DSTV'); loadCablePlans('DSTV')"><img src="assets/images/dstv.png"></div>
                <div class="net-opt" onclick="selIcon(this, 'cableProv', 'GOTV'); loadCablePlans('GOTV')"><img src="assets/images/gotv.png"></div>
                <div class="net-opt" onclick="selIcon(this, 'cableProv', 'STARTIMES'); loadCablePlans('STARTIMES')"><img src="assets/images/startimes.png"></div>
            </div>
            <input type="hidden" name="cablename" id="cableProv">
            <div class="form-group"><label>Smart Card / IUC</label><input type="text" name="smart_card_number" class="form-control" required></div>
            <div class="form-group"><label>Package</label><select name="cableplan" id="cablePlan" class="form-control"><option>Select Provider First</option></select></div>
            <div class="form-group"><label>PIN</label><input type="password" name="pin" class="form-control" maxlength="4" style="text-align:center; letter-spacing:5px;" required></div>
            <button type="button" class="btn-main" onclick="buy('cableForm', 'api/buy_cable_tv.php')">Subscribe</button>
        </form>
    </div>
</div>

<div id="electricModal" class="modal">
    <div class="modal-box">
        <span class="close-btn" onclick="closeModal('electricModal')">&times;</span>
        <h3 style="text-align:center; margin-bottom:20px; color:var(--primary);">Pay Electricity</h3>
        <form id="electricForm">
            <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
            <div class="network-grid">
                <div class="net-opt" onclick="selIcon(this, 'discoName', 'ikeja')"><img src="assets/images/ikeja.png"></div>
                <div class="net-opt" onclick="selIcon(this, 'discoName', 'eko')"><img src="assets/images/eko.png"></div>
                <div class="net-opt" onclick="selIcon(this, 'discoName', 'abuja')"><img src="assets/images/abuja.png"></div>
                <div class="net-opt" onclick="selIcon(this, 'discoName', 'kano')"><img src="assets/images/kano.png"></div>
            </div>
            <input type="hidden" name="disco_name" id="discoName">
            <div class="form-group"><label>Meter Type</label><select name="meter_type" class="form-control"><option value="prepaid">Prepaid</option><option value="postpaid">Postpaid</option></select></div>
            <div class="form-group"><label>Meter No</label><input type="text" name="meter_number" class="form-control" required></div>
            <div class="form-group"><label>Amount</label><input type="number" name="amount" class="form-control" required></div>
            <div class="form-group"><label>PIN</label><input type="password" name="pin" class="form-control" maxlength="4" style="text-align:center; letter-spacing:5px;" required></div>
            <button type="button" class="btn-main" onclick="buy('electricForm', 'api/purchase_electric.php')">Pay Bill</button>
        </form>
    </div>
</div>

<div id="fundModal" class="modal">
    <div class="modal-box">
        <span class="close-btn" onclick="closeModal('fundModal')">&times;</span>
        <h3>Fund Wallet</h3>
        <p style="font-size:0.9rem; color:#64748b; margin-bottom:15px;">Transfer to your personal account:</p>
        <?php if($vacc): ?>
            <div style="background:#f1f5f9; padding:20px; border-radius:15px; text-align:center; margin-bottom:20px;">
                <div style="font-size:0.9rem; text-transform:uppercase;"><?php echo $vacc['bank_name']; ?></div>
                <div style="font-size:1.6rem; font-weight:700; color:var(--primary); margin:5px 0;"><?php echo $vacc['account_number']; ?></div>
                <div style="font-size:0.9rem; opacity:0.8;"><?php echo $vacc['account_name']; ?></div>
            </div>
            <button class="btn-main" onclick="navigator.clipboard.writeText('<?php echo $vacc['account_number']; ?>'); alert('Account Copied')">Copy Number</button>
        <?php else: ?>
             <div class="form-group"><label>Amount</label><input type="number" id="fundAmt" class="form-control"></div>
             <div id="fundRes" style="background:#e0f2fe; padding:15px; border-radius:10px; display:none; margin:15px 0; color:#0284c7;">
                Admin Account:<br><b><?php echo $settings['account_no']; ?></b>
             </div>
             <button class="btn-main" onclick="document.getElementById('fundRes').style.display='block'">Show Admin Account</button>
        <?php endif; ?>
    </div>
</div>

<div id="settingsModal" class="modal">
    <div class="modal-box">
        <span class="close-btn" onclick="closeModal('settingsModal')">&times;</span>
        <h3><?php echo $has_pin ? 'Change PIN' : 'Create PIN'; ?></h3>
        <?php if(!$has_pin): ?>
            <p style="color:red; font-size:0.85rem; margin-bottom:15px;">You must set a PIN to perform transactions.</p>
        <?php endif; ?>
        <form action="api/set_pin.php" method="POST">
            <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
            <div class="form-group"><label>New PIN</label><input type="password" name="pin" maxlength="4" class="form-control" style="text-align:center; letter-spacing:5px;" placeholder="****" required></div>
            <button class="btn-main">Save PIN</button>
        </form>
    </div>
</div>

<div id="supportModal" class="modal">
    <div class="modal-box">
        <span class="close-btn" onclick="closeModal('supportModal')">&times;</span>
        <h3>Contact Support</h3>
        <form id="supportForm">
            <input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
            <div class="form-group">
                <label>Subject</label>
                <select name="subject" class="form-control">
                    <option value="Transaction Issue">Transaction Failed</option>
                    <option value="Funding Issue">Wallet Funding</option>
                    <option value="API Issue">API/Developer</option>
                    <option value="Other">Other</option>
                </select>
            </div>
            <div class="form-group">
                <label>Message</label>
                <textarea name="message" class="form-control" rows="5" required style="height:100px; resize:none;"></textarea>
            </div>
            <button type="button" class="btn-main" onclick="submitTicket()">Submit Ticket</button>
        </form>
    </div>
</div>

<a href="https://wa.me/2348066540390?text=Hello%20Asaad%20Data,%20I%20need%20assistance%20with%20my%20account." 
   target="_blank" 
   class="whatsapp-float">
    <i class="fab fa-whatsapp"></i>
    <span class="tooltip">Need Help? Chat with us!</span>
</a>

<style>
    .whatsapp-float { position: fixed; width: 60px; height: 60px; bottom: 30px; right: 30px; background-color: #25d366; color: #FFF; border-radius: 50px; text-align: center; font-size: 30px; box-shadow: 0 4px 15px rgba(0,0,0,0.2); z-index: 1000; display: flex; align-items: center; justify-content: center; text-decoration: none; transition: all 0.3s ease; animation: pulse-green 2s infinite; }
    .whatsapp-float:hover { background-color: #128C7E; transform: scale(1.1); }
    .tooltip { position: absolute; right: 70px; background-color: #333; color: #fff; padding: 5px 12px; border-radius: 5px; font-size: 14px; white-space: nowrap; opacity: 0; visibility: hidden; transition: opacity 0.3s; }
    .whatsapp-float:hover .tooltip { opacity: 1; visibility: visible; }
    @keyframes pulse-green { 0% { box-shadow: 0 0 0 0 rgba(37, 211, 102, 0.7); } 70% { box-shadow: 0 0 0 15px rgba(37, 211, 102, 0); } 100% { box-shadow: 0 0 0 0 rgba(37, 211, 102, 0); } }
</style>

<script>
    const userHasPin = <?php echo $has_pin; ?>;

    function toggleSidebar() { document.querySelector('.sidebar').classList.toggle('active'); document.querySelector('.overlay-bg').classList.toggle('active'); }
    function closeModal(id) { document.getElementById(id).style.display='none'; }
    
    function openModal(id) { 
        if (!userHasPin && (id === 'dataModal' || id === 'airtimeModal' || id === 'cableModal' || id === 'electricModal')) {
            if(confirm("You need to set a Transaction PIN first. Create one now?")) {
                document.getElementById('settingsModal').style.display='flex';
            }
            return;
        }
        document.getElementById(id).style.display='flex'; 
    }

    // === FULL DATA CONFIGURATION (Based on your Alumma List) ===
    const dataConfig = {
        "1": { "SME": [{id:30, name:"1.5GB 7DAYS", price:980}, {id:36, name:"2.7GB 30DAYS", price:1960}, {id:37, name:"6GB 7DAYS", price:2450}, {id:49, name:"3.5GB 30DAYS", price:2450}, {id:59, name:"10GB 30DAYS", price:4400}, {id:65, name:"11GB 7DAYS", price:3450}, {id:72, name:"2GB 30DAYS", price:1470}, {id:233, name:"2GB", price:1200}, {id:236, name:"1GB Smart Daily", price:250}, {id:237, name:"1GB", price:500}, {id:240, name:"1GB", price:550}, {id:239, name:"1GB 30DAYS", price:550}, {id:153, name:"500MB 7DAYS", price:350}, {id:196, name:"2GB 30DAYS", price:1000}, {id:195, name:"1GB 30DAYS", price:500}], "SME2": [{id:113, name:"2GB 7DAYS", price:800}, {id:112, name:"1GB 7DAYS", price:400}, {id:114, name:"3GB 7DAYS", price:1200}, {id:102, name:"20GB 7DAYS", price:4900}, {id:151, name:"5GB 30DAYS", price:1800}, {id:99, name:"500MB 7DAYS", price:300}], "Gifting": [{id:6, name:"1GB 1DAY", price:495}, {id:18, name:"2.5GB 2DAYS", price:900}, {id:33, name:"75MB 1DAY", price:75}, {id:41, name:"110MB 1DAY", price:100}, {id:66, name:"2GB 1DAY", price:740}, {id:101, name:"500MB 7DAYS", price:350}, {id:118, name:"1GB 7DAYS", price:600}, {id:168, name:"36GB 30 DAYS", price:10800}, {id:169, name:"6GB 7DAYS", price:2450}, {id:175, name:"1GB 7DAYS", price:600}, {id:198, name:"1GB Social 7DAYS", price:350}, {id:199, name:"2GB TikTok 7DAYS", price:450}, {id:211, name:"230MB 1DAY", price:200}, {id:212, name:"1.5GB 2DAYS", price:600}, {id:213, name:"1.5GB 7DAYS", price:980}, {id:214, name:"110MB 1DAY", price:100}, {id:215, name:"1GB+ Bonus 7DAYS", price:785}, {id:216, name:"1GB 7DAYS", price:600}, {id:217, name:"1GB Social 7DAYS", price:350}, {id:218, name:"1.2GB Social 30DAYS", price:500}], "Promo": [{id:5, name:"110MB 1DAY", price:100}, {id:7, name:"7GB 30DAYS", price:3450}, {id:11, name:"1GB 1DAY", price:490}, {id:31, name:"2GB 2DAYS", price:750}, {id:38, name:"230MB 1DAY", price:200}, {id:96, name:"1GB 7DAYS", price:550}, {id:117, name:"1GB 7DAYS", price:550}, {id:138, name:"500MB 7DAYS", price:355}, {id:98, name:"500MB 7DAYS", price:300}, {id:137, name:"500MB 7DAYS", price:300}], "Weekly": [{id:225, name:"20GB 7DAYS", price:4900}, {id:226, name:"3.5GB 7DAYS", price:1500}, {id:227, name:"470MB Social", price:250}, {id:79, name:"1.5GB 7DAYS", price:980}, {id:81, name:"6GB 7DAYS", price:2450}, {id:88, name:"2GB 7DAYS", price:900}, {id:89, name:"3GB 7DAYS", price:1350}, {id:232, name:"5GB 30DAYS", price:2000}, {id:91, name:"1GB 7DAYS", price:450}, {id:133, name:"500MB 7DAYS", price:350}], "Smart Bundle": [{id:238, name:"7GB 2DAYS", price:1750}, {id:234, name:"1GB Daily", price:220}, {id:235, name:"2.5GB Daily", price:520}, {id:246, name:"MTN TEST 20GB", price:100}] },
        "2": { "Awoof": [{id:77, name:"2GB 1DAY", price:485}, {id:82, name:"1.5GB 1DAY", price:290}, {id:86, name:"1GB 1DAY", price:290}, {id:83, name:"2.5GB 2DAYS", price:485}, {id:160, name:"6GB 2DAYS", price:960}, {id:249, name:"10GB 30DAYS", price:2900}, {id:247, name:"1.5GB 7DAYS", price:485}, {id:87, name:"750MB 1DAY", price:195}, {id:85, name:"10GB 7DAYS", price:1900}, {id:248, name:"5GB 30DAYS", price:1460}], "Corporate": [{id:228, name:"6.15GB 30DAYS", price:2000}, {id:10, name:"500MB 30 Days", price:200}, {id:229, name:"7.25GB 30DAYS", price:2500}, {id:39, name:"1GB 30 Days", price:405}, {id:3, name:"10GB 30 Days", price:4050}, {id:231, name:"3.5GB 7DAYS", price:1100}, {id:50, name:"2GB 30 Days", price:810}, {id:243, name:"3GB 30 Days", price:1215}, {id:245, name:"1GB 7DAYS", price:320}, {id:244, name:"3GB 14DAYS", price:1000}], "Gifting": [{id:230, name:"3.5GB 7DAYS", price:1100}, {id:142, name:"1GB 3DAYS", price:300}, {id:143, name:"1GB 7DAYS", price:360}, {id:144, name:"3GB 7DAYS", price:1070}, {id:146, name:"5GB 7DAYS", price:1480}, {id:242, name:"1GB 3 DAYS", price:300}] },
        "3": { "Awoof": [{id:61, name:"600 MB 2DAYS", price:200}, {id:128, name:"3GB 2DAYS", price:750}, {id:149, name:"10GB 30DAYS", price:3000}, {id:207, name:"2GB 2DAYS", price:500}, {id:197, name:"6.5GB 7 DAYS", price:1050}, {id:189, name:"1.5GB 1DAY", price:410}, {id:201, name:"1GB 3 DAYS", price:295}, {id:194, name:"150MB 1DAY", price:50}, {id:193, name:"5GB 7DAYS", price:1480}, {id:223, name:"300MB 1DAY", price:100}, {id:224, name:"7GB 7DAYS", price:2000}], "Corporate": [{id:32, name:"8GB 30 Days", price:2870}, {id:40, name:"10GB 30 Days", price:3830}, {id:35, name:"1GB 7DAYS", price:765}, {id:71, name:"4GB 30DAYS", price:2400}, {id:48, name:"500MB 7DAYS", price:480}, {id:56, name:"2GB 30DAYS", price:1440}, {id:123, name:"1.5GB 7DAYS", price:960}, {id:155, name:"13GB 30 DAYS", price:4750}, {id:162, name:"5GB 2DAYS", price:1470}, {id:183, name:"1GB 3 DAYS", price:295}, {id:219, name:"5GB 7DAYS", price:1500}, {id:220, name:"3GB 30DAYS", price:1900}], "Gifting": [{id:16, name:"10GB 7DAYS", price:2870}, {id:29, name:"3.5GB 7DAYS", price:1435}, {id:70, name:"1.5GB 7DAYS", price:980}, {id:73, name:"500MB 7DAYS", price:490}, {id:46, name:"6GB 7DAYS", price:2400}, {id:62, name:"18GB 7DAYS", price:4800}, {id:125, name:"1.5GB 1DAY", price:480}, {id:157, name:"3GB 2DAYS", price:750}, {id:159, name:"5GB 7DAYS", price:1450}, {id:158, name:"1.5GB 2DAYS", price:600}, {id:161, name:"5GB 2DAYS", price:1450}, {id:156, name:"1.5GB 7DAYS", price:580}, {id:250, name:"3.2GB 3 DAYS", price:550}, {id:221, name:"1.5GB Social 7Days", price:500}, {id:222, name:"500MB 1DAY", price:350}] },
        "4": { "SME": [{id:106, name:"500MB 30DAYS", price:130}, {id:108, name:"500MB 30DAYS", price:100}], "Corporate": [{id:109, name:"500MB 30DAYS", price:100}, {id:110, name:"1GB 30 Days", price:200}], "Gifting": [{id:69, name:"1GB 30DAYS", price:500}, {id:80, name:"1GB 30DAYS", price:500}, {id:107, name:"500MB", price:100}, {id:111, name:"1GB 30DAYS", price:200}, {id:119, name:"500MB 30DAYS", price:190}, {id:120, name:"2GB 30DAYS", price:740}, {id:121, name:"3GB 30DAYS", price:1110}, {id:122, name:"10GB 30DAYS", price:3700}] }
    };

    function selIcon(el, inputId, val) {
        el.parentNode.querySelectorAll('.net-opt').forEach(e=>e.classList.remove('active'));
        el.classList.add('active');
        document.getElementById(inputId).value = val;
        
        if(inputId === 'dataNet') {
            populateCategories(val);
        }
    }

    function populateCategories(netId) {
        const catSelect = document.getElementById("dataCategory");
        const planSelect = document.getElementById("dataPlan");
        const priceBox = document.getElementById("price_display");

        catSelect.innerHTML = '<option value="">Select Category</option>';
        planSelect.innerHTML = '<option value="">Select Category First</option>';
        planSelect.disabled = true;
        catSelect.disabled = true;
        priceBox.style.display = "none";

        if (netId && dataConfig[netId]) {
            catSelect.disabled = false;
            Object.keys(dataConfig[netId]).forEach(cat => {
                let opt = document.createElement("option");
                opt.value = cat;
                opt.textContent = cat;
                catSelect.appendChild(opt);
            });
        }
    }

    function populatePlans() {
        const netId = document.getElementById("dataNet").value;
        const cat = document.getElementById("dataCategory").value;
        const planSelect = document.getElementById("dataPlan");
        const priceBox = document.getElementById("price_display");

        planSelect.innerHTML = '<option value="">Select Plan</option>';
        priceBox.style.display = "none";

        if (netId && cat && dataConfig[netId][cat]) {
            planSelect.disabled = false;
            dataConfig[netId][cat].forEach(p => {
                let opt = document.createElement("option");
                opt.value = p.id;
                opt.textContent = p.name;
                opt.dataset.price = p.price;
                planSelect.appendChild(opt);
            });
        } else {
            planSelect.disabled = true;
        }
    }

    function updatePrice() {
        const sel = document.getElementById("dataPlan").options[document.getElementById("dataPlan").selectedIndex];
        if(sel.value) {
            document.getElementById("price_display").style.display = 'block';
            document.getElementById("price_display").textContent = "You Pay: ₦" + parseInt(sel.dataset.price).toLocaleString();
            document.getElementById("hidden_amount").value = sel.dataset.price;
            document.getElementById("hidden_plan_name").value = sel.textContent;
        } else {
            document.getElementById("price_display").style.display = 'none';
        }
    }

    function detectNet(val, modalId) {
        const pfx = {'MTN':['0803','0806','0813','0703','0706','0810','0814','0903','0906','0913','0916'], 'GLO':['0805','0807','0705','0815','0811','0905','0915'], 'AIRTEL':['0802','0808','0708','0812','0701','0902','0907','0901','0912','0904'], '9MOBILE':['0809','0818','0817','0909','0908']};
        if(val.length < 4) return;
        let pre = val.substring(0,4);
        for(let n in pfx) {
            if(pfx[n].includes(pre)) {
                let icons = document.querySelectorAll(`#${modalId} .net-opt`);
                icons.forEach(i => { if(i.innerHTML.includes(n.toLowerCase() + '.png')) i.click(); });
            }
        }
    }

    function loadCablePlans(prov) {
        let sel = document.getElementById('cablePlan'); sel.innerHTML = "";
        let plans = (prov==='DSTV') ? ['Padi - 5750', 'Yanga - 7000', 'Confam - 12400'] : (prov==='GOTV') ? ['Smallie - 1500', 'Jinja - 3300', 'Jolli - 4850'] : ['Nova - 1500', 'Basic - 2600'];
        plans.forEach(p => { let o = document.createElement('option'); o.value=p.split(' - ')[0]; o.text=p; sel.add(o); });
    }

    function generateAccount() {
        let btn = event.target; btn.innerText="Generating..."; btn.disabled=true;
        let fd = new FormData(); fd.append('user_id', <?php echo $user_id; ?>);
        fetch('api/generate_account.php', {method:'POST', body:fd})
        .then(r=>r.json()).then(d=>{ alert(d.message); if(d.status==='success') location.reload(); else { btn.innerText="Try Again"; btn.disabled=false; } })
        .catch(e=>{alert("Error"); btn.disabled=false;});
    }

    function copyRef() {
        var copyText = document.getElementById("myRefLink");
        copyText.select();
        copyText.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(copyText.value);
        alert("Referral Link Copied!");
    }

    function buy(fid, url) {
        let form = document.getElementById(fid);
        if(!form.checkValidity()) { alert("Fill all fields"); return; }
        
        let btn = form.querySelector('.btn-main'); 
        let old = btn.innerText; 
        btn.innerText="Processing..."; 
        btn.disabled=true;
        
        fetch(url, {method:'POST', body:new FormData(form)})
        .then(r=>r.json()).then(d=>{
            alert(d.message); 
            
            if(d.status==='success') {
                form.reset(); 
                location.reload(); 
            } else { 
                btn.innerText=old; 
                btn.disabled=false; 
            } 
        })
        .catch(e=>{ 
            alert("Connection Error"); 
            btn.innerText=old; 
            btn.disabled=false; 
        });
    }

    function dismissNotif(id) {
        document.getElementById('notif-'+id).style.display = 'none';
        let fd = new FormData(); fd.append('id', id);
        fetch('api/mark_notification_read.php', { method: 'POST', body: fd });
    }

    function submitTicket() {
        let form = document.getElementById('supportForm');
        if(!form.checkValidity()) { alert("Please fill all fields"); return; }
        let btn = form.querySelector('.btn-main'); let old = btn.innerText; btn.innerText="Sending..."; btn.disabled=true;
        fetch('api/create_ticket.php', { method: 'POST', body: new FormData(form) })
        .then(res => res.json()).then(data => {
            alert(data.message); if(data.status === 'success') { form.reset(); closeModal('supportModal'); }
            btn.innerText = old; btn.disabled = false;
        }).catch(err => { alert("Error"); btn.disabled = false; });
    }
    
    // 1. Force Clear All Inputs on Page Load (EXCEPT Refer ID)
    window.onload = function() {
        document.querySelectorAll("form").forEach(function(f) {
            f.reset();
            f.setAttribute("autocomplete", "off");
        });
        
        document.querySelectorAll("input").forEach(function(i) {
            // FIX: DO NOT CLEAR the referral link input
            if(i.type !== 'hidden' && i.type !== 'submit' && i.id !== 'myRefLink') {
                i.value = "";
                i.setAttribute("autocomplete", "off");
            }
        });

        // AUTO-OPEN PIN MODAL IF NOT SET
        if (!userHasPin) {
            setTimeout(() => { 
                document.getElementById('settingsModal').style.display='flex'; 
                // Optional: alert("Please set a Transaction PIN to secure your account."); 
            }, 1500);
        }
    };

    // 2. Prevent Form Resubmission on Refresh
    if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
    }

    // --- MOBILE SLIDER LOGIC ---
    let currentSlide = 0;
    const slides = document.querySelectorAll('.mobile-slide');
    
    function showSlide(index) {
        slides.forEach((slide, i) => {
            slide.classList.remove('active');
            if (i === index) slide.classList.add('active');
        });
        
        // Determine duration based on slide type (Text or Image)
        const type = slides[index].getAttribute('data-type');
        let duration = (type === 'text') ? 4000 : 8000; // 4s for text, 8s for images
        
        setTimeout(nextSlide, duration);
    }

    function nextSlide() {
        currentSlide = (currentSlide + 1) % slides.length;
        showSlide(currentSlide);
    }

    // Initialize Slider only if on mobile and slides exist
    if (window.innerWidth <= 768 && slides.length > 0) {
        showSlide(0); // Start the loop
    }
</script>
</body>
</html>