<?php
/**
 * Admin Dashboard - PREMIUM VERSION
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

// Check if user is admin
if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Admin Dashboard';

// Get dashboard stats
$stats = get_dashboard_stats();

// Get recent orders
$stmt = $pdo->query("SELECT o.*, u.name as user_name FROM orders o LEFT JOIN users u ON o.user_id = u.id ORDER BY o.created_at DESC LIMIT 10");
$recent_orders = $stmt->fetchAll();

// Get recent users
$stmt = $pdo->query("SELECT * FROM users WHERE role = 'user' ORDER BY created_at DESC LIMIT 5");
$recent_users = $stmt->fetchAll();

// Get sales chart data
$sales_data = get_sales_chart_data(30);

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

<div class="admin-content">
    <div class="admin-header">
        <h1><i class="fas fa-tachometer-alt me-2"></i>Dashboard</h1>
    </div>
    
    <!-- Stats Cards -->
    <div class="row g-4 mb-4">
        <div class="col-md-6 col-lg-3">
            <div class="stat-card bg-primary">
                <div class="stat-icon"><i class="fas fa-box"></i></div>
                <div class="stat-info">
                    <h3><?php echo number_format($stats['total_products'] ?? 0); ?></h3>
                    <p>Total Products</p>
                </div>
            </div>
        </div>
        
        <div class="col-md-6 col-lg-3">
            <div class="stat-card bg-success">
                <div class="stat-icon"><i class="fas fa-shopping-cart"></i></div>
                <div class="stat-info">
                    <h3><?php echo number_format($stats['total_orders'] ?? 0); ?></h3>
                    <p>Total Orders</p>
                </div>
            </div>
        </div>
        
        <div class="col-md-6 col-lg-3">
            <div class="stat-card bg-info">
                <div class="stat-icon"><i class="fas fa-users"></i></div>
                <div class="stat-info">
                    <h3><?php echo number_format($stats['total_customers'] ?? 0); ?></h3>
                    <p>Customers</p>
                </div>
            </div>
        </div>
        
        <div class="col-md-6 col-lg-3">
            <div class="stat-card bg-warning">
                <div class="stat-icon"><i class="fas fa-dollar-sign"></i></div>
                <div class="stat-info">
                    <h3><?php echo format_price($stats['total_revenue'] ?? 0); ?></h3>
                    <p>Total Revenue</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row g-4">
        <!-- Sales Chart -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-chart-line me-2"></i>Sales Overview (Last 30 Days)</h5>
                </div>
                <div class="card-body">
                    <canvas id="salesChart" height="300"></canvas>
                </div>
            </div>
        </div>
        
        <!-- Quick Stats -->
        <div class="col-lg-4">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-chart-pie me-2"></i>Quick Stats</h5>
                </div>
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span>Today's Revenue</span>
                        <strong class="text-success"><?php echo format_price($stats['today_revenue'] ?? 0); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span>This Month</span>
                        <strong class="text-primary"><?php echo format_price($stats['month_revenue'] ?? 0); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span>Pending Orders</span>
                        <strong class="text-warning"><?php echo $stats['pending_orders'] ?? 0; ?></strong>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <span>Pending Negotiations</span>
                        <strong class="text-info"><?php echo $stats['pending_negotiations'] ?? 0; ?></strong>
                    </div>
                </div>
            </div>
            
            <!-- Recent Users -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-user-plus me-2"></i>New Users</h5>
                </div>
                <div class="card-body p-0">
                    <ul class="list-group list-group-flush">
                        <?php foreach ($recent_users as $user): ?>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <strong><?php echo sanitize($user['name']); ?></strong>
                                <small class="d-block text-muted"><?php echo sanitize($user['email']); ?></small>
                            </div>
                            <small class="text-muted"><?php echo time_ago($user['created_at']); ?></small>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Recent Orders -->
    <div class="card mt-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-shopping-bag me-2"></i>Recent Orders</h5>
            <a href="orders.php" class="btn btn-sm btn-primary">View All</a>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Order #</th>
                            <th>Customer</th>
                            <th>Date</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recent_orders as $order): ?>
                        <tr>
                            <td><strong><?php echo $order['order_number']; ?></strong></td>
                            <td><?php echo sanitize($order['user_name'] ?? $order['customer_name'] ?? 'Guest'); ?></td>
                            <td><?php echo format_date($order['created_at']); ?></td>
                            <td><?php echo format_price($order['total']); ?></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo match($order['payment_status']) {
                                        'completed' => 'success',
                                        'pending' => 'warning',
                                        'failed' => 'danger',
                                        default => 'secondary'
                                    };
                                ?>">
                                    <?php echo ucfirst($order['payment_status']); ?>
                                </span>
                            </td>
                            <td>
                                <a href="order-view.php?id=<?php echo $order['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fas fa-eye"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Sales Chart
const ctx = document.getElementById('salesChart').getContext('2d');
const salesData = <?php echo json_encode($sales_data); ?>;

new Chart(ctx, {
    type: 'line',
    data: {
        labels: salesData.map(d => d.date),
        datasets: [{
            label: 'Revenue',
            data: salesData.map(d => d.revenue),
            borderColor: '#6366f1',
            backgroundColor: 'rgba(99, 102, 241, 0.1)',
            fill: true,
            tension: 0.4
        }, {
            label: 'Orders',
            data: salesData.map(d => d.orders),
            borderColor: '#10b981',
            backgroundColor: 'rgba(16, 185, 129, 0.1)',
            fill: true,
            tension: 0.4,
            yAxisID: 'y1'
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: {
            intersect: false,
            mode: 'index'
        },
        scales: {
            y: {
                beginAtZero: true,
                grid: {
                    color: 'rgba(255, 255, 255, 0.1)'
                },
                ticks: {
                    color: '#9ca3af'
                }
            },
            y1: {
                type: 'linear',
                display: true,
                position: 'right',
                beginAtZero: true,
                grid: {
                    drawOnChartArea: false
                },
                ticks: {
                    color: '#9ca3af'
                }
            },
            x: {
                grid: {
                    color: 'rgba(255, 255, 255, 0.1)'
                },
                ticks: {
                    color: '#9ca3af'
                }
            }
        },
        plugins: {
            legend: {
                labels: {
                    color: '#9ca3af'
                }
            }
        }
    }
});
</script>

<style>
.stat-card {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1.5rem;
    border-radius: 0.5rem;
    color: white;
}

.stat-icon {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255,255,255,0.2);
    border-radius: 0.5rem;
    font-size: 1.5rem;
}

.stat-info h3 {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
}

.stat-info p {
    margin: 0;
    opacity: 0.8;
}
</style>

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