<?php
require_once '../includes/config.php';

// Check if admin is logged in
if (!isAdminLoggedIn()) {
    redirect(SITE_URL . 'admin/login.php');
}

// Get statistics
try {
    $conn = connectDB();
    
    // Total users
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM users");
    $stmt->execute();
    $totalUsers = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Total products
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM products");
    $stmt->execute();
    $totalProducts = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Total orders
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM orders");
    $stmt->execute();
    $totalOrders = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Total revenue
    $stmt = $conn->prepare("SELECT SUM(total_amount) as total FROM orders WHERE status != 'cancelled'");
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalRevenue = $result['total'] ? $result['total'] : 0;
    
    // Recent orders
    $stmt = $conn->prepare("SELECT o.*, u.name as user_name FROM orders o 
                            LEFT JOIN users u ON o.user_id = u.user_id 
                            ORDER BY o.created_at DESC LIMIT 5");
    $stmt->execute();
    $recentOrders = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch revenue data for charts
    // Daily revenue (today's hourly breakdown)
    $stmt = $conn->prepare("SELECT 
                                HOUR(created_at) as hour,
                                SUM(total_amount) as revenue
                            FROM orders 
                            WHERE DATE(created_at) = CURDATE() AND status != 'cancelled'
                            GROUP BY HOUR(created_at)
                            ORDER BY hour");
    $stmt->execute();
    $dailyRevenueData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Last 7 days revenue
    $stmt = $conn->prepare("SELECT 
                                DATE(created_at) as date,
                                SUM(total_amount) as revenue
                            FROM orders 
                            WHERE created_at >= DATE(NOW()) - INTERVAL 6 DAY AND status != 'cancelled'
                            GROUP BY DATE(created_at)
                            ORDER BY date");
    $stmt->execute();
    $weeklyRevenueData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Last 6 months revenue
    $stmt = $conn->prepare("SELECT 
                                YEAR(created_at) as year,
                                MONTH(created_at) as month,
                                SUM(total_amount) as revenue
                            FROM orders 
                            WHERE created_at >= DATE(NOW()) - INTERVAL 5 MONTH AND status != 'cancelled'
                            GROUP BY YEAR(created_at), MONTH(created_at)
                            ORDER BY year, month");
    $stmt->execute();
    $monthlyRevenueData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = $e->getMessage();
}

// Prepare data for charts in JSON format
$dailyChartLabels = [];
$dailyChartData = [];
for ($i = 0; $i < 24; $i++) {
    $found = false;
    foreach ($dailyRevenueData as $data) {
        if ((int)$data['hour'] === $i) {
            $dailyChartLabels[] = $i . ':00';
            $dailyChartData[] = (int)$data['revenue'];
            $found = true;
            break;
        }
    }
    if (!$found) {
        $dailyChartLabels[] = $i . ':00';
        $dailyChartData[] = 0;
    }
}

// Prepare weekly data
$weeklyChartLabels = [];
$weeklyChartData = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $dayName = date('D', strtotime("-$i days"));
    $found = false;
    
    foreach ($weeklyRevenueData as $data) {
        if ($data['date'] === $date) {
            $weeklyChartLabels[] = $dayName;
            $weeklyChartData[] = (int)$data['revenue'];
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        $weeklyChartLabels[] = $dayName;
        $weeklyChartData[] = 0;
    }
}

// Prepare monthly data
$monthlyChartLabels = [];
$monthlyChartData = [];
for ($i = 5; $i >= 0; $i--) {
    $month = date('Y-m', strtotime("-$i months"));
    $monthYear = date('Y', strtotime("-$i months"));
    $monthNum = date('n', strtotime("-$i months"));
    $monthName = date('M Y', strtotime("-$i months"));
    
    $found = false;
    foreach ($monthlyRevenueData as $data) {
        if ((int)$data['year'] === (int)$monthYear && (int)$data['month'] === (int)$monthNum) {
            $monthlyChartLabels[] = $monthName;
            $monthlyChartData[] = (int)$data['revenue'];
            $found = true;
            break;
        }
    }
    
    if (!$found) {
        $monthlyChartLabels[] = $monthName;
        $monthlyChartData[] = 0;
    }
}

// Page title
$pageTitle = "Dashboard Admin";

// Include header
include 'header.php';
?>

<div class="admin-header">
    <h1>Dashboard Admin</h1>
    <div class="date-time">
        <?php echo date('l, d F Y'); ?>
    </div>
</div>

<div class="dashboard-stats">
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-users"></i>
        </div>
        <div class="stat-info">
            <h3>Total User</h3>
            <p><?php echo $totalUsers; ?></p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-box"></i>
        </div>
        <div class="stat-info">
            <h3>Total Produk</h3>
            <p><?php echo $totalProducts; ?></p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-shopping-cart"></i>
        </div>
        <div class="stat-info">
            <h3>Total Pesanan</h3>
            <p><?php echo $totalOrders; ?></p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-money-bill-wave"></i>
        </div>
        <div class="stat-info">
            <h3>Total Pendapatan</h3>
            <p>Rp <?php echo number_format($totalRevenue, 0, ',', '.'); ?></p>
        </div>
    </div>
</div>

<!-- Revenue Charts Section -->
<div class="charts-container">
    <div class="chart-section">
        <div class="chart-card">
            <h2>Pendapatan Hari Ini (Per Jam)</h2>
            <div class="chart-container">
                <canvas id="dailyRevenueChart"></canvas>
            </div>
        </div>
    </div>
    
    <div class="chart-section">
        <div class="chart-row">
            <div class="chart-card">
                <h2>Pendapatan 7 Hari Terakhir</h2>
                <div class="chart-container">
                    <canvas id="weeklyRevenueChart"></canvas>
                </div>
            </div>
            
            <div class="chart-card">
                <h2>Pendapatan 6 Bulan Terakhir</h2>
                <div class="chart-container">
                    <canvas id="monthlyRevenueChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="dashboard-recent">
    <div class="dashboard-section">
        <h2>Pesanan Terbaru</h2>
        <?php if (empty($recentOrders)): ?>
            <p>Belum ada pesanan</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Pelanggan</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Tanggal</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentOrders as $order): ?>
                            <tr>
                                <td>#<?php echo $order['order_id']; ?></td>
                                <td><?php echo $order['user_name']; ?></td>
                                <td>Rp <?php echo number_format($order['total_amount'], 0, ',', '.'); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $order['status']; ?>">
                                        <?php 
                                        switch($order['status']) {
                                            case 'pending': echo 'Menunggu'; break;
                                            case 'processing': echo 'Diproses'; break;
                                            case 'shipped': echo 'Dikirim'; break;
                                            case 'delivered': echo 'Terkirim'; break;
                                            case 'cancelled': echo 'Dibatalkan'; break;
                                            default: echo $order['status']; break;
                                        }
                                        ?>
                                    </span>
                                </td>
                                <td><?php echo date('d/m/Y', strtotime($order['created_at'])); ?></td>
                                <td>
                                    <a href="orders/detail.php?id=<?php echo $order['order_id']; ?>" class="action-btn view-btn">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="view-all-link">
                <a href="orders/">Lihat Semua Pesanan</a>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="dashboard-quick-actions">
    <h2>Aksi Cepat</h2>
    <div class="quick-actions">
        <a href="products/add.php" class="quick-action-btn">
            <i class="fas fa-plus"></i> Tambah Produk
        </a>
        <a href="categories/add.php" class="quick-action-btn">
            <i class="fas fa-folder-plus"></i> Tambah Kategori
        </a>
        <a href="orders/" class="quick-action-btn">
            <i class="fas fa-list"></i> Kelola Pesanan
        </a>
        <a href="users/" class="quick-action-btn">
            <i class="fas fa-users-cog"></i> Kelola User
        </a>
    </div>
</div>

<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- Chart scripts -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Styles configuration
    const chartColors = {
        primary: '#4caf50',
        primaryLight: 'rgba(76, 175, 80, 0.2)',
        secondary: '#3498db',
        secondaryLight: 'rgba(52, 152, 219, 0.2)',
        tertiary: '#e74c3c',
        tertiaryLight: 'rgba(231, 76, 60, 0.2)'
    };
    
    const chartOptions = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            },
            tooltip: {
                callbacks: {
                    label: function(context) {
                        return 'Rp ' + new Intl.NumberFormat('id-ID').format(context.raw);
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return 'Rp ' + new Intl.NumberFormat('id-ID').format(value);
                    }
                }
            }
        }
    };
    
    // Daily Revenue Chart
    const dailyChartCtx = document.getElementById('dailyRevenueChart').getContext('2d');
    const dailyRevenueChart = new Chart(dailyChartCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($dailyChartLabels); ?>,
            datasets: [{
                label: 'Pendapatan per Jam',
                data: <?php echo json_encode($dailyChartData); ?>,
                backgroundColor: chartColors.primaryLight,
                borderColor: chartColors.primary,
                borderWidth: 1
            }]
        },
        options: chartOptions
    });
    
    // Weekly Revenue Chart
    const weeklyChartCtx = document.getElementById('weeklyRevenueChart').getContext('2d');
    const weeklyRevenueChart = new Chart(weeklyChartCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($weeklyChartLabels); ?>,
            datasets: [{
                label: 'Pendapatan Harian',
                data: <?php echo json_encode($weeklyChartData); ?>,
                backgroundColor: chartColors.secondaryLight,
                borderColor: chartColors.secondary,
                tension: 0.4,
                fill: true,
                borderWidth: 2,
                pointBackgroundColor: chartColors.secondary,
                pointRadius: 4
            }]
        },
        options: chartOptions
    });
    
    // Monthly Revenue Chart
    const monthlyChartCtx = document.getElementById('monthlyRevenueChart').getContext('2d');
    const monthlyRevenueChart = new Chart(monthlyChartCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($monthlyChartLabels); ?>,
            datasets: [{
                label: 'Pendapatan Bulanan',
                data: <?php echo json_encode($monthlyChartData); ?>,
                backgroundColor: chartColors.tertiaryLight,
                borderColor: chartColors.tertiary,
                tension: 0.4,
                fill: true,
                borderWidth: 2,
                pointBackgroundColor: chartColors.tertiary,
                pointRadius: 4
            }]
        },
        options: chartOptions
    });
});
</script>

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