<?php
// Include database configuration
require_once '../config/db_config.php';
require_once '../models/Product.php';

// Check if user is logged in and is admin
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

$db = getDbConnection();

// Check if database connection is available
if ($db === null) {
    die("Koneksi database gagal. Silakan coba lagi nanti atau hubungi administrator.");
}

// Get statistics
try {
    // Total orders
    $stmt = $db->query("SELECT COUNT(*) as total FROM orders");
    $total_orders = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Total revenue
    $stmt = $db->query("SELECT SUM(total_amount) as total FROM orders WHERE status = 'paid'");
    $total_revenue = $stmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0;
    
    // Pending payment proofs
    $stmt = $db->query("SELECT COUNT(*) as total FROM payment_proofs WHERE status = 'pending'");
    $pending_proofs = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Recent orders
    $stmt = $db->query("
        SELECT o.*, COUNT(oi.item_id) as total_items 
        FROM orders o 
        LEFT JOIN order_items oi ON o.order_id = oi.order_id 
        GROUP BY o.order_id 
        ORDER BY o.created_at DESC 
        LIMIT 5
    ");
    $recent_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Admin dashboard database error: " . $e->getMessage());
    $error_message = "Terjadi kesalahan sistem. Silakan coba lagi nanti.";
    $total_orders = 0;
    $total_revenue = 0;
    $pending_proofs = 0;
    $recent_orders = [];
}

// Get products from database
try {
    $product = new Product();
    $products = $product->getAllProducts();
} catch (Exception $e) {
    error_log("Admin dashboard product error: " . $e->getMessage());
    $products = [];
    $error_message = "Error loading products: " . $e->getMessage();
}
// Report filter: purchases per user by date & time
// Defaults: today 00:00:00 to today 23:59:59
$today_date = date('Y-m-d');
$default_start_date = $_GET['start_date'] ?? $today_date;
$default_end_date = $_GET['end_date'] ?? $today_date;
$default_start_time = $_GET['start_time'] ?? '00:00';
$default_end_time = $_GET['end_time'] ?? '23:59';
$user_keyword = isset($_GET['user']) ? trim($_GET['user']) : '';
$status_filter = isset($_GET['status']) ? trim($_GET['status']) : '';

$start_datetime = date('Y-m-d H:i:s', strtotime($default_start_date . ' ' . $default_start_time));
$end_datetime = date('Y-m-d H:i:s', strtotime($default_end_date . ' ' . $default_end_time));

// Fetch report rows
$report_rows = [];
try {
    $sql = "
        SELECT 
            o.order_id,
            o.order_code,
            COALESCE(u.name, o.name) AS customer_name,
            o.email,
            o.total_amount,
            o.status,
            o.created_at,
            COUNT(oi.item_id) AS total_items
        FROM orders o
        LEFT JOIN users u ON u.user_id = o.user_id
        LEFT JOIN order_items oi ON oi.order_id = o.order_id
        WHERE o.created_at BETWEEN :start_dt AND :end_dt
    ";

    $params = [
        ':start_dt' => $start_datetime,
        ':end_dt' => $end_datetime,
    ];

    if ($user_keyword !== '') {
        $sql .= " AND (u.username LIKE :kw OR u.name LIKE :kw OR o.name LIKE :kw OR o.email LIKE :kw)";
        $params[':kw'] = '%' . $user_keyword . '%';
    }

    if ($status_filter !== '') {
        $sql .= " AND o.status = :status";
        $params[':status'] = $status_filter;
    }

    $sql .= "
        GROUP BY o.order_id
        ORDER BY o.created_at DESC
        LIMIT 500
    ";

    $stmt = $db->prepare($sql);
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }
    $stmt->execute();
    $report_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log('Admin dashboard report query error: ' . $e->getMessage());
    $report_rows = [];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Baso Alam</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #343a40;
            padding-top: 20px;
        }
        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 10px 20px;
            display: block;
        }
        .sidebar a:hover {
            background-color: #495057;
        }
        .sidebar a.active {
            background-color: #0d6efd;
        }
        .stat-card {
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .stat-card i {
            font-size: 2rem;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-2 p-0">
                <?php include 'admin_sidebar.php'; ?>
            </div>
            <div class="col-lg-10 p-4">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>Dashboard</h2>
                    <div>
                        <span class="me-3">Welcome<?php echo isset($_SESSION['name']) && $_SESSION['name'] ? ', ' . htmlspecialchars($_SESSION['name']) : ''; ?></span>
                    </div>
                </div>

                <!-- Statistics Cards -->
                <div class="row">
                    <div class="col-md-4">
                        <div class="stat-card bg-primary text-white">
                            <i class="fas fa-shopping-cart"></i>
                            <h3><?php echo number_format($total_orders); ?></h3>
                            <p class="mb-0">Total Pesanan</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="stat-card bg-success text-white">
                            <i class="fas fa-money-bill-wave"></i>
                            <h3>Rp <?php echo number_format($total_revenue, 0, ',', '.'); ?></h3>
                            <p class="mb-0">Total Pendapatan</p>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="stat-card bg-warning text-dark">
                            <i class="fas fa-clock"></i>
                            <h3><?php echo number_format($pending_proofs); ?></h3>
                            <p class="mb-0">Bukti Pembayaran Pending</p>
                        </div>
                    </div>
                </div>

             
                <!-- Laporan Pembelian per User (berdasarkan tanggal & jam) -->
                <div class="card mt-4">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="card-title mb-0">Laporan Pembelian</h5>
                        </div>

                        <form method="get" class="row g-3 align-items-end">
                            <div class="col-md-3">
                                <label for="start_date" class="form-label">Tanggal Mulai</label>
                                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo htmlspecialchars($default_start_date); ?>">
                            </div>
                            <div class="col-md-2">
                                <label for="start_time" class="form-label">Jam Mulai</label>
                                <input type="time" class="form-control" id="start_time" name="start_time" value="<?php echo htmlspecialchars($default_start_time); ?>">
                            </div>
                            <div class="col-md-3">
                                <label for="end_date" class="form-label">Tanggal Selesai</label>
                                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo htmlspecialchars($default_end_date); ?>">
                            </div>
                            <div class="col-md-2">
                                <label for="end_time" class="form-label">Jam Selesai</label>
                                <input type="time" class="form-control" id="end_time" name="end_time" value="<?php echo htmlspecialchars($default_end_time); ?>">
                            </div>
                            <div class="col-md-4">
                                <label for="user" class="form-label">User / Email / Nama</label>
                                <input type="text" class="form-control" id="user" name="user" placeholder="Cari user" value="<?php echo htmlspecialchars($user_keyword); ?>">
                            </div>
                            <div class="col-md-3">
                                <label for="status" class="form-label">Status Pesanan</label>
                                <select id="status" name="status" class="form-select">
                                    <option value="">Semua</option>
                                    <?php
                                    $statuses = ['pending','paid','processing','shipped','delivered','cancelled'];
                                    foreach ($statuses as $st) {
                                        $sel = ($status_filter === $st) ? 'selected' : '';
                                        echo '<option value="' . htmlspecialchars($st) . '" ' . $sel . '>' . htmlspecialchars(ucfirst($st)) . '</option>';
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-primary w-100"><i class="fas fa-filter me-1"></i> Filter</button>
                            </div>
                            <div class="col-md-2">
                                <a href="dashboard.php" class="btn btn-secondary w-100">Reset</a>
                            </div>
                        </form>

                        <div class="table-responsive mt-4">
                            <table class="table table-striped table-bordered align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th>Kode Pesanan</th>
                                        <th>Waktu</th>
                                        <th>User / Nama</th>
                                        <th>Email</th>
                                        <th>Item</th>
                                        <th>Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($report_rows)): ?>
                                        <?php foreach ($report_rows as $row): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($row['order_code']); ?></td>
                                                <td><?php echo htmlspecialchars(date('Y-m-d H:i', strtotime($row['created_at']))); ?></td>
                                                <td><?php echo htmlspecialchars($row['customer_name'] ?? '-'); ?></td>
                                                <td><?php echo htmlspecialchars($row['email']); ?></td>
                                                <td><?php echo number_format((int)$row['total_items']); ?></td>
                                                <td>Rp <?php echo number_format($row['total_amount'], 0, ',', '.'); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="6" class="text-center text-muted">Tidak ada data untuk rentang waktu yang dipilih.</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html> 