<?php
/**
 * admin_adjust_investment_roi.php
 * Admin endpoint to manually adjust investment ROI
 */

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

$allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: $allowed_origin");
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
requireAdmin(true);
require_once 'db.php';

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

$json_data = file_get_contents('php://input');
$data = json_decode($json_data, true);

if (!$data || !isset($data['investment_id']) || !isset($data['roi_amount'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$investment_id = intval($data['investment_id']);
$roi_amount = floatval($data['roi_amount']);
$note = isset($data['note']) ? htmlspecialchars(trim($data['note']), ENT_QUOTES, 'UTF-8') : 'Admin ROI adjustment';

if ($roi_amount < 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'ROI amount cannot be negative']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    // Get investment details
    $stmt = $pdo->prepare("
        SELECT i.*, u.username, u.email 
        FROM investments i 
        JOIN users u ON i.user_id = u.id 
        WHERE i.id = ?
    ");
    $stmt->execute([$investment_id]);
    $investment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$investment) {
        throw new Exception('Investment not found');
    }
    
    $old_roi = floatval($investment['roi']);
    $roi_diff = $roi_amount - $old_roi;
    
    // Update investment ROI
    $updateStmt = $pdo->prepare("
        UPDATE investments 
        SET roi = ?, 
            total_return = amount + ?,
            updated_at = NOW() 
        WHERE id = ?
    ");
    $updateStmt->execute([$roi_amount, $roi_amount, $investment_id]);
    
    // Log the adjustment
    $logStmt = $pdo->prepare("
        INSERT INTO admin_logs 
        (admin_id, action, target_type, target_id, details, created_at) 
        VALUES (?, 'adjust_investment_roi', 'investment', ?, ?, NOW())
    ");
    
    $log_details = json_encode([
        'investment_id' => $investment_id,
        'user_id' => $investment['user_id'],
        'username' => $investment['username'],
        'old_roi' => $old_roi,
        'new_roi' => $roi_amount,
        'difference' => $roi_diff,
        'note' => $note
    ]);
    
    $admin_id = isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 1;
    $logStmt->execute([$admin_id, $investment_id, $log_details]);
    
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Investment ROI updated successfully',
        'investment_id' => $investment_id,
        'old_roi' => $old_roi,
        'new_roi' => $roi_amount,
        'difference' => $roi_diff
    ]);
    
} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log('Database error adjusting investment ROI: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Database error adjusting investment ROI'
    ]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(400);
    echo json_encode([
        'success' => false, 
        'message' => $e->getMessage()
    ]);
}
?>
