<?php
require_once 'functions.php';
requireAuth();

$user = getCurrentUser();
if (!$user) {
    header('Location: logout.php');
    exit();
}

// Check for admin popup
if ($user['show_popup'] && $user['popup_message']) {
    $showPopup = true;
    $popupMessage = $user['popup_message'];
}

$db = getDB();

// Get recent transactions
$stmt = $db->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 8");
$stmt->bind_param('i', $user['id']);
$stmt->execute();
$recentTransactions = $stmt->get_result();

// Get user's cards
$cards = getUserCards($user['id']);

// Get unread notifications
$notifications = getUnreadNotifications($user['id']);
$notifCount = getNotificationCount($user['id']);

// Get transaction stats
// Replace the "echo" line with this:
$stats = getTransactionStats($user['id']); 

// Debugging: Uncomment the line below to see what the function actually returns
// echo '<pre>'; print_r($stats); echo '</pre>'; die();
$flash = getFlash()

// Dynamic pulls from SQL table


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        /* Base / Desktop Layout Setup */
        .dashboard-grid-top {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
            margin-bottom: 28px;
        }
        .stats-subgrid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }
        .quick-actions-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 16px;
            margin-bottom: 28px;
        }
        .cards-flex-container {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        /* Card Object Rules */
        .card-display {
            width: 100%;
            max-width: 340px;
            height: 200px;
            border-radius: var(--border-radius-lg);
            padding: 24px;
            color: var(--white);
            position: relative;
            overflow: hidden;
            margin-bottom: 16px;
            flex-shrink: 0;
        }
        .card-display.visa {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
        }
        .card-display.mastercard {
            background: linear-gradient(135deg, #f7931a 0%, #c0392b 100%);
        }
        .card-display::before {
            content: '';
            position: absolute;
            top: -30%;
            right: -20%;
            width: 160px;
            height: 160px;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            border-radius: 50%;
        }
        .card-chip {
            width: 40px;
            height: 30px;
            background: linear-gradient(135deg, #d4af37, #f4d03f);
            border-radius: 6px;
            margin-bottom: 24px;
        }
        .card-number-display {
            font-family: 'Courier New', monospace;
            font-size: 18px;
            letter-spacing: 2px;
            margin-bottom: 20px;
        }
        .card-meta {
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            text-transform: uppercase;
        }
        
        /* Quick Action Designs */
        .quick-action {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
            padding: 20px;
            background: var(--white);
            border: 1px solid var(--gray-200);
            border-radius: var(--border-radius);
            transition: var(--transition);
            cursor: pointer;
            text-decoration: none;
        }
        .quick-action:hover {
            border-color: var(--primary);
            box-shadow: var(--shadow-md);
            transform: translateY(-2px);
        }
        .quick-action-icon {
            width: 48px;
            height: 48px;
            border-radius: var(--border-radius);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }
        .quick-action-label {
            font-size: 12px;
            font-weight: 600;
            color: var(--secondary);
        }
        
        /* Table Box Overflow Shield */
        .responsive-table-wrapper {
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .responsive-table-wrapper table {
            min-width: 600px;
            width: 100%;
        }

        /* Responsive Media Adjustments */
        @media (max-width: 991px) {
            .dashboard-grid-top {
                grid-template-columns: 1fr;
            }
        }
        @media (max-width: 767px) {
            .quick-actions-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            .cards-flex-container {
                justify-content: center;
            }
            .card-display {
                max-width: 100%;
            }
        }
        @media (max-width: 480px) {
            .stats-subgrid {
                grid-template-columns: 1fr;
            }
            .quick-actions-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/client-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/client-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <div class="dashboard-grid-top">
                <div class="balance-card">
                    <div class="balance-card-label">Available Balance</div>
                    <div class="balance-card-value"><?php echo formatCurrency($user['available_balance'] ?? 0); ?></div>
                    <div class="balance-card-meta">
                        <div class="balance-card-meta-item">
                            <span class="balance-card-meta-label">Account Number</span>
                            <span class="balance-card-meta-value"><?php echo e($user['account_number']); ?></span>
                        </div>
                        <div class="balance-card-meta-item">
                            <span class="balance-card-meta-label">Account Type</span>
                            <span class="balance-card-meta-value"><?php echo ucfirst(e($user['account_type'])); ?></span>
                        </div>
                        <div class="balance-card-meta-item">
                            <span class="balance-card-meta-label">Status</span>
                            <span class="balance-card-meta-value" style="color: #10B981;">● Active</span>
                        </div>
                    </div>
                </div>
                
                <div class="stats-subgrid">
        
                    <div class="stat-card" style="margin-bottom: 0;">
                        <div class="stat-card-header">
                            <span class="stat-card-title">Total Credits</span>
                            <div class="stat-card-icon primary" style="width: 36px; height: 36px;">
                                <span style="font-size: 16px;">📈</span>
                            </div>
                        </div>
                        <div class="stat-card-value" style="font-size: 22px;"><?php echo formatCurrency($stats['total_credits'] ?? 0); ?></div>
                    </div>
                    <div class="stat-card" style="margin-bottom: 0;">
                        <div class="stat-card-header">
                            <span class="stat-card-title">Total Debits</span>
                            <div class="stat-card-icon warning" style="width: 36px; height: 36px;">
                                <span style="font-size: 16px;">📉</span>
                            </div>
                        </div>
                        <div class="stat-card-value" style="font-size: 22px;"><?php echo formatCurrency($stats['total_debits'] ?? 0); ?></div>
                    </div>
                    <div class="stat-card" style="margin-bottom: 0;">
                        <div class="stat-card-header">
                            <span class="stat-card-title">Pending</span>
                            <div class="stat-card-icon info" style="width: 36px; height: 36px;">
                                <span style="font-size: 16px;">⏳</span>
                            </div>
                        </div>
                        <div class="stat-card-value" style="font-size: 22px;"><?php echo e($stats['pending_count'] ?? 0); ?></div>
                    </div>
                </div>
            </div>
            
            <h3 style="font-size: 16px; font-weight: 700; margin-bottom: 16px;">Quick Actions</h3>
            <div class="quick-actions-grid">
                <a href="transfer.php" class="quick-action">
                    <div class="quick-action-icon" style="background: var(--primary-light); color: var(--primary);">💸</div>
                    <span class="quick-action-label">Transfer</span>
                </a>
                <a href="crypto-deposit.php" class="quick-action">
                    <div class="quick-action-icon" style="background: var(--info-light); color: var(--info);">₿</div>
                    <span class="quick-action-label">Crypto Deposit</span>
                </a>
                <a href="cards.php" class="quick-action">
                    <div class="quick-action-icon" style="background: var(--success-light); color: var(--success);">💳</div>
                    <span class="quick-action-label">My Cards</span>
                </a>
                <a href="support.php" class="quick-action">
                    <div class="quick-action-icon" style="background: var(--warning-light); color: var(--warning);">🎫</div>
                    <span class="quick-action-label">Support</span>
                </a>
            </div>
            
            <?php if ($cards): ?>
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-header">
                    <span class="card-title">My Cards</span>
                    <a href="cards.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body cards-flex-container">
                    <?php foreach ($cards as $card): ?>
                        <div class="card-display <?php echo e($card['card_type']); ?>">
                            <div style="display: flex; justify-content: space-between; align-items: start;">
                                <div class="card-chip"></div>
                                <span style="font-size: 14px; font-weight: 700; text-transform: uppercase;"><?php echo e($card['card_type']); ?></span>
                            </div>
                            <div class="card-number-display"><?php echo maskCard(e($card['card_number'])); ?></div>
                            <div class="card-meta">
                                <div>
                                    <div style="opacity: 0.7;">Card Holder</div>
                                    <div style="font-weight: 600;"><?php echo e($card['card_holder']); ?></div>
                                </div>
                                <div>
                                    <div style="opacity: 0.7;">Expires</div>
                                    <div style="font-weight: 600;"><?php echo e($card['expiry_month']); ?>/<?php echo e($card['expiry_year']); ?></div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            <style>
             /* Professional Transaction Status Badges */
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 50px; /* Fully rounded 'pill' shape */
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* Status: Completed (Success) */
.status-badge.completed {
    background-color: #dcfce7; 
    color: #166534;
    border: 1px solid #bbf7d0;
}

/* Status: Pending (Warning/Neutral) */
.status-badge.pending {
    background-color: #fef3c7; 
    color: #92400e;
    border: 1px solid #fde68a;
}

/* Status: Failed/Cancelled (Danger) */
.status-badge.failed, 
.status-badge.cancelled {
    background-color: #fee2e2; 
    color: #991b1b;
    border: 1px solid #fecaca;
}

/* Status: On Hold (Info/Secondary) */
.status-badge.on_hold {
    background-color: #e0f2fe; 
    color: #075985;
    border: 1px solid #bae6fd;
}
            </style>
            <div class="card">
                <div class="card-header">
                    <span class="card-title">Recent Transactions</span>
                    <a href="transactions.php" class="btn btn-sm btn-outline-primary">View All</a>
                </div>
                <div class="card-body" style="padding: 0;">
                    <?php if ($recentTransactions->num_rows > 0): ?>
                        <div class="table-container responsive-table-wrapper">
                            <table class="data-table" style="border: none;">
                                <thead>
                                    <tr>
                                        <th>Reference</th>
                                        <th>Type</th>
                                        <th>Description</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($tx = $recentTransactions->fetch_assoc()): ?>
                                        <tr>
                                            <td><code style="font-size: 12px;"><?php echo e($tx['reference_number']); ?></code></td>
                                            <td>
                                                <span class="status-badge <?php 
                                                    echo $tx['transaction_type'] === 'credit' ? 'success' : 
                                                        ($tx['transaction_type'] === 'debit' ? 'danger' : 'info'); 
                                                 ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($tx['transaction_type'])); ?>
                                                </span>
                                            </td>
                                            <td><?php echo e($tx['description'] ?? '-'); ?></td>
                                            <td style="font-weight: 700; <?php echo $tx['transaction_type'] === 'credit' ? 'color: var(--success);' : 'color: var(--danger);'; ?>">
                                                <?php echo $tx['transaction_type'] === 'credit' ? '+' : '-'; ?><?php echo formatCurrency($tx['amount'] ?? 0); ?>
                                            </td>
                                            <td>
    <span class="status-badge <?php echo strtolower(e($tx['status'])); ?>">
        <?php echo ucfirst(e($tx['status'])); ?>
    </span>
</td>
                                            <td style="font-size: 12px;"><?php echo formatDateShort($tx['created_at']); ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="empty-state" style="padding: 40px;">
                            <div class="empty-state-icon">📋</div>
                            <h3>No Transactions Yet</h3>
                            <p>Your transaction history will appear here once you start making transactions.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <?php if (!empty($showPopup)): ?>
    <div class="popup-overlay" id="adminPopup">
        <div class="popup-box">
            <div class="popup-icon">⚠️</div>
            <h3 class="popup-title">Important Notice</h3>
            <p class="popup-message"><?php echo nl2br(e($popupMessage)); ?></p>
            <button onclick="document.getElementById('adminPopup').style.display='none'" class="btn btn-primary">
                I Understand
            </button>
        </div>
    </div>
    <?php endif; ?>
    
    <script src="assets/js/main.js"></script>
    
    <?php if (!empty($tawkScript)): ?>
        <?php echo $tawkScript; ?>
    <?php else: ?>
        <script type="text/javascript">
        var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
        (function(){
            var s1 = document.createElement("script"), s0 = document.getElementsByTagName("script")[0];
            s1.async = true;
            s1.src = 'https://embed.tawk.to/66f75c544cbc4814f7e034cf/1i8r41aru';
            s1.charset = 'UTF-8';
            s1.setAttribute('crossorigin', '*');
            s0.parentNode.insertBefore(s1, s0);
        })();
        </script>
    <?php endif; ?>

    
</body>
</html>