<?php
// process_investment_ajax.php - Simplified version for testing
session_start();
require_once '../connection.php';

header('Content-Type: application/json');

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log all requests
error_log("AJAX request received: " . json_encode($_REQUEST));

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit();
}

$user_id = $_SESSION['user_id'];

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'process_profits':
        processProfits($conn, $user_id);
        break;
        
    case 'get_updates':
        getUpdates($conn, $user_id);
        break;
        
    default:
        echo json_encode(['success' => false, 'error' => 'Invalid action']);
}

function processProfits($conn, $user_id) {
    error_log("Processing profits for user: $user_id");
    
    // Check if user has active investments
    $check = $conn->prepare("SELECT COUNT(*) as count FROM user_investments WHERE user_id = ? AND status = 'active'");
    $check->bind_param("i", $user_id);
    $check->execute();
    $result = $check->get_result();
    $count = $result->fetch_assoc()['count'];
    
    if ($count == 0) {
        echo json_encode(['success' => true, 'processed' => 0, 'total_profit' => 0, 'message' => 'No active investments']);
        return;
    }
    
    $conn->begin_transaction();
    
    try {
        // Get active investments
        $query = "
            SELECT ui.*, ip.interest_rate, ip.duration_days 
            FROM user_investments ui
            JOIN investment_plans ip ON ui.plan_id = ip.id
            WHERE ui.user_id = ? AND ui.status = 'active'
            FOR UPDATE
        ";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $processed = 0;
        $total_profit = 0;
        
        while ($inv = $result->fetch_assoc()) {
            // Calculate profit for this minute
            $amount = floatval($inv['amount']);
            $interest_rate = floatval($inv['interest_rate']);
            $duration_days = intval($inv['duration_days']);
            
            // Total profit for entire duration
            $total_profit_amount = $amount * ($interest_rate / 100);
            
            // Profit per minute (simplified calculation)
            $total_minutes = $duration_days * 24 * 60;
            $profit_per_minute = $total_profit_amount / $total_minutes;
            
            // Ensure we don't exceed expected return
            $actual_return = floatval($inv['actual_return'] ?? 0);
            $expected_return = floatval($inv['expected_return']);
            $remaining_profit = $expected_return - $amount - $actual_return;
            
            $profit_to_add = min($profit_per_minute, max(0, $remaining_profit));
            
            if ($profit_to_add > 0.0001) { // Only process if profit is meaningful
                // Update user balance
                $update_user = $conn->prepare("
                    UPDATE users SET 
                    account_balance = account_balance + ?,
                    total_earnings = total_earnings + ?,
                    updated_at = NOW()
                    WHERE id = ?
                ");
                $update_user->bind_param("ddi", $profit_to_add, $profit_to_add, $user_id);
                $update_user->execute();
                
                // Update investment
                $update_inv = $conn->prepare("
                    UPDATE user_investments 
                    SET actual_return = actual_return + ?,
                        total_interest_paid = total_interest_paid + ?,
                        last_interest_calc = NOW(),
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $update_inv->bind_param("ddi", $profit_to_add, $profit_to_add, $inv['id']);
                $update_inv->execute();
                
                $processed++;
                $total_profit += $profit_to_add;
                
                error_log("Added $profit_to_add to investment ID: {$inv['id']}");
            }
        }
        
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'processed' => $processed,
            'total_profit' => round($total_profit, 2),
            'message' => "Added $$total_profit profit"
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        error_log("Error processing profits: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
}

function getUpdates($conn, $user_id) {
    // Get user balance
    $user_query = "SELECT account_balance, total_earnings FROM users WHERE id = ?";
    $user_stmt = $conn->prepare($user_query);
    $user_stmt->bind_param("i", $user_id);
    $user_stmt->execute();
    $user_result = $user_stmt->get_result();
    $user_data = $user_result->fetch_assoc();
    
    // Get investments
    $inv_query = "
        SELECT ui.id, ui.amount, ui.actual_return, ui.expected_return,
               ip.name as plan_name
        FROM user_investments ui
        JOIN investment_plans ip ON ui.plan_id = ip.id
        WHERE ui.user_id = ? AND ui.status = 'active'
    ";
    $inv_stmt = $conn->prepare($inv_query);
    $inv_stmt->bind_param("i", $user_id);
    $inv_stmt->execute();
    $inv_result = $inv_stmt->get_result();
    
    $investments = [];
    while ($row = $inv_result->fetch_assoc()) {
        $investments[] = [
            'id' => $row['id'],
            'amount' => floatval($row['amount']),
            'actual_return' => floatval($row['actual_return']),
            'expected_return' => floatval($row['expected_return']),
            'plan_name' => $row['plan_name']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'account_balance' => floatval($user_data['account_balance'] ?? 0),
        'total_earnings' => floatval($user_data['total_earnings'] ?? 0),
        'investments' => $investments,
        'timestamp' => time()
    ]);
}

$conn->close();
?>