<?php 
   session_start();
   ini_set('display_errors', 1);
   ini_set('display_startup_errors', 1);
   error_reporting(E_ALL);
   mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
   
   include("header.php");
   
   if (!isset($_SESSION['customerid'])) {
       header('Location:login.php?error=nologin');
       exit;
   }
   
   $dts = date("l jS \of F Y");
   
   // Update Last Login
   $stmt = $con->prepare("UPDATE customers SET lastlogin=? WHERE customerid=?");
   $stmt->bind_param("ss", $dts, $_SESSION['customerid']);
   $stmt->execute();
   $stmt->close();
   
   // Fetch Accounts
   $stmt = $con->prepare("SELECT * FROM accounts WHERE customerid=?");
   $stmt->bind_param("s", $_SESSION['customerid']);
   $stmt->execute();
   $results = $stmt->get_result();
   $rowrec = $results->fetch_assoc();
   $stmt->close();
   
   // Fetch Customer
   $stmt = $con->prepare("SELECT * FROM customers WHERE customerid=?");
   $stmt->bind_param("s", $_SESSION['customerid']);
   $stmt->execute();
   $results2 = $stmt->get_result();
   $rowrec1 = $results2->fetch_assoc();
   $stmt->close();
   
   // Handle Deposit Logic
   if (isset($_POST['deposit'])) {
       $now = floatval($_POST['mone']); 
       $lid = intval($_POST['lid']);
       $amt = floatval($_POST['amt']);
       $dt = date("Y-m-d H:i:s");
       $stmt = $con->prepare("UPDATE accounts SET accountbalance = accountbalance + ? WHERE customerid=?");
       $stmt->bind_param("ds", $now, $_SESSION['customerid']);
       $stmt->execute();
       $stmt->close();
       echo "<script>window.location='dashboard.php';</script>";
       exit;
   }
   
   require_once __DIR__ . '/../config/topup_helpers.php';
   ensureTopupSchema($con);

   $recentFeed = [];
   $cidDash = $_SESSION['customerid'];
   $stmtTf = $con->prepare("SELECT *, 'transfer' AS feed_type FROM transfers WHERE sender = ? ORDER BY date DESC LIMIT 12");
   $stmtTf->bind_param("s", $cidDash);
   $stmtTf->execute();
   $resTf = $stmtTf->get_result();
   while ($r = $resTf->fetch_assoc()) {
       $r['_ts'] = strtotime($r['date']);
       $recentFeed[] = $r;
   }
   $stmtTf->close();

   $cidDashInt = (int) $cidDash;
   $stmtTu = $con->prepare("
       SELECT tr.*, pm.method_name, 'topup' AS feed_type
       FROM topup_requests tr
       INNER JOIN payment_methods pm ON pm.id = tr.method_id
       WHERE tr.customerid = ?
       ORDER BY tr.created_at DESC
       LIMIT 12
   ");
   $stmtTu->bind_param("i", $cidDashInt);
   $stmtTu->execute();
   $resTu = $stmtTu->get_result();
   while ($r = $resTu->fetch_assoc()) {
       $r['_ts'] = strtotime($r['created_at']);
       $recentFeed[] = $r;
   }
   $stmtTu->close();

   usort($recentFeed, static function ($a, $b) {
       return ($b['_ts'] ?? 0) <=> ($a['_ts'] ?? 0);
   });
   $recentFeed = array_slice($recentFeed, 0, 8);

   $card_last_12 = $_SESSION['card_long_digit'] ?? '4532112233445566';
   $fullCardNumber_formatted = implode(' ', str_split(preg_replace('/\D/', '', $card_last_12), 4));
   
   // --- STOCK DATA INTEGRATION ---
   $apiKey = "d5fq5thr01qnjhodtm9gd5fq5thr01qnjhodtma0"; 
   
   // Helper function for stock data
   function getStockData($symbol, $apiKey) {
       $url = "https://finnhub.io/api/v1/quote?symbol=" . $symbol . "&token=" . $apiKey;
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_TIMEOUT, 2); 
       $response = curl_exec($ch);
       curl_close($ch);
       $data = json_decode($response, true);
       if (!isset($data['c'])) {
           return ['price' => 0.00, 'change' => 0.00, 'percent' => 0.00];
       }
       return [
           'price' => $data['c'],       
           'change' => $data['d'],      
           'percent' => $data['dp']     
       ];
   }

   // Fetch top 3 stocks for dashboard
   $mini_symbols = [
       ['symbol' => 'AAPL', 'name' => 'Apple', 'icon' => 'bx bxl-apple'], 
       ['symbol' => 'TSLA', 'name' => 'Tesla', 'icon' => 'bx bxs-car'], 
       ['symbol' => 'NVDA', 'name' => 'NVIDIA', 'icon' => 'bx bx-chip']
   ];
   
   $mini_stocks = [];
   $current_prices = [];
   
   foreach ($mini_symbols as $s) {
       $apiData = getStockData($s['symbol'], $apiKey);
       $current_prices[$s['symbol']] = $apiData['price']; 
       $mini_stocks[] = array_merge($s, [
           'price' => $apiData['price'], 
           'change' => number_format($apiData['change'], 2), 
           'trend' => ($apiData['change'] >= 0 ? 'up' : 'down'),
           'percent' => number_format($apiData['percent'], 2)
       ]);
   }
   
   // Define the query before calling prepare()
   $portfolio_query = "SELECT symbol, stock_name, SUM(quantity) as shares_owned, 
                       SUM(CASE WHEN quantity > 0 THEN total_cost ELSE 0 END) / 
                       NULLIF(SUM(CASE WHEN quantity > 0 THEN quantity ELSE 0 END), 0) as avg_buy_price 
                       FROM stock_orders WHERE customerid = ? 
                       GROUP BY symbol HAVING shares_owned > 0";

   // Now your existing line 66 will work correctly
   $p_stmt_summary = $con->prepare($portfolio_query);
   
   $total_market_value = 0;
   $total_investment_cost = 0;
   $total_shares_quantity = 0; 

   // Re-fetch portfolio data for summary
   $p_stmt_summary = $con->prepare($portfolio_query);
   $p_stmt_summary->bind_param("s", $_SESSION['customerid']);
   $p_stmt_summary->execute();
   $summary_res = $p_stmt_summary->get_result();

   while($s_row = $summary_res->fetch_assoc()) {
       $current_p = $current_prices[$s_row['symbol']] ?? $s_row['avg_buy_price'];
       $total_market_value += ($s_row['shares_owned'] * $current_p);
       $total_investment_cost += ($s_row['shares_owned'] * $s_row['avg_buy_price']);
       $total_shares_quantity += $s_row['shares_owned'];
   }
   $p_stmt_summary->close();

   $total_profit_loss = $total_market_value - $total_investment_cost;
   $p_l_color = ($total_profit_loss >= 0) ? '#10b981' : '#ef4444';
   $p_l_prefix = ($total_profit_loss >= 0) ? '+' : '';
   
   $cur = '$'; 
   $q = mysqli_query($con, "SELECT currency FROM system_settings LIMIT 1");
   if($r = mysqli_fetch_assoc($q)) $cur = $r['currency'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Dashboard | <?php echo $sbank ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --glass-bg: rgba(255, 255, 255, 0.95);
            --glass-border: rgba(255, 255, 255, 0.3);
            --primary-blue: #003399;
            --deep-navy: #001a4d;
            --accent-cyan: #00f2fe;
            --surface-color: #f0f4f8;
            --text-main: #1a202c;
            --3d-shadow: 0 20px 40px rgba(0,0,0,0.1), 0 5px 15px rgba(0,0,0,0.05);
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background: #f4f7fa;
            background-image: radial-gradient(at 0% 0%, rgba(0, 51, 153, 0.05) 0, transparent 50%), 
                              radial-gradient(at 50% 0%, rgba(0, 93, 157, 0.05) 0, transparent 50%);
            color: var(--text-main);
            overflow-x: hidden;
            min-height: 100vh;
        }

        .glass-card {
            background: var(--glass-bg);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            box-shadow: var(--3d-shadow);
            padding: 1.25rem;
        }

        .premium-balance-box {
            background: linear-gradient(135deg, var(--deep-navy) 0%, var(--primary-blue) 100%);
            border-radius: 24px;
            padding: 28px;
            color: white;
            position: relative;
            overflow: hidden;
            box-shadow: 0 25px 50px -12px rgba(0, 51, 153, 0.5);
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .premium-balance-box::after {
            content: '';
            position: absolute;
            top: -20%; right: -10%;
            width: 300px; height: 300px;
            background: linear-gradient(45deg, transparent, rgba(255,255,255,0.08));
            border-radius: 50%;
            pointer-events: none;
        }

        .balance-glow {
            text-shadow: 0 0 20px rgba(0, 242, 254, 0.5);
            color: white;
            font-size: 2.6rem;
            font-weight: 800;
            letter-spacing: -2px;
            line-height: 1.2;
        }

        .action-node {
            background: white;
            border-radius: 16px;
            padding: 18px 14px;
            text-align: center;
            border: 1px solid #edf2f7;
            box-shadow: 0 4px 10px rgba(0,0,0,0.04);
            transition: all 0.3s ease;
            cursor: pointer;
            text-decoration: none;
            display: block;
        }

        .action-node:hover {
            background: var(--primary-blue);
            color: white !important;
            transform: translateY(-4px);
            box-shadow: 0 12px 24px -5px rgba(0, 51, 153, 0.3);
        }

        .action-node i {
            font-size: 1.8rem;
            margin-bottom: 8px;
            display: block;
            background: linear-gradient(135deg, #003399, #00f2fe);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            transition: all 0.3s ease;
        }
        
        .floating-card {
            background: linear-gradient(135deg, #0f0f0f 0%, #2a2a2a 100%);
            border: 1px solid rgba(255, 255, 255, 0.1);
            position: relative;
            overflow: hidden;
            padding: 22px !important;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }

        .card-inner-glow {
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle at center, rgba(0, 51, 153, 0.15) 0%, transparent 40%);
            pointer-events: none;
        }

        .card-chip-gold {
            width: 38px;
            height: 28px;
            background: linear-gradient(135deg, #d4af37 0%, #f9e29c 50%, #b8860b 100%);
            border-radius: 6px;
            position: relative;
            border: 1px solid rgba(0,0,0,0.1);
        }

        .card-chip-gold::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            width: 100%;
            height: 1px;
            background: rgba(0,0,0,0.2);
        }

        .card-number h4 {
            font-family: 'Courier New', monospace;
            color: #fff;
        }

        .card-footer-row span {
            text-shadow: 1px 1px 2px rgba(0,0,0,0.3);
        }
        
        .action-node:hover i { -webkit-text-fill-color: white; background: none; }
        .action-node h6 { color: #1a202c; margin: 0; font-size: 0.8rem; transition: color 0.3s ease; font-weight: 700; }
        .action-node:hover h6 { color: white !important; }

        .floating-card {
            background: linear-gradient(135deg, #1a1a1a 0%, #333 100%);
            border-radius: 18px;
            padding: 20px;
            color: white;
            min-height: 190px;
            position: relative;
            transform-style: preserve-3d;
            box-shadow: 0 20px 40px -12px rgba(0,0,0,0.3);
            background-image: url('https://www.transparenttextures.com/patterns/carbon-fibre.png');
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .floating-card .card-header-row { display: flex; justify-content: space-between; align-items: center; }
        .floating-card .card-number { margin: 14px 0; }
        .floating-card .card-footer-row { display: flex; justify-content: space-between; align-items: flex-end; }

        .mobile-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
        }

        .trans-item-new {
            display: flex;
            align-items: center;
            padding: 14px;
            margin-bottom: 8px;
            background: #fff;
            border-radius: 14px;
            border: 1px solid #f1f5f9;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .trans-item-new:hover {
            box-shadow: 0 6px 16px rgba(0,0,0,0.06);
            transform: translateY(-1px);
        }

        .avatar-sm {
            width: 40px; height: 40px;
            display: flex; align-items: center; justify-content: center;
            flex-shrink: 0;
        }

        .avatar-title {
            width: 100%; height: 100%;
            display: flex; align-items: center; justify-content: center;
            border-radius: 50%;
        }

        .analytics-pill {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            padding: 6px 12px;
            border-radius: 50px;
            font-size: 0.8rem;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .container-fluid {
            padding: 1.25rem 1rem;
            max-width: 1400px;
            margin: 0 auto;
        }

        .row { margin-left: -8px; margin-right: -8px; }
        .row > [class*='col-'] { padding-left: 8px; padding-right: 8px; }

        .btn-primary-subtle {
            background: rgba(0, 51, 153, 0.1);
            border: none;
            color: var(--primary-blue);
            font-weight: 700;
        }
        .btn-primary-subtle:hover { background: rgba(0, 51, 153, 0.2); color: var(--primary-blue); }

        .badge { padding: 5px 10px; border-radius: 8px; font-weight: 700; font-size: 0.72rem; }
        .bg-success-subtle { background: #d4edda; }
        .text-success { color: #28a745; }
        .bg-warning-subtle { background: #fff3cd; }
        .text-warning { color: #ffc107; }

        /* STOCK MINI CARD */
        .stock-mini-card {
            background: white;
            border-radius: 14px;
            padding: 14px;
            border: 1px solid #edf2f7;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }
        
        .stock-mini-card:hover {
            box-shadow: 0 6px 16px rgba(0,0,0,0.06);
            transform: translateY(-2px);
        }
        
        .stock-icon-mini {
            width: 36px;
            height: 36px;
            background: #e6efff;
            color: #003399;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            margin-right: 10px;
        }

        /* ACTIVITY CHART CARD - Desktop Only */
        .activity-chart-card {
            background: var(--glass-bg);
            backdrop-filter: blur(12px);
            border: 1px solid var(--glass-border);
            border-radius: 20px;
            padding: 1.25rem;
            box-shadow: var(--3d-shadow);
            display: none;
        }

        /* Make all text bold */
        body, h1, h2, h3, h4, h5, h6, p, span, div, a, label, small {
            font-weight: 600 !important;
        }
        
        .fw-bold, .fw-800, .fw-700 {
            font-weight: 800 !important;
        }

        /* Desktop: Tighter layout + Show chart */
        @media (min-width: 992px) {
            .container-fluid {
                max-width: 1600px;
                padding: 1rem 1.5rem;
            }
            
            .row.g-4 {
                --bs-gutter-x: 1rem;
                --bs-gutter-y: 1rem;
            }
            
            .premium-balance-box {
                padding: 24px;
                margin-bottom: 1rem !important;
            }
            
            .mobile-grid {
                gap: 10px;
            }
            
            .glass-card {
                padding: 1rem;
            }
            
            .floating-card {
                min-height: 180px;
            }
            
            .mb-4 {
                margin-bottom: 1rem !important;
            }
            
            .mb-3 {
                margin-bottom: 0.75rem !important;
            }

            /* Show chart on desktop */
            .activity-chart-card {
                display: block;
            }
        }

        /* Force modal to be white on ALL devices */
        .modal-content {
            background-color: #ffffff !important;
            border-radius: 20px !important;
            border: none !important;
        }

        .modal-body {
            background-color: #ffffff !important;
        }

        .modal-header {
            background-color: #ffffff !important;
        }

        #receiptModal .modal-content,
        #transferChoiceModal .modal-content {
            background-color: #ffffff !important;
        }

        #receiptModal .modal-body,
        #transferChoiceModal .modal-body {
            background-color: #ffffff !important;
        }

        #receiptModal h3, 
        #receiptModal h6, 
        #receiptModal span, 
        #receiptModal .fw-bold, 
        #receiptModal #r-status-text,
        #transferChoiceModal h5,
        #transferChoiceModal h6,
        #transferChoiceModal p {
            color: #0f172a !important;
        }

        #receiptModal .text-muted {
            color: #64748b !important;
        }

        /* ===== MOBILE — TIGHT SPACING ===== */
        @media (max-width: 768px) {
            .container-fluid { padding: 0.6rem 0.6rem !important; }
            .page-content { padding: 0 !important;  margin-top: 80px !important; }

            .premium-balance-box { 
                padding: 18px !important; 
                border-radius: 18px;
            }
            .balance-glow { font-size: 1.65rem !important; letter-spacing: -1px; }
            .balance-stats .col-4 small { font-size: 0.6rem !important; }
            .balance-stats .col-4 span { font-size: 0.75rem !important; }

            .mobile-grid { grid-template-columns: repeat(4, 1fr); gap: 6px; }
            .action-node { padding: 12px 6px !important; border-radius: 12px; }
            .action-node i { font-size: 1.4rem !important; margin-bottom: 4px !important; }
            .action-node h6 { font-size: 0.68rem !important; }

            .floating-card { padding: 14px !important; min-height: 160px; border-radius: 14px; margin: 0 5px; }
            .floating-card .card-number h4 { font-size: 0.95rem !important; letter-spacing: 2px !important; }
            .floating-card .card-number { margin: 8px 0 !important; }

            .glass-card { padding: 0.85rem !important; border-radius: 14px; }
            .glass-card h5 { font-size: 0.88rem !important; margin-bottom: 0.6rem !important; }
            .glass-card .d-flex { margin-bottom: 0.4rem !important; padding-bottom: 0.4rem !important; }
            .glass-card .d-flex span { font-size: 0.78rem; }

            .trans-item-new { padding: 10px !important; margin-bottom: 5px !important; border-radius: 10px; }
            .trans-item-new h6 { font-size: 0.78rem !important; }
            .trans-item-new h5 { font-size: 0.82rem !important; }
            .trans-item-new small { font-size: 0.65rem !important; }
            .avatar-sm { width: 34px !important; height: 34px !important; }

            .stock-mini-card { padding: 10px !important; margin-bottom: 6px !important; }
            .stock-icon-mini { width: 30px !important; height: 30px !important; font-size: 14px !important; }

            .row.g-4 { --bs-gutter-y: 0.5rem !important; --bs-gutter-x: 0.4rem !important; }
            .mb-4 { margin-bottom: 0.6rem !important; }
            .mb-3 { margin-bottom: 0.4rem !important; }
            .mt-5 { margin-top: 0.8rem !important; }
            .mt-4 { margin-top: 0.6rem !important; }
            h5.fw-bold.mb-3 { font-size: 0.85rem !important; }
            h4.fw-bold { font-size: 0.95rem !important; }
            .me-3 { margin-right: 0.6rem !important; }

            .main-content { padding-bottom: 70px; }

            .modal-content { border-radius: 18px !important; }
            .modal-body { padding: 0.85rem !important; }
            .modal-body h3 { font-size: 1.4rem !important; }
            .modal-body .d-flex { margin-bottom: 0.35rem !important; }
            .modal-body .d-flex span { font-size: 0.78rem !important; }
        }

        @media (max-width: 360px) {
            .balance-glow { font-size: 1.4rem !important; }
            .action-node i { font-size: 1.2rem !important; }
            .action-node h6 { font-size: 0.6rem !important; }
        }
    </style>
</head>

<body data-sidebar="colored">
    <div id="layout-wrapper">
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <div class="row g-4">
                        <div class="col-xl-8">
                            
                            <?php
                            // Clean balance (USDT / USD)
                            $usdBalance = (float) str_replace(',', '', $rowrec['accountbalance']);
                            $btcAmount  = 0.0000;
                            
                            // Binance BTC price API
                            $apiUrl = "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT";
                            
                            // cURL request
                            $ch = curl_init();
                            curl_setopt_array($ch, [
                                CURLOPT_URL => $apiUrl,
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_TIMEOUT => 10,
                                CURLOPT_SSL_VERIFYPEER => false
                            ]);
                            
                            $response = curl_exec($ch);
                            curl_close($ch);
                            
                            if ($response) {
                                $data = json_decode($response, true);
                            
                                if (isset($data['price']) && is_numeric($data['price'])) {
                                    $btcPrice = (float)$data['price'];
                            
                                    if ($btcPrice > 0 && $usdBalance > 0) {
                                        $btcAmount = $usdBalance / $btcPrice;
                                    }
                                }
                            }
                            ?>

                            <div class="premium-balance-box mb-4">
                                <div>
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                <div>
                                    <span class="opacity-75 text-uppercase small fw-bold d-block mb-1"
                                          style="letter-spacing: 2px; font-size: 0.68rem;">
                                        Available Balance
                                    </span>
                            
                                    <div class="d-flex align-items-center gap-2">
                                        <span class="fs-5 opacity-50"><?php echo $cur; ?></span>
                                        <h1 class="balance-glow mb-0" id="balance">
                                            <?php echo number_format($rowrec['accountbalance'], 2); ?>
                                        </h1>
                                        <i class="bx bx-show fs-4" id="toggle-icon"
                                           style="cursor:pointer; opacity:0.6;"></i>
                                    </div>
                                </div>
                            
                                <div class="text-end">
                                    <div class="analytics-pill mb-1">
                                        <i class="bx bx-trending-up"></i>
                                        <?php echo number_format($btcAmount, 4); ?> BTC
                                    </div>
                                    <small class="d-block opacity-75" style="font-size:0.7rem;">
                                        <?php echo $rowrec['accounttype']; ?>
                                    </small>
                                </div>
                            </div>

                                </div>
                               <div class="row balance-stats g-2 mt-4 pt-3" style="border-top: 1px solid rgba(255,255,255,0.1);">
                                    <div class="col-4">
                                        <small class="opacity-75 d-block mb-1" style="font-size:0.65rem; letter-spacing: 0.5px; text-transform: uppercase;">Portfolio Value</small>
                                        <span class="fw-bold d-block" style="font-size:0.9rem;">
                                            <?php echo $cur . number_format($total_market_value, 2); ?>
                                        </span>
                                    </div>
                                    
                                   <div class="col-4 border-start border-white border-opacity-10 px-3">
                                        <small class="opacity-75 d-block mb-1" style="font-size:0.65rem; letter-spacing: 0.5px; text-transform: uppercase;">Total Assets</small>
                                        <span class="fw-bold d-block" style="font-size:0.9rem; color: #ffffff;">
                                            <?php echo number_format($total_shares_quantity); ?> <small class="fw-normal opacity-50" style="font-size: 0.7rem;">Shares</small>
                                        </span>
                                    </div>
                                
                                    <div class="col-4 text-end border-start border-white border-opacity-10 px-3">
                                        <small class="opacity-75 d-block mb-1" style="font-size:0.65rem; letter-spacing: 0.5px; text-transform: uppercase;">Buying Power</small>
                                        <span class="fw-bold d-block" style="font-size:0.9rem;">
                                            <?php echo $cur . number_format($rowrec['accountbalance'], 2); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <h5 class="mb-3 fw-bold">Quick Actions</h5>
                            <div class="mobile-grid mb-4">
                                <div class="action-node" data-bs-toggle="modal" data-bs-target="#transferChoiceModal" style="cursor: pointer;">
                                    <i class="bx bxs-paper-plane"></i>
                                    <h6 class="mb-0 fw-bold">Transfer</h6>
                                </div>
                                <a href="topup.php" class="action-node">
                                    <i class="bx bx-wallet"></i>
                                    <h6 class="mb-0 fw-bold">Top Up</h6>
                                </a>
                                <a href="transferhistory.php" class="action-node">
                                    <i class="bx bx-data"></i>
                                    <h6 class="mb-0 fw-bold">History</h6>
                                </a>
                                <a href="pin.php" class="action-node">
                                    <i class="bx bxs-key"></i>
                                    <h6 class="mb-0 fw-bold">Security</h6>
                                </a>
                                <a href="stocks.php" class="action-node">
                                    <i class="bx bx-line-chart"></i>
                                    <h6 class="mb-0 fw-bold">Stocks</h6>
                                </a>
                                <a href="card.php" class="action-node">
                                    <i class="bx bxs-credit-card"></i>
                                    <h6 class="mb-0 fw-bold">Card</h6>
                                </a>
                                <a href="myprofile.php" class="action-node">
                                    <i class="bx bxs-user-detail"></i>
                                    <h6 class="mb-0 fw-bold">Account</h6>
                                </a>
                                <a href="logout.php" class="action-node" style="border-color:#fee2e2;">
                                    <i class="bx bx-log-out" style="background:linear-gradient(135deg,#ef4444,#f87171);-webkit-background-clip:text;"></i>
                                    <h6 class="mb-0 fw-bold" style="color:#ef4444;">Logout</h6>
                                </a>
                            </div>

                            <!-- DESKTOP ONLY: Activity Chart -->
                            <div class="activity-chart-card">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h5 class="fw-bold mb-0">Account Activity</h5>
                                    <span class="badge bg-primary-subtle text-primary" style="font-size: 0.7rem;">Last 7 Days</span>
                                </div>
                                <div id="activityChart" style="min-height: 180px;"></div>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <div class="floating-card mb-3">
                                <div class="card-inner-glow"></div>
                                
                                <div class="card-header-row">
                                    <img src="https://upload.wikimedia.org/wikipedia/commons/5/5e/Visa_Inc._logo.svg" height="18" style="filter: brightness(0) invert(1); opacity: 0.9;" alt="Visa">
                                    <i class="bx bx-wifi fs-4" style="transform: rotate(90deg); opacity: 0.8;"></i>
                                </div>
                            
                                <div class="card-chip-gold my-2"></div>
                            
                                <div class="card-number">
                                    <h4 class="fw-bold mb-0" style="letter-spacing: 4px; font-size: 1.2rem; text-shadow: 2px 2px 4px rgba(0,0,0,0.5);">
                                        <?php echo $fullCardNumber_formatted; ?>
                                    </h4>
                                </div>
                            
                                <div class="card-footer-row">
                                    <div>
                                        <small class="opacity-75 d-block" style="font-size: 0.6rem; letter-spacing: 1px;">CARD HOLDER</small>
                                        <span class="text-uppercase fw-bold" style="font-size: 0.85rem; letter-spacing: 1px;">
                                            <?php echo $_SESSION['customername']; ?>
                                        </span>
                                    </div>
                                    <div class="text-end">
                                        <small class="opacity-75 d-block" style="font-size: 0.6rem; letter-spacing: 1px;">EXPIRES</small>
                                        <span class="fw-bold" style="font-size: 0.85rem; letter-spacing: 1px;">
                                            <?php echo $_SESSION['valid_thru'] ?? '12/28'; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <div class="glass-card mb-3">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h5 class="fw-bold mb-0">Market Watch</h5>
                                    <a href="stocks.php" class="btn btn-sm btn-light rounded-pill px-3" style="font-size:0.7rem; font-weight: 700;">View All</a>
                                </div>
                                
                                <?php foreach($mini_stocks as $stock): ?>
                                <div class="stock-mini-card">
                                    <div class="d-flex align-items-center flex-grow-1">
                                        <div class="stock-icon-mini"><i class="<?php echo $stock['icon']; ?>"></i></div>
                                        <div>
                                            <h6 class="mb-0 fw-bold" style="font-size:0.85rem;"><?php echo $stock['symbol']; ?></h6>
                                            <small class="text-muted" style="font-size:0.7rem;"><?php echo $stock['name']; ?></small>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <div class="fw-bold" style="font-size:0.9rem;">$<?php echo number_format($stock['price'], 2); ?></div>
                                        <small class="<?php echo ($stock['trend'] == 'up') ? 'text-success' : 'text-danger'; ?> fw-bold" style="font-size:0.7rem;">
                                            <?php echo ($stock['trend'] == 'up') ? '↑' : '↓'; ?> <?php echo $stock['percent']; ?>%
                                        </small>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>

                            <div class="glass-card">
                                <h5 class="fw-bold mb-3">Account Details</h5>
                                <div class="d-flex justify-content-between mb-2 pb-2 border-bottom">
                                    <span class="text-muted">Account Number</span>
                                    <span class="fw-bold">****<?php echo substr($rowrec['accno'], -4); ?></span>
                                </div>
                                <div class="d-flex justify-content-between mb-2 pb-2 border-bottom">
                                    <span class="text-muted">Status</span>
                                    <span class="badge bg-success-subtle text-success">Verified</span>
                                </div>
                                <div class="d-flex justify-content-between mb-0">
                                    <span class="text-muted">Branch Code</span>
                                    <span class="fw-bold"><?php echo htmlspecialchars($rowrec1['ifsccode']); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mt-4">
                        <div class="col-lg-12">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h4 class="fw-bold text-dark mb-0">Recent Transactions</h4>
                                <a href="statement.php" class="btn btn-sm btn-light rounded-pill px-3" style="font-size:0.75rem; font-weight: 700;">View All</a>
                            </div>
                            
                            <div class="row">
                                <?php if (!empty($recentFeed)): 
                                    foreach ($recentFeed as $recs): 
                                        if (($recs['feed_type'] ?? '') === 'transfer'):
                                            $statusClass = ($recs['status'] == '1') ? 'success' : 'warning';
                                ?>
                                <div class="col-lg-6">
                                    <div class="trans-item-new" onclick="showReceipt('<?php echo htmlspecialchars($recs['receiver'], ENT_QUOTES); ?>', '<?php echo $recs['date']; ?>', '<?php echo number_format($recs['amount'],2); ?>', '<?php echo $recs['status']; ?>', '<?php echo htmlspecialchars($recs['bank'], ENT_QUOTES); ?>', '<?php echo $recs['id']; ?>', '<?php echo $cur; ?>')">
                                        <div class="avatar-sm me-3">
                                            <div class="avatar-title bg-<?php echo $statusClass; ?>-subtle text-<?php echo $statusClass; ?>">
                                                <i class="bx bx-transfer-alt fs-5"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-0 fw-bold"><?php echo $recs['bank']; ?></h6>
                                            <small class="text-muted"><?php echo date("M d, H:i", strtotime($recs['date'])); ?> · #TRX-<?php echo $recs['id']; ?></small>
                                        </div>
                                        <div class="text-end">
                                            <h5 class="mb-0 fw-bold text-danger" style="font-size:0.88rem;">-<?php echo $cur . number_format($recs['amount'], 2); ?></h5>
                                            <span class="text-<?php echo $statusClass; ?> small fw-bold" style="font-size:0.68rem;"><?php echo ($recs['status'] == '1') ? 'Completed' : 'Pending'; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <?php else:
                                    $tuStatus = strtolower((string) ($recs['status'] ?? ''));
                                    if ($tuStatus === 'approved') {
                                        $statusClass = 'success';
                                        $statusLabel = 'Approved';
                                        $amtClass = 'text-success';
                                        $amtPrefix = '+';
                                    } elseif ($tuStatus === 'rejected') {
                                        $statusClass = 'danger';
                                        $statusLabel = 'Rejected';
                                        $amtClass = 'text-muted';
                                        $amtPrefix = '';
                                    } else {
                                        $statusClass = 'warning';
                                        $statusLabel = 'Pending';
                                        $amtClass = 'text-primary';
                                        $amtPrefix = '';
                                    }
                                    $tuRef = htmlspecialchars((string) ($recs['reference'] ?? ''), ENT_QUOTES, 'UTF-8');
                                    $tuMethod = htmlspecialchars((string) ($recs['method_name'] ?? 'Top up'), ENT_QUOTES, 'UTF-8');
                                ?>
                                <div class="col-lg-6">
                                    <div class="trans-item-new" style="cursor:default;">
                                        <div class="avatar-sm me-3">
                                            <div class="avatar-title bg-<?php echo $statusClass; ?>-subtle text-<?php echo $statusClass; ?>">
                                                <i class="bx bx-wallet fs-5"></i>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="mb-0 fw-bold">Top up · <?php echo $tuMethod; ?></h6>
                                            <small class="text-muted"><?php echo date("M d, H:i", strtotime($recs['created_at'])); ?> · <?php echo $tuRef; ?></small>
                                        </div>
                                        <div class="text-end">
                                            <h5 class="mb-0 fw-bold <?php echo $amtClass; ?>" style="font-size:0.88rem;"><?php echo $amtPrefix . $cur . number_format((float) $recs['amount'], 2); ?></h5>
                                            <span class="text-<?php echo $statusClass; ?> small fw-bold" style="font-size:0.68rem;"><?php echo $statusLabel; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <?php
                                        endif;
                                    endforeach;
                                else:
                                ?>
                                    <div class="col-12 text-center p-4">
                                        <i class="bx bx-receipt text-muted" style="font-size: 2.5rem;"></i>
                                        <p class="text-muted mt-2 mb-0" style="font-size:0.82rem;">No transactions yet</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="receiptModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0" style="background:#fff; border-radius:20px; overflow:hidden;">
                <div class="modal-header border-0 pb-0" style="padding:1.1rem 1.1rem 0; background: #fff !important;">
                    <h6 class="modal-title fw-bold" style="font-size:0.9rem; color: #0f172a !important;">Transaction Receipt</h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="font-size:0.65rem;"></button>
                </div>
                <div class="modal-body text-center pt-3" style="background: #fff !important;">
                    <div id="r-status-icon-wrap" style="width:56px;height:56px;margin:0 auto 10px;display:flex;align-items:center;justify-content:center;border-radius:50%;background:#d4edda;">
                        <i class="bx bx-check text-success" style="font-size:1.8rem;" id="r-status-icon-el"></i>
                    </div>
                    <h3 class="fw-800 mb-1" id="r-amount-display" style="font-size:1.5rem; color: #0f172a !important;"></h3>
                    <p class="text-success fw-bold mb-0" id="r-status-text" style="font-size:0.78rem;">Transaction Successful</p>
                    
                    <hr class="my-3" style="border-style:dashed; opacity:0.3;">
                    
                    <div class="text-start px-1">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted" style="font-size:0.78rem; color: #64748b !important;">Recipient</span>
                            <span class="fw-bold" id="r-receiver" style="font-size:0.78rem; color: #0f172a !important;"></span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted" style="font-size:0.78rem; color: #64748b !important;">Bank</span>
                            <span class="fw-bold" id="r-bank" style="font-size:0.78rem; color: #0f172a !important;"></span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted" style="font-size:0.78rem; color: #64748b !important;">Reference</span>
                            <span class="fw-bold text-uppercase" id="r-id" style="font-size:0.78rem; color: #0f172a !important;"></span>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted" style="font-size:0.78rem; color: #64748b !important;">Date & Time</span>
                            <span class="fw-bold" id="r-date" style="font-size:0.78rem; color: #0f172a !important;"></span>
                        </div>
                        <div class="d-flex justify-content-between mb-0">
                            <span class="text-muted" style="font-size:0.78rem; color: #64748b !important;">Type</span>
                            <span class="fw-bold" style="font-size:0.78rem; color: #0f172a !important;">Debit Transfer</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0" style="padding:0.6rem 1.1rem 1.1rem; background: #fff !important;">
                    <button type="button" class="btn btn-light w-100 rounded-pill fw-bold py-2" onclick="window.print()" style="font-size:0.82rem;">
                        <i class="bx bx-printer me-1"></i> Print Receipt
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="transferChoiceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0" style="background: #fff !important;">
            <div class="modal-header border-0 pb-0" style="padding: 25px 25px 0; background: #fff !important;">
                <h5 class="fw-800 mb-0" style="color: #0f172a !important;">Select Transfer Type</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4" style="background: #fff !important;">
                <div class="row g-3">
                    <div class="col-6">
                        <a href="local_transfer.php" class="text-decoration-none">
                            <div class="p-4 rounded-4 border text-center h-100 transition-all choice-card">
                                <div class="mb-3 mx-auto d-flex align-items-center justify-content-center icon-box">
                                    <i class="bx bxs-bank fs-2"></i>
                                </div>
                                <h6 class="fw-bold mb-1 card-title" style="color: #0f172a !important;">Local</h6>
                                <p class="small mb-0 card-subtitle" style="color: #64748b !important;">Within same country</p>
                            </div>
                        </a>
                    </div>

                    <div class="col-6">
                        <a href="international.php" class="text-decoration-none">
                            <div class="p-4 rounded-4 border text-center h-100 transition-all choice-card">
                                <div class="mb-3 mx-auto d-flex align-items-center justify-content-center icon-box">
                                    <i class="bx bx-globe fs-2"></i>
                                </div>
                                <h6 class="fw-bold mb-1 card-title" style="color: #0f172a !important;">International</h6>
                                <p class="small mb-0 card-subtitle" style="color: #64748b !important;">Send across borders</p>
                            </div>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    #transferChoiceModal .choice-card {
        background: #f8fafc !important;
        border: 2px solid #edf2f7 !important;
    }

    #transferChoiceModal .icon-box {
        width: 60px; 
        height: 60px; 
        background: white !important; 
        border-radius: 16px; 
        color: #003399; 
        box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    }

    #transferChoiceModal .choice-card:hover {
        background: #ffffff !important;
        border-color: #003399 !important;
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 51, 153, 0.1);
    }

    #transferChoiceModal .btn-close {
        filter: none !important;
        opacity: 0.8;
    }

    .transition-all { transition: all 0.3s ease; }
</style>

    <?php include 'footer.php' ?>

    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>
    <script src="assets/libs/apexcharts/apexcharts.min.js"></script>
    <script src="assets/js/app.js"></script>

    <script>
        const balance = document.getElementById('balance');
        const toggle = document.getElementById('toggle-icon');
        const realVal = '<?php echo number_format($rowrec['accountbalance'], 2); ?>';
        let hidden = false;

        toggle.addEventListener('click', () => {
            hidden = !hidden;
            balance.innerText = hidden ? '******' : realVal;
            toggle.className = hidden ? 'bx bx-hide fs-4' : 'bx bx-show fs-4';
        });

        const card = document.querySelector('.floating-card');
        if(card && window.innerWidth > 768) {
            document.addEventListener('mousemove', (e) => {
                let x = (window.innerWidth / 2 - e.pageX) / 30;
                let y = (window.innerHeight / 2 - e.pageY) / 30;
                card.style.transform = `rotateY(${x}deg) rotateX(${y}deg)`;
            });
        }
        
        // Activity Chart (Desktop Only)
        if (window.innerWidth > 991) {
            var activityOptions = {
                chart: { 
                    height: 180, 
                    type: 'area', 
                    toolbar: { show: false },
                    sparkline: { enabled: false }
                },
                colors: ['#003399'],
                stroke: { curve: 'smooth', width: 3 },
                series: [{ 
                    name: 'Activity', 
                    data: [23, 45, 32, 67, 49, 72, 58] 
                }],
                xaxis: {
                    categories: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                    labels: { 
                        style: { 
                            colors: '#64748b',
                            fontSize: '11px',
                            fontWeight: 600
                        }
                    }
                },
                yaxis: {
                    show: true,
                    labels: {
                        style: {
                            colors: '#64748b',
                            fontSize: '11px',
                            fontWeight: 600
                        }
                    }
                },
                grid: {
                    borderColor: '#f1f5f9',
                    strokeDashArray: 3
                },
                fill: {
                    type: 'gradient',
                    gradient: {
                        shadeIntensity: 1,
                        opacityFrom: 0.4,
                        opacityTo: 0.1,
                        stops: [0, 90, 100]
                    }
                },
                dataLabels: { enabled: false },
                tooltip: { 
                    theme: 'light',
                    style: {
                        fontSize: '12px',
                        fontFamily: 'Plus Jakarta Sans'
                    }
                }
            };
            var activityChart = new ApexCharts(document.querySelector("#activityChart"), activityOptions);
            activityChart.render();
        }
        
        function showReceipt(receiver, date, amount, status, bank, id, currency) {
            document.getElementById('r-receiver').innerText = receiver;
            document.getElementById('r-bank').innerText = bank;
            document.getElementById('r-amount-display').innerText = '-' + currency + amount;
            document.getElementById('r-id').innerText = 'TRX-' + id;
            
            const d = new Date(date);
            document.getElementById('r-date').innerText = d.toLocaleDateString('en-GB', {
                day: 'numeric', month: 'short', year: 'numeric'
            }) + ', ' + d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });

            const statusText = document.getElementById('r-status-text');
            const iconWrap = document.getElementById('r-status-icon-wrap');
            const iconEl = document.getElementById('r-status-icon-el');
            
            if(status === '1') {
                statusText.innerText = 'Transaction Completed';
                statusText.className = 'text-success fw-bold mb-0';
                iconWrap.style.background = '#d4edda';
                iconEl.className = 'bx bx-check text-success';
                iconEl.style.fontSize = '1.8rem';
            } else {
                statusText.innerText = 'Transaction Pending';
                statusText.className = 'text-warning fw-bold mb-0';
                iconWrap.style.background = '#fff3cd';
                iconEl.className = 'bx bx-time text-warning';
                iconEl.style.fontSize = '1.8rem';
            }

            var myModal = new bootstrap.Modal(document.getElementById('receiptModal'));
            myModal.show();
        }
    </script>
</body>
</html>