<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';
include '../auth.php';

// Check authentication first
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Aggressive caching headers for performance
header('Content-Type: application/json');
header('Cache-Control: public, max-age=30, stale-while-revalidate=60'); // Cache for 30 seconds, serve stale for 60s while revalidating
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 30) . ' GMT');

try {
    // Use a single multi-query for better performance
    $multi_query = "
        SELECT 
            (SELECT COALESCE(amount, 0) FROM opening_cash WHERE cash_date = CURDATE() LIMIT 1) as opening_cash,
            (SELECT COALESCE(SUM(total_amount), 0) FROM sales WHERE DATE(sale_date) = CURDATE()) as today_sales,
            (SELECT COUNT(*) FROM products) as total_products,
            (SELECT COUNT(*) FROM products WHERE stock <= COALESCE(min_stock, 5)) as low_stock,
            (SELECT COUNT(*) FROM customers) as total_customers,
            (SELECT COUNT(*) FROM categories) as total_categories,
            (SELECT COUNT(*) FROM users WHERE is_active = 1) as active_users,
            (SELECT COUNT(*) FROM sales WHERE sale_date >= DATE_SUB(NOW(), INTERVAL 1 HOUR)) as recent_sales
    ";
    
    $result = $conn->query($multi_query);
    if (!$result) {
        throw new Exception('Database query failed: ' . $conn->error);
    }
    
    $stats = $result->fetch_assoc();
    $opening_cash = floatval($stats['opening_cash'] ?? 0);
    $today_sales = floatval($stats['today_sales'] ?? 0);
    $total_products = intval($stats['total_products'] ?? 0);
    $low_stock = intval($stats['low_stock'] ?? 0);
    $total_customers = intval($stats['total_customers'] ?? 0);
    $total_categories = intval($stats['total_categories'] ?? 0);
    $active_users = intval($stats['active_users'] ?? 0);
    $recent_sales = intval($stats['recent_sales'] ?? 0);
    
    echo json_encode([
        'todaySales' => 'Rs ' . number_format($today_sales, 2),
        'totalProducts' => $total_products,
        'lowStock' => $low_stock,
        'totalCustomers' => $total_customers,
        'totalSuppliers' => $total_categories,
        'activeUsers' => $active_users,
        'recentSales' => $recent_sales,
        'openingCash' => $opening_cash,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to fetch dashboard statistics',
        'message' => $e->getMessage()
    ]);
    error_log('Enhanced stats API error: ' . $e->getMessage());
}
?>
