<?php
header('Content-Type: application/json');
// Critical: Add cache control headers
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// CRITICAL: Allow origin with credentials
$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Define TONSUI_LOADED constant to prevent direct access to session_init.php
define('TONSUI_LOADED', true);

// Include centralized session initialization
require_once __DIR__ . '/session_init.php';

// Require admin authentication since this lists ALL investments
requireAdmin(true);

require_once 'db.php';

try {
    // CRITICAL FIX: Add roi_percentage and alias fields for Analytics component
    // Frontend expects: plan_name, roi_percent, amount_invested, total_roi_earned
    $stmt = $pdo->query("
        SELECT 
            i.*,
            p.name as plan_name,
            p.roi_percentage as roi_percent,
            p.duration_days,
            u.username,
            i.amount as amount_invested,
            i.roi as total_roi_earned
        FROM investments i 
        LEFT JOIN investment_plans p ON i.plan_id = p.id 
        LEFT JOIN users u ON i.user_id = u.id 
        ORDER BY i.created_at DESC LIMIT 100
    ");
    $investments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['success' => true, 'investments' => $investments]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
