<?php
require_once 'includes/auth_check.php';
$page = 'dashboard';
require_once '../config/database.php';

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

// --- Helper function to check if a table exists ---
function tableExists($db, $tableName) {
    try {
        $result = $db->query("SELECT 1 FROM `$tableName` LIMIT 1");
        return $result !== false;
    } catch (Exception $e) {
        return false;
    }
}

// --- Use a reliable variable for the admin's name ---
$admin_name = $admin['username'] ?? $admin['email'] ?? 'Admin';
$admin_first_name = explode(' ', $admin['first_name'] ?? $admin_name)[0];

// --- Initialize all variables to prevent errors ---
$totalUsers = $pending_users = $pending_deposits = $pending_wires = $open_tickets = $monthly_volume = 0;
$financial_labels = $financial_income = $financial_expense = '[]';
$recent_activities = [];
$dashboardError = null;

try {
    // --- STAT CARD DATA (with checks) ---
    if (tableExists($db, 'users')) {
        $totalUsers = $db->query("SELECT COUNT(id) FROM users")->fetchColumn();
        $pending_users = $db->query("SELECT COUNT(id) FROM users WHERE status = 'pending'")->fetchColumn();
        
        // Get user growth data for the last 7 days
        $user_growth_stmt = $db->query("
            SELECT DATE(created_at) as date, COUNT(id) as count 
            FROM users 
            WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
            GROUP BY DATE(created_at) 
            ORDER BY date ASC
        ");
        $user_growth_data = $user_growth_stmt->fetchAll(PDO::FETCH_ASSOC);
        $user_growth_labels = json_encode(array_map(fn($row) => date('D', strtotime($row['date'])), $user_growth_data));
        $user_growth_values = json_encode(array_column($user_growth_data, 'count'));
    }
    
    if (tableExists($db, 'crypto_deposits')) {
        $pending_deposits = $db->query("SELECT COUNT(id) FROM crypto_deposits WHERE status = 'pending'")->fetchColumn();
    }
    
    if (tableExists($db, 'wire_transfers')) {
        $pending_wires = $db->query("SELECT COUNT(id) FROM wire_transfers WHERE status = 'pending'")->fetchColumn();
    }
    
    if (tableExists($db, 'tickets')) {
        $open_tickets = $db->query("SELECT COUNT(id) FROM tickets WHERE status != 'closed'")->fetchColumn();
        
        // Get ticket status distribution
        $ticket_status_stmt = $db->query("
            SELECT status, COUNT(id) as count 
            FROM tickets 
            GROUP BY status
        ");
        $ticket_status_data = $ticket_status_stmt->fetchAll(PDO::FETCH_ASSOC);
        $ticket_status_labels = json_encode(array_column($ticket_status_data, 'status'));
        $ticket_status_values = json_encode(array_column($ticket_status_data, 'count'));
    }
    
    if (tableExists($db, 'transactions')) {
        $monthly_volume = $db->query("SELECT SUM(amount) FROM transactions WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND status = 'completed'")->fetchColumn();
        
        // Get transaction volume by day for the last 30 days
        $volume_stmt = $db->query("
            SELECT DATE(created_at) as date, SUM(amount) as volume 
            FROM transactions 
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND status = 'completed' 
            GROUP BY DATE(created_at) 
            ORDER BY date ASC
        ");
        $volume_data = $volume_stmt->fetchAll(PDO::FETCH_ASSOC);
        $volume_labels = json_encode(array_map(fn($row) => date('M j', strtotime($row['date'])), $volume_data));
        $volume_values = json_encode(array_column($volume_data, 'volume'));
    }
    
    $pending_items_total = $pending_users + $pending_deposits + $pending_wires;

    // --- FINANCIAL SUMMARY CHART ---
    if (tableExists($db, 'transactions')) {
        $financial_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 created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) AND status = 'completed'
            GROUP BY DATE(created_at) ORDER BY date ASC
        ");
        $financial_stmt->execute();
        $financial_history = $financial_stmt->fetchAll(PDO::FETCH_ASSOC);
        $financial_labels = json_encode(array_map(fn($row) => date('M j', strtotime($row['date'])), $financial_history));
        $financial_income = json_encode(array_column($financial_history, 'income'));
        $financial_expense = json_encode(array_column($financial_history, 'expense'));
        
        // Calculate total income and expense
        $total_income = array_sum(array_column($financial_history, 'income'));
        $total_expense = array_sum(array_column($financial_history, 'expense'));
        $net_profit = $total_income - $total_expense;
        $profit_percentage = $total_income > 0 ? ($net_profit / $total_income) * 100 : 0;
    }

    // --- RECENT ACTIVITY FEED (Resilient Method) ---
    $all_activities = [];
    if (tableExists($db, 'users')) {
        $stmt = $db->query("SELECT 'new_user' as type, id as item_id, CONCAT(first_name, ' ', last_name) as description, created_at as timestamp, CONCAT('manage_users.php?view=', id) as link FROM users ORDER BY created_at DESC LIMIT 5");
        $all_activities = array_merge($all_activities, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }
    if (tableExists($db, 'crypto_deposits')) {
        $stmt = $db->query("SELECT 'new_deposit' as type, id as item_id, CONCAT('Deposit of ', amount, ' ', currency) as description, created_at as timestamp, CONCAT('crypto_deposits.php#deposit-', id) as link FROM crypto_deposits ORDER BY created_at DESC LIMIT 5");
        $all_activities = array_merge($all_activities, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }
    if (tableExists($db, 'tickets')) {
        $stmt = $db->query("SELECT 'new_ticket' as type, id as item_id, subject as description, created_at as timestamp, CONCAT('ticket_details.php?id=', id) as link FROM tickets ORDER BY created_at DESC LIMIT 5");
        $all_activities = array_merge($all_activities, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }
    // Sort all collected activities by timestamp and take the most recent
    usort($all_activities, fn($a, $b) => strtotime($b['timestamp']) - strtotime($a['timestamp']));
    $recent_activities = array_slice($all_activities, 0, 7);

    // Get user status distribution for pie chart
    if (tableExists($db, 'users')) {
        $user_status_stmt = $db->query("
            SELECT status, COUNT(id) as count 
            FROM users 
            GROUP BY status
        ");
        $user_status_data = $user_status_stmt->fetchAll(PDO::FETCH_ASSOC);
        $user_status_labels = json_encode(array_column($user_status_data, 'status'));
        $user_status_values = json_encode(array_column($user_status_data, 'count'));
        $user_status_colors = json_encode([
            'active' => '#10b981',
            'pending' => '#f59e0b',
            'suspended' => '#ef4444',
            'closed' => '#6b7280'
        ]);
    }

} catch (PDOException $e) {
    error_log("Admin Dashboard DB Error: " . $e->getMessage());
    $dashboardError = "A database error occurred. Some analytics may not be available. Please check the logs.";
}

include 'includes/header.php';
?>

<!-- Dashboard Styles -->
<style>
:root {
    --primary-color: #4f46e5;
    --primary-light: rgba(79, 70, 229, 0.1);
    --success-color: #10b981;
    --success-light: rgba(16, 185, 129, 0.1);
    --warning-color: #f59e0b;
    --warning-light: rgba(245, 158, 11, 0.1);
    --danger-color: #ef4444;
    --danger-light: rgba(239, 68, 68, 0.1);
    --info-color: #0ea5e9;
    --info-light: rgba(14, 165, 233, 0.1);
    --secondary-color: #6b7280;
    --secondary-light: rgba(107, 114, 128, 0.1);
}

.dashboard-welcome {
    background: linear-gradient(135deg, var(--primary-color), #6366f1);
    border-radius: 12px;
    padding: 1.5rem;
    color: white;
    margin-bottom: 1.5rem;
    position: relative;
    overflow: hidden;
}

.dashboard-welcome::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 300px;
    height: 100%;
    background-image: url('assets/images/pattern-white.svg');
    background-repeat: no-repeat;
    background-position: right center;
    background-size: contain;
    opacity: 0.1;
}

.stat-card {
    transition: all 0.3s ease;
    border-radius: 12px;
    border: none;
    box-shadow: 0 2px 12px rgba(0,0,0,0.04);
    overflow: hidden;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.stat-card .card-body {
    padding: 1.5rem;
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}

.bg-primary-light { background-color: var(--primary-light); color: var(--primary-color); }
.bg-warning-light { background-color: var(--warning-light); color: var(--warning-color); }
.bg-success-light { background-color: var(--success-light); color: var(--success-color); }
.bg-info-light { background-color: var(--info-light); color: var(--info-color); }
.bg-danger-light { background-color: var(--danger-light); color: var(--danger-color); }
.bg-secondary-light { background-color: var(--secondary-light); color: var(--secondary-color); }

.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; }

.card-title {
    font-size: 1rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.card-value {
    font-size: 1.75rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
}

.trend-indicator {
    display: inline-flex;
    align-items: center;
    font-size: 0.875rem;
    font-weight: 500;
}

.trend-indicator i {
    margin-right: 0.25rem;
}

.activity-item {
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 0.75rem;
    transition: all 0.2s ease;
    border-left: 3px solid transparent;
}

.activity-item:hover {
    background-color: rgba(0,0,0,0.02);
}

.activity-item.new-user { border-left-color: var(--primary-color); }
.activity-item.new-deposit { border-left-color: var(--success-color); }
.activity-item.new-ticket { border-left-color: var(--info-color); }

.activity-icon {
    width: 36px;
    height: 36px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
}

.chart-container {
    position: relative;
    height: 300px;
}

.metric-card {
    padding: 1.25rem;
    border-radius: 12px;
    background-color: white;
    box-shadow: 0 2px 12px rgba(0,0,0,0.04);
    transition: all 0.3s ease;
}

.metric-card:hover {
    box-shadow: 0 10px 20px rgba(0,0,0,0.08);
}

.metric-value {
    font-size: 1.5rem;
    font-weight: 700;
}

.metric-label {
    font-size: 0.875rem;
    color: var(--secondary-color);
}

.pending-item {
    transition: all 0.2s ease;
    border-radius: 8px;
    padding: 0.75rem 1rem;
}

.pending-item:hover {
    background-color: rgba(0,0,0,0.02);
    transform: translateX(5px);
}

.pending-item i {
    transition: transform 0.2s ease;
}

.pending-item:hover i {
    transform: translateX(3px);
}

.dashboard-card {
    border-radius: 12px;
    border: none;
    box-shadow: 0 2px 12px rgba(0,0,0,0.04);
    overflow: hidden;
    height: 100%;
}

.dashboard-card .card-header {
    background-color: white;
    border-bottom: 1px solid rgba(0,0,0,0.05);
    padding: 1rem 1.5rem;
}

.dashboard-card .card-title {
    margin-bottom: 0;
    display: flex;
    align-items: center;
}

.dashboard-card .card-title i {
    margin-right: 0.5rem;
    font-size: 1.25rem;
    opacity: 0.8;
}

.empty-state {

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 3rem 1rem;
    text-align: center;
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.2;
}

.empty-state p {
    color: var(--secondary-color);
    max-width: 300px;
    margin: 0 auto;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .stat-card .card-body {
        padding: 1rem;
    }
    
    .card-value {
        font-size: 1.5rem;
    }
    
    .dashboard-welcome {
        padding: 1rem;
    }
}
</style>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Welcome Banner -->
        <div class="dashboard-welcome">
            <div class="row align-items-center">
                <div class="col-lg-8">
                    <h1 class="h3 mb-2">Welcome back, <?php echo htmlspecialchars($admin_first_name); ?>!</h1>
                    <p class="mb-0 opacity-75">Here's what's happening with your banking system today.</p>
                </div>
                <div class="col-lg-4 text-lg-end mt-3 mt-lg-0">
                    <div class="d-inline-block text-start">
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <span class="d-block text-white opacity-75">Current Date</span>
                                <span class="h5 mb-0"><?php echo date('F j, Y'); ?></span>
                            </div>
                            <i class='bx bx-calendar fs-1 opacity-50'></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if (isset($dashboardError)): ?>
            <div class="alert alert-danger">
                <i class='bx bx-error-circle me-2'></i>
                <?php echo $dashboardError; ?>
            </div>
        <?php endif; ?>

        <!-- Stat Cards Row -->
        <div class="row g-4 mb-4">
            <div class="col-xl-3 col-md-6">
                <div class="stat-card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <span class="d-block text-muted mb-1">Total Users</span>
                                <h3 class="card-value mb-1"><?php echo number_format($totalUsers); ?></h3>
                                <div class="trend-indicator text-success">
                                    <i class='bx bx-up-arrow-alt'></i>
                                    <span>12% this month</span>
                                </div>
                            </div>
                            <div class="stat-icon bg-primary-light">
                                <i class='bx bxs-group'></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar bg-primary" role="progressbar" style="width: 75%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6">
                <div class="stat-card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <span class="d-block text-muted mb-1">Pending Items</span>
                                <h3 class="card-value mb-1"><?php echo number_format($pending_items_total); ?></h3>
                                <div class="trend-indicator <?php echo $pending_items_total > 5 ? 'text-warning' : 'text-success'; ?>">
                                    <i class='bx bx-time'></i>
                                    <span>Requires attention</span>
                                </div>
                            </div>
                            <div class="stat-icon bg-warning-light">
                                <i class='bx bx-time-five'></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar bg-warning" role="progressbar" style="width: <?php echo min(100, ($pending_items_total / 10) * 100); ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6">
                <div class="stat-card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <span class="d-block text-muted mb-1">Open Tickets</span>
                                <h3 class="card-value mb-1"><?php echo number_format($open_tickets); ?></h3>
                                <div class="trend-indicator <?php echo $open_tickets > 0 ? 'text-info' : 'text-success'; ?>">
                                    <i class='bx bx-support'></i>
                                    <span><?php echo $open_tickets > 0 ? 'Need response' : 'All resolved'; ?></span>
                                </div>
                            </div>
                            <div class="stat-icon bg-info-light">
                                <i class='bx bx-support'></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar bg-info" role="progressbar" style="width: <?php echo min(100, ($open_tickets / 5) * 100); ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-3 col-md-6">
                <div class="stat-card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <span class="d-block text-muted mb-1">30-Day Volume</span>
                                <h3 class="card-value mb-1">$<?php echo number_format($monthly_volume ?? 0, 0); ?></h3>
                                <div class="trend-indicator text-success">
                                    <i class='bx bx-up-arrow-alt'></i>
                                    <span>8.5% increase</span>
                                </div>
                            </div>
                            <div class="stat-icon bg-success-light">
                                <i class='bx bx-dollar-circle'></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar bg-success" role="progressbar" style="width: 65%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Content Row -->
        <div class="row g-4">
            <!-- Financial Summary Chart -->
            <div class="col-lg-8">
                <div class="dashboard-card h-100">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title">
                            <i class='bx bx-line-chart text-primary'></i>
                            Financial Summary
                        </h5>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="timeRangeDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                Last 30 Days
                            </button>
                            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="timeRangeDropdown">
                                <li><a class="dropdown-item active" href="#">Last 30 Days</a></li>
                                <li><a class="dropdown-item" href="#">Last Quarter</a></li>
                                <li><a class="dropdown-item" href="#">Year to Date</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="metric-card">
                                    <div class="d-flex align-items-center">
                                        <div class="stat-icon bg-success-light me-3">
                                            <i class='bx bx-trending-up'></i>
                                        </div>
                                        <div>
                                            <div class="metric-label">Total Income</div>
                                            <div class="metric-value text-success">$<?php echo number_format($total_income ?? 0, 0); ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="metric-card">
                                    <div class="d-flex align-items-center">
                                        <div class="stat-icon bg-danger-light me-3">
                                            <i class='bx bx-trending-down'></i>
                                        </div>
                                        <div>
                                            <div class="metric-label">Total Expense</div>
                                            <div class="metric-value text-danger">$<?php echo number_format($total_expense ?? 0, 0); ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="metric-card">
                                    <div class="d-flex align-items-center">
                                        <div class="stat-icon bg-primary-light me-3">
                                            <i class='bx bx-dollar'></i>
                                        </div>
                                        <div>
                                            <div class="metric-label">Net Profit</div>
                                            <div class="metric-value text-primary">$<?php echo number_format($net_profit ?? 0, 0); ?></div>
                                            <div class="small text-success">
                                                <i class='bx bx-up-arrow-alt'></i> <?php echo number_format($profit_percentage ?? 0, 1); ?>%
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="chart-container">
                            <canvas id="financialSummaryChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- What to do Next -->
            <div class="col-lg-4">
                <div class="dashboard-card h-100">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class='bx bx-list-check text-warning'></i>
                            Action Items
                        </h5>
                    </div>
                    <div class="card-body p-0">
                        <?php if ($pending_items_total == 0 && $open_tickets == 0): ?>
                            <div class="empty-state">
                                <i class="bx bx-check-shield text-success"></i>
                                <h5 class="mt-2">All Caught Up!</h5>
                                <p>There are no pending items that require your attention at this time.</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php if ($pending_users > 0): ?>
                                    <a href="manage_users.php?status=pending" class="list-group-item list-group-item-action pending-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <div class="d-flex align-items-center">
                                                    <div class="stat-icon bg-primary-light me-3" style="width: 36px; height: 36px; font-size: 1.1rem;">
                                                        <i class='bx bx-user-plus'></i>
                                                    </div>
                                                    <div>
                                                        <h6 class="mb-0">Pending User Registrations</h6>
                                                        <small class="text-muted">Needs verification</small>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="d-flex align-items-center">
                                                <span class="badge bg-primary rounded-pill me-2"><?php echo $pending_users; ?></span>
                                                <i class='bx bx-chevron-right text-muted'></i>
                                            </div>
                                        </div>
                                    </a>
                                <?php endif; ?>
                                
                                <?php if ($pending_deposits > 0): ?>
                                    <a href="crypto_deposits.php?status=pending" class="list-group-item list-group-item-action pending-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <div class="d-flex align-items-center">
                                                    <div class="stat-icon bg-success-light me-3" style="width: 36px; height: 36px; font-size: 1.1rem;">
                                                        <i class='bx bx-coin-stack'></i>
                                                    </div>
                                                    <div>
                                                        <h6 class="mb-0">Pending Crypto Deposits</h6>
                                                        <small class="text-muted">Awaiting approval</small>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="d-flex align-items-center">
                                                <span class="badge bg-success rounded-pill me-2"><?php echo $pending_deposits; ?></span>
                                                <i class='bx bx-chevron-right text-muted'></i>
                                            </div>
                                        </div>
                                    </a>
                                <?php endif; ?>
                                
                                <?php if ($pending_wires > 0): ?>
                                    <a href="wire_transactions.php?status=pending" class="list-group-item list-group-item-action pending-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <div class="d-flex align-items-center">
                                                    <div class="stat-icon bg-warning-light me-3" style="width: 36px; height: 36px; font-size: 1.1rem;">
                                                        <i class='bx bx-transfer'></i>
                                                    </div>
                                                                                                     <div>
                                                        <h6 class="mb-0">Pending Wire Transfers</h6>
                                                        <small class="text-muted">Needs processing</small>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="d-flex align-items-center">
                                                <span class="badge bg-warning rounded-pill me-2"><?php echo $pending_wires; ?></span>
                                                <i class='bx bx-chevron-right text-muted'></i>
                                            </div>
                                        </div>
                                    </a>
                                <?php endif; ?>
                                
                                <?php if ($open_tickets > 0): ?>
                                    <a href="tickets.php?status=open" class="list-group-item list-group-item-action pending-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <div class="d-flex align-items-center">
                                                    <div class="stat-icon bg-info-light me-3" style="width: 36px; height: 36px; font-size: 1.1rem;">
                                                        <i class='bx bx-support'></i>
                                                    </div>
                                                    <div>
                                                        <h6 class="mb-0">Open Support Tickets</h6>
                                                        <small class="text-muted">Awaiting response</small>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="d-flex align-items-center">
                                                <span class="badge bg-info rounded-pill me-2"><?php echo $open_tickets; ?></span>
                                                <i class='bx bx-chevron-right text-muted'></i>
                                            </div>
                                        </div>
                                    </a>
                                <?php endif; ?>
                            </div>
                            
                            <div class="p-3 text-center">
                                <a href="dashboard_tasks.php" class="btn btn-sm btn-outline-primary">
                                    View All Tasks <i class='bx bx-right-arrow-alt'></i>
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Second Row -->
        <div class="row g-4 mt-4">
            <!-- User Distribution Chart -->
            <div class="col-lg-4">
                <div class="dashboard-card h-100">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class='bx bx-pie-chart-alt-2 text-primary'></i>
                            User Distribution
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="chart-container" style="height: 240px;">
                            <canvas id="userStatusChart"></canvas>
                        </div>
                        <div class="mt-3">
                            <div class="row text-center">
                                <?php foreach ($user_status_data ?? [] as $status): ?>
                                <div class="col-6 mb-3">
                                    <div class="d-flex align-items-center">
                                        <span class="d-inline-block me-2" style="width: 12px; height: 12px; border-radius: 50%; background-color: <?php 
                                            echo match($status['status']) {
                                                'active' => '#10b981',
                                                'pending' => '#f59e0b',
                                                'suspended' => '#ef4444',
                                                'closed' => '#6b7280',
                                                default => '#6b7280'
                                            };
                                        ?>"></span>
                                        <div class="text-start">
                                            <div class="small text-muted"><?php echo ucfirst($status['status']); ?></div>
                                            <div class="fw-medium"><?php echo number_format($status['count']); ?></div>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- User Growth Chart -->
            <div class="col-lg-4">
                <div class="dashboard-card h-100">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class='bx bx-trending-up text-success'></i>
                            User Growth
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <div>
                                <h3 class="mb-0"><?php echo number_format($totalUsers); ?></h3>
                                <div class="text-muted">Total Users</div>
                            </div>
                            <div class="trend-indicator text-success">
                                <i class='bx bx-up-arrow-alt'></i>
                                <span>12% this week</span>
                            </div>
                        </div>
                        <div class="chart-container" style="height: 200px;">
                            <canvas id="userGrowthChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Ticket Status Chart -->
            <div class="col-lg-4">
                <div class="dashboard-card h-100">
                    <div class="card-header">
                        <h5 class="card-title">
                            <i class='bx bx-support text-info'></i>
                            Support Tickets
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($ticket_status_data)): ?>
                            <div class="empty-state">
                                <i class="bx bx-support"></i>
                                <h6 class="mt-2">No Tickets</h6>
                                <p>There are no support tickets in the system.</p>
                            </div>
                        <?php else: ?>
                            <div class="chart-container" style="height: 200px;">
                                <canvas id="ticketStatusChart"></canvas>
                            </div>
                            <div class="mt-3">
                                <div class="row">
                                    <?php 
                                    $ticket_colors = [
                                        'open' => '#0ea5e9',
                                        'in_progress' => '#f59e0b',
                                        'closed' => '#10b981'
                                    ];
                                    foreach ($ticket_status_data as $status): ?>
                                    <div class="col-4 text-center">
                                        <div class="d-flex flex-column">
                                            <span class="fw-medium"><?php echo number_format($status['count']); ?></span>
                                            <span class="small text-muted"><?php echo ucfirst(str_replace('_', ' ', $status['status'])); ?></span>
                                        </div>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Activity Feed -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="dashboard-card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title">
                            <i class='bx bx-pulse text-primary'></i>
                            Recent Activity
                        </h5>
                        <a href="#" class="btn btn-sm btn-outline-primary">View All</a>
                    </div>
                    <div class="card-body p-0">
                        <?php if (empty($recent_activities)): ?>
                            <div class="empty-state">
                                <i class="bx bx-calendar-x"></i>
                                <h6 class="mt-2">No Recent Activity</h6>
                                <p>There has been no recent activity in the system.</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($recent_activities as $activity): ?>
                                    <?php
                                    $icon = 'bx-question-mark';
                                    $color = 'secondary';
                                    $activityClass = '';
                                    
                                    switch ($activity['type']) {
                                        case 'new_user':
                                            $icon = 'bx-user-plus';
                                            $color = 'primary';
                                            $activityClass = 'new-user';
                                            break;
                                        case 'new_deposit':
                                            $icon = 'bx-wallet';
                                            $color = 'success';
                                            $activityClass = 'new-deposit';
                                            break;
                                        case 'new_ticket':
                                            $icon = 'bx-support';
                                            $color = 'info';
                                            $activityClass = 'new-ticket';
                                            break;
                                    }
                                    
                                    $timeAgo = time_elapsed_string(strtotime($activity['timestamp']));
                                    ?>
                                    <a href="<?php echo htmlspecialchars($activity['link']); ?>" class="list-group-item list-group-item-action activity-item <?php echo $activityClass; ?>">
                                        <div class="d-flex align-items-center">
                                            <div class="activity-icon bg-<?php echo $color; ?>-light me-3">
                                                <i class='bx <?php echo $icon; ?>'></i>
                                            </div>
                                            <div class="flex-grow-1">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($activity['description']); ?></h6>
                                                    <small class="text-muted"><?php echo $timeAgo; ?></small>
                                                </div>
                                                <small class="text-muted">
                                                    <?php 
                                                    switch ($activity['type']) {
                                                        case 'new_user':
                                                            echo 'New user registration';
                                                            break;
                                                        case 'new_deposit':
                                                            echo 'New crypto deposit';
                                                            break;
                                                        case 'new_ticket':
                                                            echo 'Support ticket created';
                                                            break;
                                                    }
                                                    ?>
                                                </small>
                                            </div>
                                        </div>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// Helper function to format time elapsed string
function time_elapsed_string($timestamp) {
    $diff = time() - $timestamp;
    
    if ($diff < 60) {
        return 'Just now';
    } elseif ($diff < 3600) {
        $mins = floor($diff / 60);
        return $mins . ' min' . ($mins > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        return $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ago';
    } elseif ($diff < 604800) {
        $days = floor($diff / 86400);
        return $days . ' day' . ($days > 1 ? 's' : '') . ' ago';
    } else {
        return date('M j, Y', $timestamp);
    }
}
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Set Chart.js defaults
    Chart.defaults.font.family = "'Inter', 'Helvetica', 'Arial', sans-serif";
    Chart.defaults.font.size = 12;
    Chart.defaults.color = '#6b7280';
    Chart.defaults.plugins.tooltip.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    Chart.defaults.plugins.tooltip.padding = 10;
    Chart.defaults.plugins.tooltip.cornerRadius = 6;
    Chart.defaults.plugins.tooltip.titleFont = { weight: 'bold' };
    Chart.defaults.plugins.legend.labels.usePointStyle = true;
    Chart.defaults.elements.line.tension = 0.4;
    Chart.defaults.elements.line.borderWidth = 2;
    Chart.defaults.elements.point.radius = 3;
    Chart.defaults.elements.point.hoverRadius = 5;
    
    // Financial Summary Chart
    const financialCtx = document.getElementById('financialSummaryChart');
    const financialLabels = <?php echo $financial_labels; ?>;

    if (financialCtx && financialLabels.length > 0) {
        new Chart(financialCtx.getContext('2d'), {
            type: 'line',
            data: {
                labels: financialLabels,
                datasets: [
                    {
                        label: 'Income',
                        data: <?php echo $financial_income; ?>,
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        fill: true,
                        pointBackgroundColor: '#10b981'
                    },
                    {
                        label: 'Expense',
                        data: <?php echo $financial_expense; ?>,
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        fill: true,
                        pointBackgroundColor: '#ef4444'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            drawBorder: false,
                            color: 'rgba(0, 0, 0, 0.05)'
                        },
                        ticks: {
                            callback: value => '$' + value.toLocaleString()
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                        align: 'end'
                    },
                    tooltip: {
                        callbacks: {
                            label: context => `${context.dataset.label}: $${context.raw.toLocaleString()}`
                        }
                    }
                }
            }
        });
    } else if (financialCtx) {
        // Display a message if there's no chart data
        const ctx = financialCtx.getContext('2d');
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.font = '16px Inter, Helvetica, Arial, sans-serif';
        ctx.fillStyle = '#6b7280';
        ctx.fillText('No financial data available for the last 30 days.', financialCtx.width / 2, financialCtx.height / 2);
    }
    
    // User Status Chart (Pie Chart)
    const userStatusCtx = document.getElementById('userStatusChart');
    const userStatusLabels = <?php echo $user_status_labels ?? '[]'; ?>;
    
    if (userStatusCtx && userStatusLabels.length > 0) {
        new Chart(userStatusCtx.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: userStatusLabels.map(label => label.charAt(0).toUpperCase() + label.slice(1)),
                datasets: [{
                    data: <?php echo $user_status_values ?? '[]'; ?>,
                    backgroundColor: [
                        '#10b981', // active - green
                        '#f59e0b', // pending - amber
                        '#ef4444', // suspended - red
                        '#6b7280'  // closed - gray
                    ],
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: (context) => {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = Math.round((value / total) * 100);
                                return `${label}: ${value} (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
    }
    
    // User Growth Chart
    const userGrowthCtx = document.getElementById('userGrowthChart');
    const userGrowthLabels = <?php echo $user_growth_labels ?? '[]'; ?>;
    
    if (userGrowthCtx && userGrowthLabels.length > 0) {
        new Chart(userGrowthCtx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: userGrowthLabels,
                datasets: [{
                    label: 'New Users',
                    data: <?php echo $user_growth_values ?? '[]'; ?>,
                    backgroundColor: 'rgba(79, 70, 229, 0.7)',
                    borderColor: 'rgba(79, 70, 229, 1)',
                    borderWidth: 1,
                    borderRadius: 4,
                    barThickness: 12,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            drawBorder: false,
                            color: 'rgba(0, 0, 0, 0.05)'
                        },
                        ticks: {
                            precision: 0
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    }
                }
            }
        });
    }
    
    // Ticket Status Chart
    const ticketStatusCtx = document.getElementById('ticketStatusChart');
    const ticketStatusLabels = <?php echo $ticket_status_labels ?? '[]'; ?>;
    
    if (ticketStatusCtx && ticketStatusLabels.length > 0) {
        new Chart(ticketStatusCtx.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: ticketStatusLabels.map(label => label.replace('_', ' ').charAt(0).toUpperCase() + label.replace('_', ' ').slice(1)),
                datasets: [{
                    data: <?php echo $ticket_status_values ?? '[]'; ?>,
                    backgroundColor: [
                        '#0ea5e9', // open - blue
                        '#f59e0b', // in_progress - amber
                        '#10b981'  // closed - green
                    ],
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 12,
                            padding: 15
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: (context) => {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = Math.round((value / total) * 100);
                                return `${label}: ${value} (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
    }
});
</script>

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