<?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);

try {
    $db->beginTransaction();

    // Get available profit
    $stmt = $db->prepare("SELECT profit_balance FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $profit_balance = (float)$stmt->fetchColumn();

    if ($profit_balance <= 0) {
        throw new Exception('No profits available to reinvest');
    }

    if ($investment_id > 0) {
        // Add to specific 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');
        }

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

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

        $description = "Reinvested profits into investment #$investment_id";
    } else {
        // Just move to balance (user can create new investment manually)
        $functions->updateUserBalance($user_id, $profit_balance, 'add');
        $description = "Profits moved to balance for reinvestment";
    }

    // Reset profit balance
    $db->prepare("UPDATE users SET profit_balance = 0 WHERE id = ?")->execute([$user_id]);

    // Log transaction
    $functions->createTransaction([
        'user_id' => $user_id,
        'type' => 'investment', // or 'transfer'
        'amount' => $profit_balance,
        'description' => $description,
        'status' => 'completed'
    ]);

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