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

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

$user_id = $auth->getCurrentUserId();
$functions = new InvestmentFunctions();
$db = Database::getInstance()->getConnection();

$investment_id = (int)($_POST['investment_id'] ?? 0);
$amount = (float)($_POST['amount'] ?? 0);

if (!$investment_id || $amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit();
}

try {
    $db->beginTransaction();

    // Get investment
    $stmt = $db->prepare("SELECT * FROM investments WHERE id = ? AND user_id = ? AND status = 'running'");
    $stmt->execute([$investment_id, $user_id]);
    $investment = $stmt->fetch();

    if (!$investment) {
        throw new Exception('Investment not found or not active');
    }

    // Check balance
    $user_balance = $functions->getUserBalance($user_id);
    if ($user_balance < $amount) {
        throw new Exception('Insufficient balance');
    }

    // Get plan details to recalculate daily profit
    $plan = $functions->getPlanById($investment['plan_id']);
    $new_amount = $investment['amount'] + $amount;
    $new_daily_profit = ($new_amount * $plan['daily_return']) / 100;

    // Deduct balance
    $functions->updateUserBalance($user_id, $amount, 'subtract');

    // Update investment
    $update_stmt = $db->prepare("UPDATE investments SET amount = ?, daily_profit = ? WHERE id = ?");
    $update_stmt->execute([$new_amount, $new_daily_profit, $investment_id]);

    // Log transaction
    $functions->createTransaction([
        'user_id' => $user_id,
        'type' => 'investment',
        'amount' => $amount,
        'description' => "Added funds to investment #$investment_id",
        'status' => 'completed'
    ]);

    $db->commit();
    echo json_encode(['success' => true, 'message' => 'Funds added successfully']);
} catch (Exception $e) {
    $db->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>