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

if (!$investment_id) {
    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');
    }

    // Return principal to balance
    $functions->updateUserBalance($user_id, $investment['amount'], 'add');

    // Update investment status
    $update_stmt = $db->prepare("UPDATE investments SET status = 'cancelled', end_date = NOW() WHERE id = ?");
    $update_stmt->execute([$investment_id]);

    // Log transaction
    $functions->createTransaction([
        'user_id' => $user_id,
        'type' => 'credit',
        'amount' => $investment['amount'],
        'description' => "Principal return from cancelled investment #$investment_id",
        'status' => 'completed'
    ]);

    $db->commit();
    echo json_encode(['success' => true, 'message' => 'Investment cancelled and principal returned']);
} catch (Exception $e) {
    $db->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>