<?php
/**
 * Dashboard Statistics API
 */
require_once 'guard.php';
require_once __DIR__ . '/../includes/database.php';

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

try {
    $db = Database::getInstance();
    $conn = $db->getConnection();
    
    $stats = [];
    $unit_id = $_SESSION['unit_id'];
    $user_id = $_SESSION['user_id'];
    
    // Get counts with proper user isolation
    if ($_SESSION['user_role'] === 'superuser') {
        // Superuser sees all data
        $stats['ingredients'] = $conn->query("SELECT COUNT(*) FROM ingredients")->fetchColumn();
        $stats['recipes'] = $conn->query("SELECT COUNT(*) FROM recipes")->fetchColumn();
        $stats['meals'] = $conn->query("SELECT COUNT(*) FROM meals")->fetchColumn();
        $stats['users'] = $conn->query("SELECT COUNT(*) FROM users WHERE status = 'active'")->fetchColumn();
    } else {
        // Regular users see only their data and unit-wide ingredients
        $stats['ingredients'] = $conn->query("
            SELECT COUNT(*) FROM ingredients i 
            JOIN users u ON i.user_id = u.id 
            WHERE u.unit_id = $unit_id
        ")->fetchColumn();
        
        $stats['recipes'] = $conn->query("
            SELECT COUNT(*) FROM recipes WHERE created_by = $user_id
        ")->fetchColumn();
        
        $stats['meals'] = $conn->query("
            SELECT COUNT(*) FROM meals WHERE created_by = $user_id
        ")->fetchColumn();
        
        $stats['users'] = $conn->query("
            SELECT COUNT(*) FROM users WHERE unit_id = $unit_id AND status = 'active'
        ")->fetchColumn();
    }
    
    // Get recent activity
    $stmt = $conn->prepare("
        SELECT al.*, u.full_name as creator_name 
        FROM activity_log al 
        LEFT JOIN users u ON al.created_by = u.id 
        WHERE al.unit_id = ? 
        ORDER BY al.created_at DESC 
        LIMIT 10
    ");
    $stmt->execute([$unit_id]);
    $recent_activity = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'counts' => $stats,
        'recent' => $recent_activity,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    error_log("Stats API error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load statistics',
        'counts' => ['ingredients' => 0, 'recipes' => 0, 'meals' => 0, 'users' => 0],
        'recent' => []
    ]);
}
?>