<?php
require_once __DIR__ . '/includes/admin_header.php';

// Get statistics
$products_count = $conn->query("SELECT COUNT(*) AS total FROM products")->fetch_assoc()['total'];
$orders_count = $conn->query("SELECT COUNT(*) AS total FROM orders")->fetch_assoc()['total'];
$customers_count = $conn->query("SELECT COUNT(*) AS total FROM customers")->fetch_assoc()['total'];

// Get revenue with improved query to handle NULL values
$revenue_result = $conn->query("SELECT COALESCE(SUM(total_amount), 0) AS revenue FROM orders WHERE status = 'completed'");
$revenue = $revenue_result->fetch_assoc()['revenue'];

// Get recent orders with prepared statement for security
$stmt = $conn->prepare("
    SELECT o.order_id AS id, o.order_date, o.total_amount, o.status, c.name AS customer_name 
    FROM orders o
    JOIN customers c ON o.customer_id = c.customer_id
    ORDER BY o.order_date DESC
    LIMIT 5
");
$stmt->execute();
$recent_orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>

<div class="admin-content">
    <div class="page-header">
        <h1 class="page-title">
            <i class="fas fa-tachometer-alt"></i> Dashboard
        </h1>
    </div>
    
    <!-- Stats Overview with Real Growth Calculation -->
    <div class="stats-grid">
        <?php
        // Calculate growth percentages (example implementation)
        $products_growth = calculateGrowth('products', 'created_at');
        $orders_growth = calculateGrowth('orders', 'order_date');
        $customers_growth = calculateGrowth('customers', 'created_at');
        $revenue_growth = calculateRevenueGrowth();
        ?>
        
        <div class="stat-card">
            <div class="stat-header">
                <span class="stat-title">Total Products</span>
                <div class="stat-icon primary">
                    <i class="fas fa-box-open"></i>
                </div>
            </div>
            <div class="stat-value"><?= number_format($products_count) ?></div>
            <div class="stat-change <?= $products_growth >= 0 ? 'positive' : 'negative' ?>">
                <i class="fas fa-arrow-<?= $products_growth >= 0 ? 'up' : 'down' ?>"></i>
                <span><?= abs($products_growth) ?>% from last month</span>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-header">
                <span class="stat-title">Total Orders</span>
                <div class="stat-icon secondary">
                    <i class="fas fa-shopping-cart"></i>
                </div>
            </div>
            <div class="stat-value"><?= number_format($orders_count) ?></div>
            <div class="stat-change <?= $orders_growth >= 0 ? 'positive' : 'negative' ?>">
                <i class="fas fa-arrow-<?= $orders_growth >= 0 ? 'up' : 'down' ?>"></i>
                <span><?= abs($orders_growth) ?>% from last month</span>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-header">
                <span class="stat-title">Total Customers</span>
                <div class="stat-icon accent">
                    <i class="fas fa-users"></i>
                </div>
            </div>
            <div class="stat-value"><?= number_format($customers_count) ?></div>
            <div class="stat-change <?= $customers_growth >= 0 ? 'positive' : 'negative' ?>">
                <i class="fas fa-arrow-<?= $customers_growth >= 0 ? 'up' : 'down' ?>"></i>
                <span><?= abs($customers_growth) ?>% from last month</span>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-header">
                <span class="stat-title">Total Revenue</span>
                <div class="stat-icon danger">
                    <i class="fas fa-money-bill-wave"></i>
                </div>
            </div>
            <div class="stat-value">KSh <?= number_format($revenue, 2) ?></div>
            <div class="stat-change <?= $revenue_growth >= 0 ? 'positive' : 'negative' ?>">
                <i class="fas fa-arrow-<?= $revenue_growth >= 0 ? 'up' : 'down' ?>"></i>
                <span><?= abs($revenue_growth) ?>% from last month</span>
            </div>
        </div>
    </div>
    
    <!-- Quick Actions Panel -->
    <div class="quick-actions-panel">
        <h3 class="panel-title">Quick Actions</h3>
        <div class="actions-grid">
            <a href="products.php?action=add" class="action-card">
                <i class="fas fa-plus-circle"></i>
                <span>Add New Product</span>
            </a>
            <a href="orders.php?filter=pending" class="action-card">
                <i class="fas fa-clock"></i>
                <span>Process Pending Orders</span>
            </a>
            <a href="reports.php" class="action-card">
                <i class="fas fa-chart-bar"></i>
                <span>Generate Reports</span>
            </a>
            <a href="settings.php" class="action-card">
                <i class="fas fa-cog"></i>
                <span>System Settings</span>
            </a>
        </div>
    </div>
    
    <!-- Recent Activity Section -->
    <div class="activity-container">
        <div class="table-header">
            <h3 class="table-title">Recent Orders</h3>
            <div class="table-actions">
                <a href="orders.php" class="btn btn-primary">
                    <i class="fas fa-list"></i> View All Orders
                </a>
                <a href="orders.php?export=recent" class="btn btn-outline">
                    <i class="fas fa-download"></i> Export
                </a>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>Order ID</th>
                        <th>Customer</th>
                        <th>Date</th>
                        <th>Amount</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent_orders as $order): ?>
                    <tr>
                        <td>#<?= $order['id'] ?></td>
                        <td><?= htmlspecialchars($order['customer_name']) ?></td>
                        <td><?= date('M j, Y', strtotime($order['order_date'])) ?></td>
                        <td>KSh <?= number_format($order['total_amount'], 2) ?></td>
                        <td>
                            <span class="status-badge <?= strtolower($order['status']) ?>">
                                <?= ucfirst($order['status']) ?>
                            </span>
                        </td>
                        <td class="action-cell">
                            <div class="btn-group">
                                <a href="order_view.php?id=<?= $order['id'] ?>" class="action-btn" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="order_edit.php?id=<?= $order['id'] ?>" class="action-btn" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="order_process.php?id=<?= $order['id'] ?>" class="action-btn" title="Process">
                                    <i class="fas fa-cog"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
// Real-time updates for dashboard (using fetch API)
function updateDashboardStats() {
    fetch('/admin/api/dashboard_stats.php')
        .then(response => response.json())
        .then(data => {
            // Update stats cards with new data
            document.querySelector('.stat-value:nth-child(1)').textContent = data.products_count;
            document.querySelector('.stat-value:nth-child(2)').textContent = data.orders_count;
            // ... update other values
        });
}

// Update stats every 60 seconds
setInterval(updateDashboardStats, 60000);
</script>

<?php require_once __DIR__ . '/includes/admin_footer.php'; 

// Helper functions for growth calculations
function calculateGrowth($table, $dateColumn) {
    global $conn;
    
    $current_month = $conn->query("
        SELECT COUNT(*) as count 
        FROM $table 
        WHERE $dateColumn >= DATE_FORMAT(NOW(), '%Y-%m-01')
    ")->fetch_assoc()['count'];
    
    $previous_month = $conn->query("
        SELECT COUNT(*) as count 
        FROM $table 
        WHERE $dateColumn >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m-01')
        AND $dateColumn < DATE_FORMAT(NOW(), '%Y-%m-01')
    ")->fetch_assoc()['count'];
    
    if ($previous_month == 0) return 0;
    return round((($current_month - $previous_month) / $previous_month) * 100, 1);
}

function calculateRevenueGrowth() {
    global $conn;
    
    $current_month = $conn->query("
        SELECT COALESCE(SUM(total_amount), 0) as revenue 
        FROM orders 
        WHERE status = 'completed'
        AND order_date >= DATE_FORMAT(NOW(), '%Y-%m-01')
    ")->fetch_assoc()['revenue'];
    
    $previous_month = $conn->query("
        SELECT COALESCE(SUM(total_amount), 0) as revenue 
        FROM orders 
        WHERE status = 'completed'
        AND order_date >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m-01')
        AND order_date < DATE_FORMAT(NOW(), '%Y-%m-01')
    ")->fetch_assoc()['revenue'];
    
    if ($previous_month == 0) return 0;
    return round((($current_month - $previous_month) / $previous_month) * 100, 1);
}
?>