<?php
header('Content-Type: application/json');
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$user_id = $auth->getCurrentUserId();
$user_data = $auth->getCurrentUser();
$functions = new Functions();

// Get POST data
$plan_id = isset($_POST['plan_id']) ? (int)$_POST['plan_id'] : 0;
$amount = isset($_POST['amount']) ? (float)$_POST['amount'] : 0;

// Validate input
if ($plan_id <= 0 || $amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid plan or amount']);
    exit();
}

// Get investment plan details
$stmt = $functions->db->prepare("SELECT * FROM investment_plans WHERE id = ? AND status = 'active'");
$stmt->execute([$plan_id]);
$plan = $stmt->fetch();

if (!$plan) {
    echo json_encode(['success' => false, 'message' => 'Investment plan not found']);
    exit();
}

// Validate amount range
if ($amount < $plan['min_amount'] || $amount > $plan['max_amount']) {
    echo json_encode(['success' => false, 'message' => 'Amount must be between $' . number_format($plan['min_amount']) . ' and $' . number_format($plan['max_amount'])]);
    exit();
}

// Check if user has sufficient balance
if ($user_data['balance'] < $amount) {
    echo json_encode(['success' => false, 'message' => 'Insufficient balance']);
    exit();
}

// Calculate investment details
$daily_profit = ($amount * $plan['daily_return']) / 100;
$end_date = date('Y-m-d H:i:s', strtotime('+' . $plan['duration_days'] . ' days'));

try {
    $functions->db->beginTransaction();

    // Deduct amount from user balance
    $functions->updateUserBalance($user_id, -$amount);

    // Create investment record
    $stmt = $functions->db->prepare("
        INSERT INTO investments (user_id, plan_id, amount, daily_profit, end_date)
        VALUES (?, ?, ?, ?, ?)
    ");
    $stmt->execute([$user_id, $plan_id, $amount, $daily_profit, $end_date]);
    $investment_id = $functions->db->lastInsertId();

    // Create transaction record
    $functions->createTransaction([
        'user_id' => $user_id,
        'type' => 'investment',
        'amount' => $amount,
        'method' => 'balance',
        'description' => 'Investment in ' . $plan['name'],
        'status' => 'completed',
        'details' => ['plan_id' => $plan_id, 'investment_id' => $investment_id]
    ]);

    // Log activity
    $functions->logActivity($user_id, 'investment_created', 'Created investment #' . $investment_id . ' for $' . number_format($amount));

    $functions->db->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Investment created successfully',
        'data' => [
            'investment_id' => $investment_id,
            'amount' => number_format($amount, 2),
            'daily_profit' => number_format($daily_profit, 2),
            'end_date' => $end_date
        ]
    ]);

} catch (Exception $e) {
    $functions->db->rollBack();
    error_log("Investment creation error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Failed to create investment. Please try again.']);
}
?>
