<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "Step 1: Starting<br>";

try {
    require_once __DIR__ . '/../../includes/config.php';
    echo "Step 2: Config loaded<br>";
    
    // Simular sessão de super admin
    $_SESSION['is_super_admin'] = true;
    $_SESSION['super_admin_id'] = 1;
    
    echo "Step 3: Session set<br>";
    echo "isSuperAdmin: " . (isSuperAdmin() ? 'true' : 'false') . "<br>";
    
    $pdo = getDB();
    echo "Step 4: DB connected<br>";
    
    $totalStores = $pdo->query("SELECT COUNT(*) FROM stores WHERE deleted_at IS NULL")->fetchColumn();
    echo "Step 5: Total stores: $totalStores<br>";
    
    $activeStores = $pdo->query("SELECT COUNT(*) FROM stores WHERE status = 'active' AND deleted_at IS NULL")->fetchColumn();
    echo "Step 6: Active stores: $activeStores<br>";
    
    $mrrResult = $pdo->query("
        SELECT COALESCE(SUM(p.price_monthly), 0) as mrr
        FROM subscriptions s
        JOIN plans p ON s.plan_id = p.id
        WHERE s.status = 'active'
    ")->fetch();
    echo "Step 7: MRR query OK<br>";
    
    $ordersThisMonth = $pdo->query("SELECT COUNT(*) FROM orders WHERE MONTH(created_at) = MONTH(CURRENT_DATE())")->fetchColumn();
    echo "Step 8: Orders query OK<br>";
    
    $recentStores = $pdo->query("
        SELECT s.*,
               (SELECT COUNT(*) FROM orders o WHERE o.store_id = s.id) as orders_count,
               (SELECT COALESCE(SUM(total_amount), 0) FROM orders o WHERE o.store_id = s.id) as total_revenue
        FROM stores s
        WHERE s.deleted_at IS NULL
        ORDER BY s.created_at DESC
        LIMIT 10
    ")->fetchAll();
    echo "Step 9: Recent stores query OK - Count: " . count($recentStores) . "<br>";
    
    echo "<br><strong>All queries passed! The issue might be in the HTML/template part.</strong>";
    
} catch (Exception $e) {
    echo "<br><strong>ERROR:</strong> " . $e->getMessage() . "<br>";
    echo "File: " . $e->getFile() . "<br>";
    echo "Line: " . $e->getLine() . "<br>";
}
