<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'dashboard';
$database = new Database();
$db = $database->getConnection();

// Debug user ID
error_log("Dashboard loaded for user ID: " . $_SESSION['user_id']);

// Include notification functions
require_once 'includes/notification_functions.php';

// Get notifications directly from database
try {
    $unread_stmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
    $unread_stmt->execute([$_SESSION['user_id']]);
    $unread_count = $unread_stmt->fetchColumn();
    
    $notifications_stmt = $db->prepare("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 3");
    $notifications_stmt->execute([$_SESSION['user_id']]);
    $recent_notifications = $notifications_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $unread_count = 0;
    $recent_notifications = [];
    error_log("Error loading notifications: " . $e->getMessage());
}

// Get recent transactions - FIXED: Don't filter out any transactions
try {
    $stmt = $db->prepare("
        SELECT reference, user_id, type, amount, currency, description, status, transaction_type, created_at 
        FROM transactions 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT 5
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $recentTransactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Log the count for debugging
    error_log("Found " . count($recentTransactions) . " transactions for user " . $_SESSION['user_id']);
} catch (PDOException $e) {
    error_log("Error fetching transactions: " . $e->getMessage());
    $recentTransactions = [];
}

// Get monthly summary
$currentMonth = date('Y-m-01');
$stmt = $db->prepare("SELECT SUM(CASE WHEN type = 'credit' THEN amount ELSE 0 END) as total_credits, SUM(CASE WHEN type = 'debit' THEN amount ELSE 0 END) as total_debits FROM transactions WHERE user_id = ? AND created_at >= ? AND status = 'completed'");
$stmt->execute([$_SESSION['user_id'], $currentMonth]);
$monthlySummary = $stmt->fetch(PDO::FETCH_ASSOC);

// Get spending categories for chart
try {
    $stmt = $db->prepare("
        SELECT 
            COALESCE(category, 'Other') as category, 
            SUM(amount) as total_amount 
        FROM transactions 
        WHERE 
            user_id = ? AND 
            type = 'debit' AND 
            created_at >= ? AND 
            status = 'completed' 
        GROUP BY category 
        ORDER BY total_amount DESC 
        LIMIT 5
    ");
    $stmt->execute([$_SESSION['user_id'], date('Y-m-d', strtotime('-30 days'))]);
    $spendingCategories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $spendingCategories = [];
}

// Get transaction history for chart (last 7 days)
try {
    $stmt = $db->prepare("
        SELECT 
            DATE(created_at) as date,
            SUM(CASE WHEN type = 'credit' THEN amount ELSE 0 END) as income,
            SUM(CASE WHEN type = 'debit' THEN amount ELSE 0 END) as expense
        FROM transactions 
        WHERE 
            user_id = ? AND 
            created_at >= ? AND 
            status = 'completed' 
        GROUP BY DATE(created_at)
        ORDER BY date ASC
    ");
    $stmt->execute([$_SESSION['user_id'], date('Y-m-d', strtotime('-7 days'))]);
    $transactionHistory = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $transactionHistory = [];
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* Base Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --primary-dark: #4338ca;
    --success-color: #10b981;
    --success-light: #ecfdf5;
    --danger-color: #ef4444;
    --danger-light: #fef2f2;
    --warning-color: #f59e0b;
    --warning-light: #fffbeb;
    --info-color: #0ea5e9;
    --info-light: #e0f9ff;
    --dark-color: #1e293b;
    --light-color: #f8fafc;
    --gray-color: #64748b;
    --border-color: #e5e7eb;
    --animation-speed: 0.5s;
}

/* Animation Keyframes */
@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes slideInRight {
    from {
        opacity: 0;
        transform: translateX(20px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

@keyframes shimmer {
    0% { background-position: -1000px 0; }
    100% { background-position: 1000px 0; }
}

/* Animated Elements */
.fade-in {
    animation: fadeIn var(--animation-speed) ease forwards;
}

.slide-up {
    animation: slideInUp var(--animation-speed) ease forwards;
}

.slide-right {
    animation: slideInRight var(--animation-speed) ease forwards;
}

.staggered-item {
    opacity: 0;
}

/* Card Styles with Animation */
.dashboard-card {
    background: white;
    border-radius: 15px;
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    margin-bottom: 1.5rem;
    transition: all 0.3s ease;
    overflow: hidden;
    position: relative;
}

.dashboard-card:hover {
    box-shadow: 0 15px 30px -10px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1);
    transform: translateY(-5px);
}

.card-fixed-height {
    height: 400px;
}

.card-header {
    background: none;
    padding: 1.25rem;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    z-index: 2;
}

.card-header::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 0;
    height: 2px;
    background: var(--primary-color);
    transition: width 0.3s ease;
    z-index: 3;
}

.dashboard-card:hover .card-header::after {
    width: 100%;
}

.card-title {
    margin-bottom: 0;
    font-size: 1.1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
}

.card-title i {
    margin-right: 0.5rem;
    font-size: 1.25rem;
    color: var(--primary-color);
}

.card-body {
    padding: 1.5rem;
    position: relative;
    z-index: 1;
}

/* Balance Card with Animation */
.balance-card {
    background: linear-gradient(135deg, #4338ca, #6366F1);
    color: white;
    position: relative;
    overflow: hidden;
}

.balance-card::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
    transform: rotate(30deg);
    z-index: 1;
    animation: shimmer 8s infinite linear;
}

.balance-value {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
    position: relative;
    z-index: 2;
}

.account-number {
    background-color: rgba(255,255,255,0.2);
    padding: 0.5rem 1rem;
    border-radius: 999px;
    font-family: monospace;
    display: inline-block;
    position: relative;
    z-index: 2;
    transition: all 0.3s ease;
}

.account-number:hover {
    background-color: rgba(255,255,255,0.3);
    transform: translateY(-2px);
}

/* Profile Picture Animation */
.dash-profile-pic {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;
    border: 4px solid rgba(255,255,255,0.5);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    flex-shrink: 0;
    margin-left: auto;
    transition: all 0.3s ease;
    position: relative;
    z-index: 2;
}

.dash-profile-pic:hover {
    transform: scale(1.05);
    border-color: rgba(255,255,255,0.8);
    box-shadow: 0 8px 20px rgba(0,0,0,0.2);
}

.dash-profile-pic img, .dash-profile-initial {
    width: 100%;
    height: 100%;
    object-fit: cover;
    background: linear-gradient(135deg, #4f46e5, #818cf8);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    color: white;
    font-weight: 600;
}

/* Quick Actions with Animation */
.quick-actions {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 1rem;
}

.quick-action {
    text-align: center;
    padding: 1.25rem 1rem;
    border-radius: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    background-color: var(--light-color);
    text-decoration: none;
    color: var(--dark-color);
    position: relative;
    overflow: hidden;
}

.quick-action::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: radial-gradient(circle, rgba(79, 70, 229, 0.2) 0%, rgba(79, 70, 229, 0) 70%);
    opacity: 0;
    transition: opacity 0.3s ease;
}

.quick-action:hover {
    background-color: var(--primary-light);
    transform: translateY(-5px);
}

.quick-action:hover::after {
    opacity: 1;
}

.quick-action-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 1rem;
    font-size: 1.5rem;
    background-color: white;
    color: var(--primary-color);
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}

.quick-action:hover .quick-action-icon {
    transform: scale(1.1);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.quick-action-title {
    font-weight: 600;
    font-size: 0.9rem;
    transition: all 0.3s ease;
}

.quick-action:hover .quick-action-title {
    color: var(--primary-color);
}

/* Scrollable Content */
.overflow-auto {
    overflow: auto !important;
    scrollbar-width: thin;
}

.overflow-auto::-webkit-scrollbar {
    width: 4px;
}

.overflow-auto::-webkit-scrollbar-track {
    background: #f1f1f1;
}

.overflow-auto::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 10px;
}

/* Tip Items with Animation */
.tip-item {
    margin-bottom: 1.5rem;
    padding: 1rem;
    border-radius: 0.5rem;
    transition: all 0.3s ease;
    border: 1px solid transparent;
}

.tip-item:hover {
    background-color: var(--light-color);
    border-color: var(--border-color);
    transform: translateX(5px);
}

.tip-icon {
    width: 28px;
    height: 28px;
    font-size: 1rem;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.tip-item:hover .tip-icon {
    transform: scale(1.2);
}

/* Transaction Items with Animation */
.transaction-item {
    padding: 1rem;
    border-bottom: 1px solid var(--border-color);
    transition: all 0.3s ease;
}

.transaction-item:hover {
    background-color: var(--light-color);
    transform: translateX(5px);
}

.transaction-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    transition: all 0.3s ease;
}

.transaction-item:hover .transaction-icon {
    transform: scale(1.1);
}

/* Notification Items with Animation */
.notification-item {
    padding: 1rem;
    border-bottom: 1px solid var(--border-color);
    transition: all 0.3s ease;
    display: flex;
    align-items: flex-start;
    text-decoration: none;
    color: inherit;
}

.notification-item:hover {
    background-color: var(--primary-light);
    transform: translateX(5px);
}

.notification-item.unread {
    background-color: rgba(79, 70, 229, 0.05);
}

.notification-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 1rem;
    flex-shrink: 0;
    font-size: 1.25rem;
    transition: all 0.3s ease;
}

.notification-item:hover .notification-icon {
    transform: scale(1.1);
}

.notification-content {
    flex: 1;
}

.notification-title {
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.notification-text {
    color: var(--gray-color);
    font-size: 0.875rem;
    margin-bottom: 0.25rem;
}

.notification-time {
    color: var(--gray-color);
    font-size: 0.75rem;
}

/* Empty States with Animation */
.empty-state {
    text-align: center;
    padding: 2rem 1rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.empty-state-icon {
    font-size: 2.5rem;
    color: #d1d5db;
    margin-bottom: 0.5rem;
    transition: all 0.3s ease;
}

.empty-state:hover .empty-state-icon {
    transform: scale(1.1);
    color: var(--primary-color);
}

.empty-state-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.empty-state-text {
    color: var(--gray-color);
    margin-bottom: 1rem;
    font-size: 0.875rem;
}

/* Chart Container */
.chart-container {
    position: relative;
    height: 250px;
    width: 100%;
}

/* Progress Bar Animation */
.progress {
    height: 8px;
    background-color: var(--light-color);
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 0.5rem;
}

.progress-bar {
    height: 100%;
    border-radius: 4px;
    background-color: var(--primary-color);
    width: 0;
    transition: width 1s ease;
}

/* Background Colors */
.bg-primary-light { background-color: rgba(79, 70, 229, 0.1); }
.bg-success-light { background-color: rgba(16, 185, 129, 0.1); }
.bg-warning-light { background-color: rgba(245, 158, 11, 0.1); }
.bg-danger-light { background-color: rgba(239, 68, 68, 0.1); }
.bg-info-light { background-color: rgba(14, 165, 233, 0.1); }

/* Text Colors */
.text-primary { color: var(--primary-color) !important; }
.text-success { color: var(--success-color) !important; }
.text-warning { color: var(--warning-color) !important; }
.text-danger { color: var(--danger-color) !important; }
.text-info { color: var(--info-color) !important; }

/* Button Animations */
.btn {
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.btn::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 5px;
    height: 5px;
    background: rgba(255, 255, 255, 0.5);
    opacity: 0;
    border-radius: 100%;
    transform: scale(1, 1) translate(-50%);
    transform-origin: 50% 50%;
}

.btn:hover::after {
    animation: ripple 1s ease-out;
}

@keyframes ripple {
    0% {
        transform: scale(0, 0);
        opacity: 0.5;
    }
    100% {
        transform: scale(20, 20);
        opacity: 0;
    }
}

/* Interactive Badges */
.badge {
    transition: all 0.3s ease;
}

.badge:hover {
    transform: scale(1.1);
}

/* Tooltip Animation */
.tooltip {
    opacity: 0;
    transition: opacity 0.3s ease;
}

.tooltip.show {
    opacity: 1;
}

/* Pulse Animation for Notifications */
@keyframes pulse-dot {
    0% {
        transform: scale(0.8);
    }
    50% {
        transform: scale(1.2);
    }
    100% {
        transform: scale(0.8);
    }
}

.notification-pulse {
    position: relative;
}

.notification-pulse::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: var(--danger-color);
    animation: pulse-dot 1.5s cubic-bezier(0.455, 0.03, 0.515, 0.955) infinite;
}

/* Shimmer Loading Effect */
.shimmer {
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: shimmer 1.5s infinite;
}

/* Spending Category Styles */
.spending-category {
    margin-bottom: 1rem;
    padding: 0.75rem;
    border-radius: 0.5rem;
    transition: all 0.3s ease;
}

.spending-category:hover {
    background-color: var(--light-color);
    transform: translateX(5px);
}

.category-name {
    font-weight: 500;
    display: flex;
    align-items: center;
}

.category-icon {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 0.5rem;
    font-size: 0.875rem;
}

.category-amount {
    font-weight: 600;
}

.category-bar {
    height: 6px;
    background-color: var(--light-color);
    border-radius: 3px;
    overflow: hidden;
    margin-top: 0.5rem;
}

.category-bar-fill {
    height: 100%;
    border-radius: 3px;
    width: 0;
    transition: width 1s ease;
}


/* Add this to your CSS styles section */
.position-absolute {
    position: absolute !important;
}

.top-0 {
    top: 0 !important;
}

.start-100 {
    left: 100% !important;
}

.translate-middle {
    transform: translate(-50%, -50%) !important;
}

.badge.bg-danger {
    background-color: #ef4444 !important;
    color: white;
    font-size: 0.75rem;
    padding: 0.25rem 0.5rem;
    border-radius: 9999px;
}


.balance-selector {
    background-color: rgba(255,255,255,0.2);
    border: 1px solid rgba(255,255,255,0.3);
    color: white;
    border-radius: 0.375rem;
    padding: 0.25rem 0.5rem;
    font-size: 1rem;
    font-weight: 500;
}
.balance-selector:focus {
    outline: none;
    box-shadow: 0 0 0 2px rgba(255,255,255,0.5);
}
.balance-selector option {
    background-color: #4338ca;
    color: white;
}

/* Enhanced Balance Display */
.balance-value {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
    position: relative;
    z-index: 2;
    text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    transition: all 0.3s ease;
}

.balance-updated {
    animation: balancePulse 1s ease-in-out;
}

@keyframes balancePulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); color: #ffffff; }
    100% { transform: scale(1); }
}

.balance-selector {
    background-color: rgba(255,255,255,0.2);
    border: 1px solid rgba(255,255,255,0.3);
    color: white;
    border-radius: 0.375rem;
    padding: 0.25rem 0.5rem;
    font-size: 1rem;
    font-weight: 500;
    transition: all 0.3s ease;
}

.balance-selector:hover {
    background-color: rgba(255,255,255,0.25);
    border-color: rgba(255,255,255,0.4);
}

.balance-selector:focus {
    outline: none;
    box-shadow: 0 0 0 2px rgba(255,255,255,0.5);
    background-color: rgba(255,255,255,0.3);
}

.balance-selector option {
    background-color: #4338ca;
    color: white;
    padding: 8px;
}

.balance-updated-time {
    opacity: 0.7;
    font-size: 0.8rem;
    transition: opacity 0.3s ease;
}

.balance-card:hover .balance-updated-time {
    opacity: 1;
}

/* Transaction description styles - NEW */
.transaction-description {
    font-weight: 500;
    color: #1e293b;
    max-width: 250px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    transition: all 0.3s ease;
}

.transaction-item:hover .transaction-description {
    white-space: normal;
    max-height: 60px;
    overflow: auto;
}

</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex justify-content-between align-items-center mb-4 fade-in">
            <div>
                <h1 class="h3 mb-1">Welcome back, <?php echo htmlspecialchars($user['first_name']); ?>!</h1>
                <p class="text-muted mb-0">Here's your financial overview.</p>
            </div>
            
            <!-- Notification bell -->
            <?php if ($unread_count > 0): ?>
            <div>
                <!-- Notification bell -->
                <div>
                    <a href="notifications.php" class="btn btn-light position-relative">
                        <i class='bx bx-bell'></i> Notifications
                        <?php if ($unread_count > 0): ?>
                            <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                                <?php echo $unread_count; ?>
                            </span>
                        <?php endif; ?>
                    </a>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Balance Card -->
        <div class="dashboard-card balance-card mb-4 slide-up" style="animation-delay: 0.1s;">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="text-white-50 mb-2">Available Balance</div>
                        <div class="d-flex align-items-center">
                            <div class="balance-value" id="balanceDisplay">Loading...</div>
                            <select id="currencySelector" class="balance-selector ms-3">
                                <?php
                                // Get account balances from the account_balances table
                                try {
                                    $balances_stmt = $db->prepare("SELECT currency, balance FROM account_balances WHERE user_id = ? ORDER BY currency ASC");
                                    $balances_stmt->execute([$_SESSION['user_id']]);
                                    $balances = $balances_stmt->fetchAll(PDO::FETCH_ASSOC);
                                    
                                    if (empty($balances)): ?>
                                        <option value="<?php echo htmlspecialchars($user['currency']); ?>" data-balance="0.00"><?php echo htmlspecialchars($user['currency']); ?></option>
                                    <?php else: 
                                        foreach ($balances as $account): ?>
                                            <option value="<?php echo htmlspecialchars($account['currency']); ?>" data-balance="<?php echo htmlspecialchars($account['balance']); ?>">
                                                <?php echo htmlspecialchars($account['currency']); ?>
                                            </option>
                                        <?php endforeach;
                                    endif;
                                } catch (Exception $e) {
                                    // If there's an error, show the default balance
                                    echo '<option value="' . htmlspecialchars($user['currency']) . '" data-balance="0.00">' . htmlspecialchars($user['currency']) . '</option>';
                                    error_log("Error fetching account balances: " . $e->getMessage());
                                }
                                ?>
                            </select>
                        </div>

                        <div class="account-number">
                            <span class="account-number-text"><?php echo htmlspecialchars($user['account_number']); ?></span>
                            <button class="btn btn-sm btn-link p-0 ms-2 text-white" onclick="copyAccountNumber()" data-bs-toggle="tooltip" title="Copy Account Number">
                                <i class='bx bx-copy'></i>
                            </button>
                        </div>
                    </div>
                    <div class="text-end">
                        <div class="dash-profile-pic mb-3">
                            <?php if (!empty($user['profile_picture'])): ?>
                                <img src="<?php echo BASE_URL . 'uploads/profiles/' . htmlspecialchars($user['profile_picture']); ?>" alt="Profile" onerror="this.onerror=null; this.src='<?php echo BASE_URL; ?>assets/images/default-avatar.png';">
                            <?php else: ?>
                                <div class="dash-profile-initial">
                                    <?php echo strtoupper(substr($user['first_name'] ?? 'U', 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <a href="transfer.php" class="btn btn-light"><i class='bx bx-send me-1'></i>Send Money</a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="dashboard-card mb-4 slide-up" style="animation-delay: 0.2s;">
            <div class="card-header">
                <h5 class="card-title"><i class='bx bx-joystick'></i> Quick Actions</h5>
            </div>

            <div class="card-body">
                <div class="quick-actions">
                                        <a href="transfer.php" class="quick-action">
                        <div class="quick-action-icon"><i class='bx bx-transfer'></i></div>
                        <div class="quick-action-title">Transfer</div>
                    </a>
                    <a href="international-transfer.php" class="quick-action">
                        <div class="quick-action-icon"><i class='bx bx-globe'></i></div>
                        <div class="quick-action-title">Wire Transfer</div>
                    </a>
                    <a href="cards.php" class="quick-action">
                        <div class="quick-action-icon"><i class='bx bx-credit-card'></i></div>
                        <div class="quick-action-title">Cards</div>
                    </a>
                    <a href="loans.php" class="quick-action">
                        <div class="quick-action-icon"><i class='bx bx-dollar-circle'></i></div>
                        <div class="quick-action-title">Loans</div>
                    </a>
                    <a href="tickets.php" class="quick-action">
                        <div class="quick-action-icon"><i class='bx bx-support'></i></div>
                        <div class="quick-action-title">Support</div>
                    </a>
                    <a href="profile.php" class="quick-action">
                        <div class="quick-action-icon"><i class='bx bx-user'></i></div>
                        <div class="quick-action-title">Profile</div>
                    </a>
                </div>
            </div>
        </div>

        <!-- Three Column Cards with Equal Height -->
        <div class="row">
            <!-- Recent Transactions Card - MODIFIED to show full descriptions -->
            <div class="col-lg-12 mb-12">
                <div class="dashboard-card d-flex flex-column card-fixed-height slide-up" style="animation-delay: 0.3s;">
                    <div class="card-header">
                        <h5 class="card-title"><i class='bx bx-history'></i> Recent Transactions</h5>
                        <a href="transactions.php" class="btn btn-sm btn-outline-primary">View All</a>
                    </div>
                    <div class="card-body p-0 flex-grow-1 overflow-auto">
    <?php if (empty($recentTransactions)): ?>
        <div class="empty-state">
            <i class='bx bx-receipt empty-state-icon'></i>
            <h5 class="empty-state-title">No Recent Transactions</h5>
            <p class="empty-state-text">Your recent transactions will appear here.</p>
        </div>
    <?php else: ?>
        <div class="list-group list-group-flush">
            <?php foreach ($recentTransactions as $index => $transaction): ?>
                <?php
                $iconClass = 'bx-transfer'; $bgColorClass = 'primary';
                if ($transaction['type'] == 'credit') { $iconClass = 'bx-log-in-circle'; $bgColorClass = 'success'; } 
                elseif ($transaction['type'] == 'debit') { $iconClass = 'bx-log-out-circle'; $bgColorClass = 'danger'; }
                if (!empty($transaction['transaction_type'])) {
                    switch ($transaction['transaction_type']) {
                        case 'wire_transfer': $iconClass = 'bx-globe'; break;
                        case 'refund': $iconClass = 'bx-revision'; $bgColorClass = 'info'; break;
                        case 'adjustment': $iconClass = 'bx-slider'; $bgColorClass = 'info'; break;
                    }
                }
                ?>
                <div class="transaction-item staggered-transaction" data-index="<?php echo $index; ?>">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="d-flex align-items-start">
                            <div class="transaction-icon bg-<?php echo $bgColorClass; ?>-light text-<?php echo $bgColorClass; ?> me-3">
                                <i class='bx <?php echo $iconClass; ?>'></i>
                            </div>
                            <div>
                                <!-- FIXED: Clean up admin-related descriptions for customer view -->
                                <div class="transaction-description">
                                    <?php 
                                    $displayDescription = $transaction['description'];
                                    
                                    // Clean up various admin-related prefixes
                                    $adminPrefixes = [
                                        'Admin Action: ',
                                        'Balance adjustment: ',
                                        'Admin adjustment: ',
                                        'Manual adjustment: ',
                                        'Account adjustment: '
                                    ];
                                    
                                    foreach ($adminPrefixes as $prefix) {
                                        if (stripos($displayDescription, $prefix) === 0) {
                                            $displayDescription = substr($displayDescription, strlen($prefix));
                                            break;
                                        }
                                    }
                                    
                                    echo htmlspecialchars($displayDescription); 
                                    ?>
                                </div>
                                <div class="text-muted small"><?php echo date('M j, Y', strtotime($transaction['created_at'])); ?></div>
                            </div>
                        </div>
                        <div class="text-end">
                            <div class="fw-bold text-<?php echo $transaction['type'] == 'credit' ? 'success' : 'danger'; ?>">
                                <?php
                                    // Dynamic decimal places for amount
                                    $decimal_places = (strtoupper($transaction['currency']) === 'BTC') ? 8 : 2;
                                    $formatted_amount = number_format($transaction['amount'], $decimal_places);
                                ?>
                                <?php echo $transaction['type'] == 'credit' ? '+' : '-'; ?><?php echo htmlspecialchars($transaction['currency']); ?> <?php echo $formatted_amount; ?>
                            </div>
                            <span class="badge bg-<?php echo $transaction['status'] == 'completed' ? 'success' : 'warning'; ?>-light text-<?php echo $transaction['status'] == 'completed' ? 'success' : 'warning'; ?> mt-1">
                                <?php echo ucfirst($transaction['status']); ?>
                            </span>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>
                </div>
            </div>
            
            <!-- Support Tickets Card -->
            <div class="col-lg-6 mb-6">
                <div class="dashboard-card d-flex flex-column card-fixed-height slide-up" style="animation-delay: 0.4s;">
                    <div class="card-header">
                        <h5 class="card-title"><i class='bx bx-support'></i> Support Tickets</h5>
                        <a href="tickets.php" class="btn btn-sm btn-outline-primary">View All</a>
                    </div>
                    <div class="card-body p-0 flex-grow-1 overflow-auto">
                        <?php
                        // Get recent tickets
                        try {
                            $tickets_stmt = $db->prepare("
                                SELECT t.*, 
                                    (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id = t.id) as message_count,
                                    (SELECT created_at FROM ticket_messages WHERE ticket_id = t.id ORDER BY created_at DESC LIMIT 1) as last_activity
                                FROM tickets t 
                                WHERE t.user_id = ? 
                                ORDER BY 
                                    CASE WHEN t.status = 'open' THEN 1 
                                        WHEN t.status = 'in_progress' THEN 2
                                        ELSE 3 END,
                                    t.updated_at DESC
                                LIMIT 3
                            ");
                            $tickets_stmt->execute([$_SESSION['user_id']]);
                            $recent_tickets = $tickets_stmt->fetchAll(PDO::FETCH_ASSOC);
                            
                            if (empty($recent_tickets)):
                        ?>
                            <div class="empty-state">
                                <i class='bx bx-support empty-state-icon'></i>
                                <h5 class="empty-state-title">No Support Tickets</h5>
                                <p class="empty-state-text">You haven't created any support tickets yet.</p>
                                <a href="tickets.php" class="btn btn-sm btn-primary">Create a Ticket</a>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($recent_tickets as $index => $ticket): ?>
                                    <a href="ticket_details.php?id=<?php echo $ticket['id']; ?>" class="list-group-item list-group-item-action p-3 staggered-ticket" data-index="<?php echo $index; ?>">
                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                            <h6 class="mb-0 text-truncate" style="max-width: 180px;"><?php echo htmlspecialchars($ticket['subject']); ?></h6>
                                            <?php 
                                            $statusClass = 'secondary';
                                            if ($ticket['status'] == 'open') $statusClass = 'info';
                                            if ($ticket['status'] == 'in_progress') $statusClass = 'warning';
                                            if ($ticket['status'] == 'closed') $statusClass = 'success';
                                            ?>
                                            <span class="badge bg-<?php echo $statusClass; ?> rounded-pill"><?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?></span>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <small class="text-muted">
                                                <i class='bx bx-message-detail'></i> <?php echo $ticket['message_count']; ?>
                                            </small>
                                            <small class="text-muted">
                                                <?php echo date('M j, Y', strtotime($ticket['last_activity'] ?? $ticket['created_at'])); ?>
                                            </small>
                                        </div>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                            <?php if (count($recent_tickets) < 3): ?>
                                <!-- Add empty space to maintain height -->
                                <div style="height: <?php echo (3 - count($recent_tickets)) * 80; ?>px;"></div>
                            <?php endif; ?>
                            <div class="card-footer bg-light text-center p-2 mt-auto">
                                <a href="tickets.php" class="text-primary text-decoration-none fw-medium">View All Tickets</a>
                            </div>
                        <?php endif; 
                        } catch (PDOException $e) {
                            echo "<!-- Error loading tickets: " . $e->getMessage() . " -->";
                        ?>
                            <div class="empty-state">
                                <i class='bx bx-support empty-state-icon'></i>
                                <h5 class="empty-state-title">No Support Tickets</h5>
                                <p class="empty-state-text">You haven't created any support tickets yet.</p>
                                <a href="tickets.php" class="btn btn-sm btn-primary">Create a Ticket</a>
                            </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
            
            <!-- Banking Tips Card -->
            <div class="col-lg-6 mb-6">
                <div class="dashboard-card d-flex flex-column card-fixed-height slide-up" style="animation-delay: 0.5s;">
                    <div class="card-header">
                        <h5 class="card-title"><i class='bx bx-bulb'></i> Banking Tips</h5>
                    </div>
                    <div class="card-body flex-grow-1 overflow-auto">
                        <div class="tip-item staggered-tip" data-index="0">
                            <div class="d-flex align-items-center mb-1">
                                <div class="tip-icon bg-primary-light text-primary me-2">
                                    <i class='bx bx-shield-quarter'></i>
                                </div>
                                <h6 class="mb-0 fs-6">Secure Your Account</h6>
                            </div>
                            <p class="text-muted small mb-0 ms-4 ps-2">Use a strong password and enable two-factor authentication for enhanced security.</p>
                        </div>
                        
                        <div class="tip-item staggered-tip" data-index="1">
                            <div class="d-flex align-items-center mb-1">
                                <div class="tip-icon bg-warning-light text-warning me-2">
                                    <i class='bx bx-credit-card'></i>
                                </div>
                                <h6 class="mb-0 fs-6">Monitor Transactions</h6>
                            </div>
                            <p class="text-muted small mb-0 ms-4 ps-2">Regularly check your account for any unauthorized transactions.</p>
                        </div>
                        
                        <div class="tip-item staggered-tip" data-index="2">
                            <div class="d-flex align-items-center mb-1">
                                <div class="tip-icon bg-success-light text-success me-2">
                                    <i class='bx bx-money'></i>
                                </div>
                                <h6 class="mb-0 fs-6">Save Automatically</h6>
                            </div>
                            <p class="text-muted small mb-0 ms-4 ps-2">Set up automatic transfers to your savings account to build your financial future.</p>
                        </div>
                        
                        <div class="tip-item staggered-tip" data-index="3">
                            <div class="d-flex align-items-center mb-1">
                                <div class="tip-icon bg-info-light text-info me-2">
                                    <i class='bx bx-calendar'></i>
                                </div>
                                <h6 class="mb-0 fs-6">Schedule Payments</h6>
                            </div>
                            <p class="text-muted small mb-0 ms-4 ps-2">Never miss a bill payment by scheduling automatic payments for recurring bills.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
   
        <!-- Notifications Card -->
        <div class="dashboard-card slide-up" style="animation-delay: 0.8s;">
            <div class="card-header">
                <h5 class="card-title"><i class='bx bx-bell'></i> Notifications</h5>
                <a href="notifications.php" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="card-body p-0">
                <?php
                // Direct database query to ensure we get notifications
                try {
                    $direct_stmt = $db->prepare("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 3");
                    $direct_stmt->execute([$_SESSION['user_id']]);
                    $direct_notifications = $direct_stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    if (empty($direct_notifications)):
                ?>
                    <div class="empty-state" style="height: 200px;">
                        <i class='bx bx-bell-off empty-state-icon'></i>
                        <h5 class="empty-state-title">No Notifications</h5>
                        <p class="empty-state-text">You don't have any notifications yet.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($direct_notifications as $index => $notification): ?>
                        <a href="<?php echo !empty($notification['link']) ? htmlspecialchars($notification['link']) : '#'; ?>" class="notification-item <?php echo ($notification['is_read'] == 0) ? 'unread' : ''; ?> staggered-notification" data-index="<?php echo $index; ?>">
                            <div class="notification-icon bg-<?php echo getNotificationColor($notification['type'] ?? 'default'); ?>-light text-<?php echo getNotificationColor($notification['type'] ?? 'default'); ?>">
                                <i class='bx <?php echo getNotificationIcon($notification['type'] ?? 'default'); ?>'></i>
                            </div>
                            <div class="notification-content">
                                <div class="notification-title"><?php echo htmlspecialchars($notification['title'] ?? 'Notification'); ?></div>
                                <div class="notification-text"><?php echo htmlspecialchars($notification['message'] ?? ''); ?></div>
                                <div class="notification-time"><?php echo date('M j, g:i A', strtotime($notification['created_at'] ?? 'now')); ?></div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php endif; 
                } catch (PDOException $e) {
                    echo "<!-- Error loading notifications: " . $e->getMessage() . " -->";
                ?>
                    <div class="empty-state" style="height: 200px;">
                        <i class='bx bx-bell-off empty-state-icon'></i>
                        <h5 class="empty-state-title">No Notifications</h5>
                        <p class="empty-state-text">You don't have any notifications yet.</p>
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/countup.js@2.0.7/dist/countUp.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (el) { return new bootstrap.Tooltip(el); });

    // --- 1. DYNAMIC BALANCE DISPLAY LOGIC (FIXED) ---
    const selector = document.getElementById('currencySelector');
    const display = document.getElementById('balanceDisplay');
    
function updateBalanceDisplay() {
    // Guard clause: Make sure elements exist before running
    if (!selector || !display) {
        console.error("Balance display or selector not found.");
        return;
    }
    // Guard clause: Make sure there's a selected option
    if (!selector.options || selector.selectedIndex < 0) {
        display.textContent = "No balance available";
        return;
    }

    const selectedOption = selector.options[selector.selectedIndex];
    const currency = selectedOption.value;
    const balance = parseFloat(selectedOption.dataset.balance);
    
    // Set decimal places based on currency type
    let decimalPlaces = 2;
    if (currency === 'BTC') decimalPlaces = 8;
    else if (currency === 'ETH') decimalPlaces = 6;
    else if (currency === 'USDT') decimalPlaces = 2;
    
    // Format the currency symbol properly
    let currencySymbol = '';
    if (currency === 'USD') currencySymbol = '$';
    else if (currency === 'EUR') currencySymbol = '€';
    else if (currency === 'GBP') currencySymbol = '£';
    else currencySymbol = currency + ' ';
    
    const countUpOptions = { 
        decimalPlaces: decimalPlaces, 
        duration: 1.5, 
        prefix: currencySymbol,
        separator: ',',  // Add comma as thousands separator
        decimal: '.',    // Use period as decimal separator
        useGrouping: true
    };

    try {
        let countUp = new CountUp(display, balance, countUpOptions);
        if (!countUp.error) {
            countUp.start();
            
            // Add a subtle animation to the balance
            display.classList.add('balance-updated');
            setTimeout(() => {
                display.classList.remove('balance-updated');
            }, 2000);
            
            // Update the last updated time
            const updateTimeElement = document.getElementById('balanceUpdateTime');
            if (updateTimeElement) {
                updateTimeElement.textContent = new Date().toLocaleString();
            }
        } else {
            console.error("CountUp.js Error:", countUp.error);
            // Fallback to simple text if CountUp fails
            display.textContent = `${currencySymbol}${balance.toFixed(decimalPlaces).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;
        }
    } catch(e) {
        console.error("Error initializing CountUp:", e);
        display.textContent = `${currencySymbol}${balance.toFixed(decimalPlaces).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`;
    }
}

    // Update balance when currency is changed
    if (selector) {
        selector.addEventListener('change', updateBalanceDisplay);
    }

    // Set the initial balance display on page load
    updateBalanceDisplay();


    // --- 2. YOUR EXISTING SCRIPT LOGIC (MERGED) ---

    // Copy to clipboard function
    window.copyAccountNumber = function() {
        const textToCopy = document.querySelector('.account-number-text').innerText;
        navigator.clipboard.writeText(textToCopy).then(function() {
            const copyButton = document.querySelector('.account-number button');
            const tooltip = bootstrap.Tooltip.getInstance(copyButton);
            tooltip.setContent({ '.tooltip-inner': 'Copied!' });
            setTimeout(() => {
                tooltip.setContent({ '.tooltip-inner': 'Copy Account Number' });
            }, 2000);
        });
    };

    // Staggered animations for various items
    const staggeredItems = document.querySelectorAll('.staggered-item, .staggered-transaction, .staggered-ticket, .staggered-tip, .staggered-notification');
    staggeredItems.forEach((item, index) => {
        setTimeout(() => {
            item.style.animation = 'slideInRight 0.5s ease forwards';
            item.style.opacity = '1'; // Ensure it becomes visible
        }, 300 + (index * 100));
    });

    // Initialize Spending Chart if data exists
    <?php if (!empty($spendingCategories)): ?>
    const spendingCtx = document.getElementById('spendingChart');
    if (spendingCtx) {
        // Chart.js logic for spendingChart...
    }
    <?php endif; ?>

    // Initialize Transaction History Chart if data exists
    <?php if (!empty($transactionHistory)): ?>
    const historyCtx = document.getElementById('transactionHistoryChart');
    if (historyCtx) {
        // Chart.js logic for transactionHistoryChart...
    }
    <?php endif; ?>

    // Add hover effects to cards
    const cards = document.querySelectorAll('.dashboard-card');
    cards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-5px)';
            this.style.boxShadow = '0 15px 30px -10px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1)';
        });
        card.addEventListener('mouseleave', function() {
            this.style.transform = '';
            this.style.boxShadow = '';
        });
    });
});
</script>

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