<?php
// process_investments.php
// This script should be run EVERY MINUTE via cron job

require_once '../connection.php';

// Create lock file to prevent multiple simultaneous executions
$lockFile = __DIR__ . '/investment_process.lock';

// Check if lock file exists (process already running)
if (file_exists($lockFile)) {
    $lockAge = time() - filemtime($lockFile);
    // If lock is older than 5 minutes, assume it's stale and remove it
    if ($lockAge > 300) {
        unlink($lockFile);
        error_log("[" . date('Y-m-d H:i:s') . "] Removed stale lock file");
    } else {
        error_log("[" . date('Y-m-d H:i:s') . "] Process already running, exiting");
        exit(0);
    }
}

// Create lock file
file_put_contents($lockFile, date('Y-m-d H:i:s'));
error_log("[" . date('Y-m-d H:i:s') . "] Lock file created.");

// Log start time
error_log("[" . date('Y-m-d H:i:s') . "] Starting investment processing");

// Process completed investments
$completed_count = processCompletedInvestments($conn);
error_log("[" . date('Y-m-d H:i:s') . "] Processed {$completed_count} completed investments");

// Process interest for all active investments (every minute)
$interest_count = processMinuteInterest($conn);
error_log("[" . date('Y-m-d H:i:s') . "] Processed {$interest_count} interest payments");

// Log completion
error_log("[" . date('Y-m-d H:i:s') . "] Investment processing completed");

echo "Content-type: text/html; charset=UTF-8\n\n";
echo "Processed:\n";
echo "- Completed investments: {$completed_count}\n";
echo "- Interest payments: {$interest_count}\n";

// Remove lock file
if (file_exists($lockFile)) {
    unlink($lockFile);
    error_log("[" . date('Y-m-d H:i:s') . "] Lock file removed.");
}

// Function to process completed investments (remains similar but with minute precision)
function processCompletedInvestments($conn) {
    $now = date('Y-m-d H:i:s');
    
    $query = "
        SELECT ui.*, u.account_balance, u.total_earnings, ip.name as plan_name
        FROM user_investments ui
        JOIN users u ON ui.user_id = u.id
        JOIN investment_plans ip ON ui.plan_id = ip.id
        WHERE ui.status = 'active' 
        AND ui.end_date <= ? 
        AND ui.actual_return = 0
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $now);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $processed_count = 0;
    
    while ($investment = $result->fetch_assoc()) {
        // Calculate final profit including any accrued interest
        $total_return = $investment['expected_return'] + ($investment['actual_return'] ?? 0);
        $profit = $total_return - $investment['amount'];
        
        if ($total_return > 0) {
            $conn->begin_transaction();
            
            try {
                // Update user balance and total earnings
                $update_user = $conn->prepare("
                    UPDATE users SET 
                    account_balance = account_balance + ?,
                    total_earnings = total_earnings + ?,
                    investment_balance = investment_balance - ?,
                    updated_at = NOW()
                    WHERE id = ?
                ");
                $update_user->bind_param("dddi", $total_return, $profit, $investment['amount'], $investment['user_id']);
                $update_user->execute();
                $update_user->close();
                
                // Update investment status
                $update_investment = $conn->prepare("
                    UPDATE user_investments SET 
                    status = 'completed',
                    actual_return = ?,
                    updated_at = NOW()
                    WHERE id = ?
                ");
                $update_investment->bind_param("di", $total_return, $investment['id']);
                $update_investment->execute();
                $update_investment->close();
                
                // Create transaction
                $create_transaction = $conn->prepare("
                    INSERT INTO transactions 
                    (user_id, amount, type, status, description, created_at)
                    VALUES (?, ?, 'profit', 'completed', 'Investment completed - {$investment['plan_name']}', NOW())
                ");
                $create_transaction->bind_param("id", $investment['user_id'], $total_return);
                $create_transaction->execute();
                $create_transaction->close();
                
                $conn->commit();
                $processed_count++;
                
                error_log("[" . date('Y-m-d H:i:s') . "] Investment ID {$investment['id']} completed. User {$investment['user_id']} received {$total_return}");
                
            } catch (Exception $e) {
                $conn->rollback();
                error_log("[" . date('Y-m-d H:i:s') . "] ERROR: Failed to process investment ID {$investment['id']}: " . $e->getMessage());
            }
        }
    }
    
    $stmt->close();
    return $processed_count;
}

// NEW FUNCTION: Process interest every minute
function processMinuteInterest($conn) {
    $now = date('Y-m-d H:i:s');
    
    // Get all active investments
    $query = "
        SELECT ui.*, 
               ip.interest_rate, 
               ip.duration_days,
               ip.name as plan_name,
               ip.compounding_interval,
               u.total_earnings,
               u.account_balance
        FROM user_investments ui
        JOIN investment_plans ip ON ui.plan_id = ip.id
        JOIN users u ON ui.user_id = u.id
        WHERE ui.status = 'active'
        AND ui.end_date > ?
        AND (
            (ip.compounding_interval = 'daily' AND TIMESTAMPDIFF(MINUTE, ui.last_interest_calc, ?) >= 1440) OR
            (ip.compounding_interval = 'weekly' AND TIMESTAMPDIFF(MINUTE, ui.last_interest_calc, ?) >= 10080) OR
            (ip.compounding_interval = 'monthly' AND TIMESTAMPDIFF(MINUTE, ui.last_interest_calc, ?) >= 43200)
        )
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ssss", $now, $now, $now, $now);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $processed_count = 0;
    
    while ($investment = $result->fetch_assoc()) {
        $conn->begin_transaction();
        
        try {
            // Calculate total profit for the investment period
            $total_profit = $investment['amount'] * ($investment['interest_rate'] / 100);
            
            // Calculate interest based on compounding interval
            switch ($investment['compounding_interval']) {
                case 'daily':
                    // Daily interest = total profit / duration_days
                    $interest_amount = $total_profit / $investment['duration_days'];
                    $next_calc_interval = "INTERVAL 1 DAY";
                    $description = "Daily interest";
                    break;
                    
                case 'weekly':
                    // Weekly interest = total profit / (duration_days / 7)
                    $interest_amount = $total_profit / ($investment['duration_days'] / 7);
                    $next_calc_interval = "INTERVAL 7 DAY";
                    $description = "Weekly interest";
                    break;
                    
                case 'monthly':
                    // Monthly interest = total profit / (duration_days / 30)
                    $interest_amount = $total_profit / ($investment['duration_days'] / 30);
                    $next_calc_interval = "INTERVAL 30 DAY";
                    $description = "Monthly interest";
                    break;
                    
                default:
                    // Default to daily if not specified
                    $interest_amount = $total_profit / $investment['duration_days'];
                    $next_calc_interval = "INTERVAL 1 DAY";
                    $description = "Interest";
            }
            
            if ($interest_amount > 0) {
                // Update user balance and total earnings
                $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", $interest_amount, $interest_amount, $investment['user_id']);
                $update_user->execute();
                $update_user->close();
                
                // Update investment record
                $update_investment = $conn->prepare("
                    UPDATE user_investments SET 
                    actual_return = actual_return + ?,
                    last_interest_calc = NOW(),
                    updated_at = NOW()
                    WHERE id = ?
                ");
                $update_investment->bind_param("di", $interest_amount, $investment['id']);
                $update_investment->execute();
                $update_investment->close();
                
                // Create transaction record
                $transaction_description = "{$description} from {$investment['plan_name']}";
                $create_transaction = $conn->prepare("
                    INSERT INTO transactions 
                    (user_id, amount, type, status, description, created_at)
                    VALUES (?, ?, 'profit', 'completed', ?, NOW())
                ");
                $create_transaction->bind_param("ids", $investment['user_id'], $interest_amount, $transaction_description);
                $create_transaction->execute();
                $create_transaction->close();
                
                $processed_count++;
                
                error_log("[" . date('Y-m-d H:i:s') . "] Interest for Investment ID {$investment['id']}: User {$investment['user_id']} received {$interest_amount}");
            }
            
            $conn->commit();
            
        } catch (Exception $e) {
            $conn->rollback();
            error_log("[" . date('Y-m-d H:i:s') . "] ERROR: Failed to process interest for investment ID {$investment['id']}: " . $e->getMessage());
        }
    }
    
    $stmt->close();
    return $processed_count;
}

$conn->close();
?>