<?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';

// --- 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();
    }
    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();
    }
    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();
    }
    $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'));
    }

    // --- RECENT ACTIVITY FEED (Resilient Method) ---
    $all_activities = [];
    if (tableExists($db, 'users')) {
        $stmt = $db->query("SELECT 'new_user' as type, 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 3");
        $all_activities = array_merge($all_activities, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }
    if (tableExists($db, 'crypto_deposits')) {
        $stmt = $db->query("SELECT 'new_deposit' as type, 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 3");
        $all_activities = array_merge($all_activities, $stmt->fetchAll(PDO::FETCH_ASSOC));
    }
    if (tableExists($db, 'tickets')) {
        $stmt = $db->query("SELECT 'new_ticket' as type, subject as description, created_at as timestamp, CONCAT('ticket_details.php?id=', id) as link FROM tickets ORDER BY created_at DESC LIMIT 3");
        $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);

} 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';
// Sidebar include removed as requested
?>

<style>
.stat-card { transition: all 0.3s ease; }
.stat-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
.icon-circle { width: 50px; height: 50px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; }
.bg-primary-light { background-color: rgba(79, 70, 229, 0.1); color: #4f46e5; }
.bg-warning-light { background-color: rgba(245, 158, 11, 0.1); color: #f59e0b; }
.bg-success-light { background-color: rgba(16, 185, 129, 0.1); color: #10b981; }
.bg-info-light { background-color: rgba(14, 165, 233, 0.1); color: #0ea5e9; }
.pending-item { transition: background-color 0.2s ease; }
.pending-item:hover { background-color: #f8f9fa; }
</style>

<div class="content-wrapper">
    <div class="container-fluid">
        <div class="page-header">
            <h1 class="page-header-title">Admin Dashboard</h1>
            <p class="text-muted">Welcome back, <?php echo htmlspecialchars($admin_name); ?>!</p>
        </div>

        <?php if (isset($dashboardError)): ?>
            <div class="alert alert-danger"><?php echo $dashboardError; ?></div>
        <?php endif; ?>

        <!-- Stat Cards Row -->
        <div class="row g-4">
            <div class="col-xl-3 col-md-6"><div class="card stat-card h-100"><div class="card-body d-flex justify-content-between align-items-center"><div><h6 class="text-muted fw-normal mb-1">Total Users</h6><h3 class="mb-0 fw-bold"><?php echo number_format($totalUsers); ?></h3></div><div class="icon-circle bg-primary-light"><i class='bx bxs-group'></i></div></div></div></div>
            <div class="col-xl-3 col-md-6"><div class="card stat-card h-100"><div class="card-body d-flex justify-content-between align-items-center"><div><h6 class="text-muted fw-normal mb-1">Pending Items</h6><h3 class="mb-0 fw-bold"><?php echo number_format($pending_items_total); ?></h3></div><div class="icon-circle bg-warning-light"><i class='bx bx-time-five'></i></div></div></div></div>
            <div class="col-xl-3 col-md-6"><div class="card stat-card h-100"><div class="card-body d-flex justify-content-between align-items-center"><div><h6 class="text-muted fw-normal mb-1">Open Tickets</h6><h3 class="mb-0 fw-bold"><?php echo number_format($open_tickets); ?></h3></div><div class="icon-circle bg-info-light"><i class='bx bx-support'></i></div></div></div></div>
            <div class="col-xl-3 col-md-6"><div class="card stat-card h-100"><div class="card-body d-flex justify-content-between align-items-center"><div><h6 class="text-muted fw-normal mb-1">30-Day Volume</h6><h3 class="mb-0 fw-bold">$<?php echo number_format($monthly_volume ?? 0, 2); ?></h3></div><div class="icon-circle bg-success-light"><i class='bx bx-dollar-circle'></i></div></div></div></div>
        </div>

        <!-- Main Content Row -->
        <div class="row g-4 mt-2">
            <div class="col-lg-7">
                <div class="card h-100">
                    <div class="card-header"><h5 class="card-title"><i class='bx bx-line-chart me-2'></i>Financial Summary (Last 30 Days)</h5></div>
                    <div class="card-body"><div style="height: 320px;"><canvas id="financialSummaryChart"></canvas></div></div>
                </div>
            </div>
            <div class="col-lg-5">
                <div class="card h-100">
                    <div class="card-header"><h5 class="card-title"><i class='bx bx-list-check me-2'></i>What to do Next</h5></div>
                    <div class="card-body">
                        <?php if ($pending_items_total == 0 && $open_tickets == 0): ?>
                            <div class="text-center text-muted p-4"><i class="bx bx-check-shield fs-1 text-success"></i><h5 class="mt-2">All Caught Up!</h5><p>No pending items require your attention.</p></div>
                        <?php else: ?>
                            <ul 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 d-flex justify-content-between align-items-center pending-item">Pending User Registrations <span class="badge bg-warning rounded-pill"><?php echo $pending_users; ?></span></a><?php endif; ?>
                                <?php if ($pending_deposits > 0): ?><a href="crypto_deposits.php?status=pending" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center pending-item">Pending Crypto Deposits <span class="badge bg-warning rounded-pill"><?php echo $pending_deposits; ?></span></a><?php endif; ?>
                                <?php if ($pending_wires > 0): ?><a href="wire_transactions.php?status=pending" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center pending-item">Pending Wire Transfers <span class="badge bg-warning rounded-pill"><?php echo $pending_wires; ?></span></a><?php endif; ?>
                                <?php if ($open_tickets > 0): ?><a href="tickets.php?status=open" class="list-group-item list-group-item-action d-flex justify-content-between align-items-center pending-item">Open Support Tickets <span class="badge bg-info rounded-pill"><?php echo $open_tickets; ?></span></a><?php endif; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Activity Feed -->
        <div class="card mt-4">
            <div class="card-header"><h5 class="card-title"><i class='bx bx-pulse me-2'></i>Recent Activity</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <tbody>
                            <?php if (empty($recent_activities)): ?>
                                <tr><td class="text-center p-4 text-muted">No recent activity to display.</td></tr>
                            <?php else: ?>
                                <?php foreach ($recent_activities as $activity): ?>
                                    <tr>
                                        <td class="ps-4" style="width: 50px;">
                                            <?php
                                            $icon = 'bx-question-mark'; $color = 'secondary';
                                            switch ($activity['type']) {
                                                case 'new_user': $icon = 'bx-user-plus'; $color = 'primary'; break;
                                                case 'new_deposit': $icon = 'bx-wallet'; $color = 'success'; break;
                                                case 'new_ticket': $icon = 'bx-support'; $color = 'info'; break;
                                            }
                                            ?>
                                            <div class="icon-circle bg-<?php echo $color; ?>-light"><i class='bx <?php echo $icon; ?>'></i></div>
                                        </td>
                                        <td><a href="<?php echo htmlspecialchars($activity['link']); ?>" class="text-dark text-decoration-none fw-bold"><?php echo htmlspecialchars($activity['description']); ?></a></td>
                                        <td class="text-end text-muted pe-4"><?php echo date('M j, Y g:i A', strtotime($activity['timestamp'])); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const financialCtx = document.getElementById('financialSummaryChart');
    const financialLabels = <?php echo $financial_labels; ?>;

    // FIX: Only initialize the chart if there is data to display
    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,
                        tension: 0.4
                    },
                    {
                        label: 'Expense',
                        data: <?php echo $financial_expense; ?>,
                        borderColor: '#ef4444',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        fill: true,
                        tension: 0.4
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: { y: { beginAtZero: true, ticks: { callback: value => '$' + value } } },
                plugins: { tooltip: { callbacks: { label: context => `${context.dataset.label}: $${context.raw.toFixed(2)}` } } }
            }
        });
    } else if (financialCtx) {
        // Optional: Display a message if there's no chart data
        const ctx = financialCtx.getContext('2d');
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.font = '16px Arial';
        ctx.fillText('No financial data available for the last 30 days.', financialCtx.width / 2, financialCtx.height / 2);
    }
});
</script>

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