<?php
/**
 * Get Investment Plans Endpoint
 * 
 * Returns a list of available investment plans
 * 
 * Required Headers:
 * - Content-Type: application/json
 * 
 * Response:
 * - success: boolean
 * - plans: array of investment plan objects
 * - message: string (optional, for errors)
 */

// Include configuration and authentication
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/includes/Database.php';

// Set content type to JSON
header('Content-Type: application/json');

// Initialize response array
$response = [
    'success' => false,
    'plans' => [],
    'message' => ''
];

try {
    // Verify admin authentication
    $auth = new Auth();
    if (!$auth->isLoggedIn() || !$auth->isAdmin()) {
        http_response_code(403);
        $response['message'] = 'Unauthorized: Admin access required';
        echo json_encode($response);
        exit;
    }
    
    // Get database connection
    $db = Database::getInstance()->getConnection();
    
    // Query to get active investment plans
    $stmt = $db->query("SELECT * FROM investment_plans WHERE status = 'active' ORDER BY min_amount ASC");
    $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // If no plans found, create a default one
    if (empty($plans)) {
        createDefaultPlan($db);
        $stmt = $db->query("SELECT * FROM investment_plans WHERE status = 'active'");
        $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    // Format plan data
    foreach ($plans as &$plan) {
        $plan['id'] = (int)$plan['id'];
        $plan['min_amount'] = (float)$plan['min_amount'];
        $plan['max_amount'] = (float)$plan['max_amount'];
        $plan['roi_percentage'] = (float)$plan['roi_percentage'];
        $plan['duration_days'] = (int)$plan['duration_days'];
        $plan['created_at'] = $plan['created_at'];
    }
    
    $response['success'] = true;
    $response['plans'] = $plans;
    
} catch (PDOException $e) {
    http_response_code(500);
    $response['message'] = 'Database error: ' . $e->getMessage();
    
} catch (Exception $e) {
    http_response_code(500);
    $response['message'] = 'Server error: ' . $e->getMessage();
}

// Return JSON response
echo json_encode($response);

/**
 * Create a default investment plan if none exists
 */
function createDefaultPlan($db) {
    $defaultPlan = [
        'name' => 'Starter Plan',
        'description' => 'Perfect for beginners',
        'min_amount' => 100.00,
        'max_amount' => 1000.00,
        'roi_percentage' => 10.5,
        'duration_days' => 30,
        'status' => 'active',
        'created_at' => date('Y-m-d H:i:s')
    ];
    
    $stmt = $db->prepare("INSERT INTO investment_plans 
        (name, description, min_amount, max_amount, roi_percentage, duration_days, status, created_at)
        VALUES (:name, :description, :min_amount, :max_amount, :roi_percentage, :duration_days, :status, :created_at)");
    
    return $stmt->execute($defaultPlan);
}

/**
 * Get database connection
 */
// Database connection now handled by Database singleton
