<?php
// --- START: Added for detailed error reporting ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// --- END: Added for detailed error reporting ---

// FIX 1: Corrected the file paths by changing ../ to ../../
require_once '../../config/cors.php';
require_once '../../config/database.php';
require_once '../../middleware/auth.php';
require_once '../../utils/jwt.php';

// --- AUTHENTICATION DISABLED FOR TESTING ---
/*
// ... (authentication code remains commented out)
*/
// --- END OF DISABLED CODE ---


// FIX 2: Add database connection and convert to PDO
$database = new Database();
$db = $database->getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        // Get total users
        $userStmt = $db->prepare("SELECT COUNT(*) as total FROM users");
        $userStmt->execute();
        $totalUsers = $userStmt->fetch(PDO::FETCH_ASSOC)['total'];

        // Get total orders and revenue
        $orderStmt = $db->prepare("SELECT COUNT(*) as total_orders, SUM(total_price) as total_revenue FROM orders");
        $orderStmt->execute();
        $orderResult = $orderStmt->fetch(PDO::FETCH_ASSOC);
        $totalOrders = $orderResult['total_orders'];
        $totalRevenue = $orderResult['total_revenue'];

        // Get total products
        $productStmt = $db->prepare("SELECT COUNT(*) as total FROM products");
        $productStmt->execute();
        $totalProducts = $productStmt->fetch(PDO::FETCH_ASSOC)['total'];

        // Get new notifications count
        $notificationStmt = $db->prepare("SELECT COUNT(*) as total FROM notifications WHERE read_status = 0");
        $notificationStmt->execute();
        $newNotifications = $notificationStmt->fetch(PDO::FETCH_ASSOC)['total'];

        // Get recent orders
        $recentOrdersStmt = $db->prepare("
            SELECT o.id, o.total_price, o.status, u.name as user_name 
            FROM orders o 
            JOIN users u ON o.user_id = u.id 
            ORDER BY o.created_at DESC 
            LIMIT 5
        ");
        $recentOrdersStmt->execute();
        $recentOrders = $recentOrdersStmt->fetchAll(PDO::FETCH_ASSOC);

        // Get revenue by month (last 6 months)
        $revenueStmt = $db->prepare("
            SELECT 
                DATE_FORMAT(created_at, '%Y-%m') as month,
                SUM(total_price) as revenue 
            FROM orders 
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
            GROUP BY month 
            ORDER BY month ASC
        ");
        $revenueStmt->execute();
        $revenueByMonth = $revenueStmt->fetchAll(PDO::FETCH_ASSOC);

        // Get top selling products
        $topProductsStmt = $db->prepare("
            SELECT 
                p.name,
                COUNT(oi.id) as order_count,
                SUM(oi.quantity) as total_quantity
            FROM products p 
            JOIN order_items oi ON p.id = oi.product_id
            GROUP BY p.id
            ORDER BY order_count DESC
            LIMIT 5
        ");
        $topProductsStmt->execute();
        $topProducts = $topProductsStmt->fetchAll(PDO::FETCH_ASSOC);

        // Get recent activities for the dashboard
        $activitiesStmt = $db->prepare("
            (SELECT 
                'new_order' as type,
                o.id,
                u.name as user_name,
                u.name as customer_name,
                o.total_price as amount,
                o.created_at,
                o.created_at as timestamp,
                CONCAT('New order #', o.id, ' placed by ', u.name) as message
            FROM orders o 
            JOIN users u ON o.user_id = u.id 
            ORDER BY o.created_at DESC 
            LIMIT 8)
            UNION ALL
            (SELECT 
                'new_user' as type,
                u.id,
                u.name as user_name,
                u.name as customer_name,
                NULL as amount,
                u.created_at,
                u.created_at as timestamp,
                CONCAT('New user ', u.name, ' registered') as message
            FROM users u 
            ORDER BY u.created_at DESC 
            LIMIT 4)
            ORDER BY created_at DESC
            LIMIT 10
        ");
        $activitiesStmt->execute();
        $activities = $activitiesStmt->fetchAll(PDO::FETCH_ASSOC);

        // Prepare and send response
        $response = [
            'success' => true,
            'stats' => [
                'totalUsers' => (int)$totalUsers,
                'totalOrders' => (int)$totalOrders,
                'totalRevenue' => (float)$totalRevenue,
                'totalProducts' => (int)$totalProducts,
                'newNotifications' => (int)$newNotifications
            ],
            'recentOrders' => $recentOrders,
            'revenueByMonth' => $revenueByMonth,
            'topProducts' => $topProducts,
            'activities' => $activities
        ];

        http_response_code(200);
        header('Content-Type: application/json');
        echo json_encode($response);

    } catch (PDOException $e) {
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Database Query Failed: ' . $e->getMessage()]);
    }
} else {
    http_response_code(405);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Method not allowed']);
}
?>