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

try {
    $db->beginTransaction();

    // Get user data
    $stmt = $db->prepare("SELECT profit_balance FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch();

    $amount = $user['profit_balance'];

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

    // Update balances
    // Deduct from profit_balance
    $stmt = $db->prepare("UPDATE users SET profit_balance = 0 WHERE id = ?");
    $stmt->execute([$user_id]);

    // Add to main balance
    $functions->updateUserBalance($user_id, $amount, 'add');

    // Log transaction
    $functions->createTransaction([
        'user_id' => $user_id,
        'type' => 'credit',
        'amount' => $amount,
        'method' => 'system',
        'description' => "Profit withdrawal to main balance",
        'status' => 'completed'
    ]);

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