<?php
session_start();

// Only allow authenticated admin users
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Get database connection
require_once '../config/db.php';

header('Content-Type: application/json');

// Use $connection from config/db.php
$conn = $connection;

if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

// Get dashboard statistics
$stats_query = $conn->query("
    SELECT 
        COUNT(*) as total_orders,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
        SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as delivered_orders,
        0 as total_revenue
    FROM orders
");
$stats = $stats_query ? $stats_query->fetch_assoc() : ['total_orders' => 0, 'pending_orders' => 0, 'delivered_orders' => 0, 'total_revenue' => 0];

// Get recent users
$users_query = "
    SELECT id, email, phone, created_at
    FROM users
    ORDER BY created_at DESC
    LIMIT 10
";
$users_result = $conn->query($users_query);
$users = [];
if ($users_result) {
    while ($user = $users_result->fetch_assoc()) {
        $users[] = $user;
    }
}

// Get recent orders
$orders_query = "
    SELECT o.id, o.user_id, o.status, o.total, o.created_at, u.name as customer_name, u.email as customer_email
    FROM orders o
    LEFT JOIN users u ON o.user_id = u.id
    ORDER BY o.created_at DESC
    LIMIT 10
";
$orders_result = $conn->query($orders_query);
$orders = [];
if ($orders_result) {
    while ($order = $orders_result->fetch_assoc()) {
        $orders[] = $order;
    }
}

// Get recent consultations
$consultations_query = "
    SELECT id, first_name, last_name, email, phone, consultation_type, preferred_date, status, created_at
    FROM consultations
    ORDER BY created_at DESC
    LIMIT 10
";
$consultations_result = $conn->query($consultations_query);
$consultations = [];
if ($consultations_result) {
    while ($consultation = $consultations_result->fetch_assoc()) {
        $consultations[] = $consultation;
    }
}

// Get counts
$users_count = $conn->query("SELECT COUNT(*) as count FROM users")->fetch_assoc()['count'];
$orders_count = $conn->query("SELECT COUNT(*) as count FROM orders")->fetch_assoc()['count'];
$consultations_count = $conn->query("SELECT COUNT(*) as count FROM consultations")->fetch_assoc()['count'];

echo json_encode([
    'success' => true,
    'stats' => $stats,
    'users' => $users,
    'orders' => $orders,
    'consultations' => $consultations,
    'counts' => [
        'users' => $users_count,
        'orders' => $orders_count,
        'consultations' => $consultations_count
    ],
    'timestamp' => date('Y-m-d H:i:s')
]);

$conn->close();
?>
