<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'auth_guard.php';
require_once '../config/database.php';
$db = getDB();

// 1. Calculate Gross Revenue Metrics from Delivered Orders (Case-insensitive check)
$deliveredQuery = $db->query("SELECT COUNT(id) as total_count, SUM(total) as gross_sales FROM orders WHERE LOWER(status) = 'delivered'");
$deliveredData = $deliveredQuery->fetch_assoc();
$deliveredCount = intval($deliveredData['total_count'] ?? 0);
$deliveredSales = floatval($deliveredData['gross_sales'] ?? 0.0);

// 2. Calculate Financial Impact of Cancelled and Failed Orders
$lostQuery = $db->query("SELECT SUM(total) as lost_sales FROM orders WHERE LOWER(status) IN ('cancelled', 'failed')");
$lostSales = floatval($lostQuery->fetch_assoc()['lost_sales'] ?? 0.0);

// 3. Fetch Status Distribution Summary Map
$statusQuery = $db->query("SELECT status, COUNT(id) as status_count FROM orders GROUP BY status");
$chartDistribution = [];
while ($row = $statusQuery->fetch_assoc()) {
    // Normalizes index keys to match whatever case is stored
    $chartDistribution[$row['status']] = intval($row['status_count']);
}

echo json_encode([
    "success" => true,
    "analytics" => [
        "delivered_orders_count" => $deliveredCount,
        "gross_revenue" => $deliveredSales,
        "cancelled_revenue_lost" => $lostSales,
        "status_distribution" => $chartDistribution
    ]
]);