<?php
// Cron job to check and process completed investments
require_once __DIR__ . '/../includes/functions.php';

$functions = new InvestmentFunctions();

try {
    // Get all running investments that have ended
    $stmt = $functions->db->prepare("
        SELECT i.*, p.name as plan_name, p.principal_return, u.email, u.username
        FROM investments i
        JOIN investment_plans p ON i.plan_id = p.id
        JOIN users u ON i.user_id = u.id
        WHERE i.status = 'running' AND i.end_date <= NOW()
    ");
    $stmt->execute();
    $completed_investments = $stmt->fetchAll();

    foreach ($completed_investments as $investment) {
        try {
            $functions->db->beginTransaction();

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

            // Return principal if applicable
            if ($investment['principal_return']) {
                $functions->updateUserBalance($investment['user_id'], $investment['amount']);

                // Create transaction for principal return
                $functions->createTransaction([
                    'user_id' => $investment['user_id'],
                    'type' => 'credit',
                    'amount' => $investment['amount'],
                    'method' => 'system',
                    'description' => 'Principal return from investment #' . $investment['id'],
                    'status' => 'completed',
                    'details' => ['investment_id' => $investment['id'], 'type' => 'principal_return']
                ]);
            }

            // Log activity
            $functions->logActivity(
                $investment['user_id'],
                'investment_completed',
                'Investment #' . $investment['id'] . ' completed'
            );

            $functions->db->commit();

            error_log("Investment completed: ID " . $investment['id'] . " for user " . $investment['username']);

        } catch (Exception $e) {
            $functions->db->rollBack();
            error_log("Error completing investment " . $investment['id'] . ": " . $e->getMessage());
        }
    }

    // Log summary
    $completed_count = count($completed_investments);
    if ($completed_count > 0) {
        error_log("Cron job completed: $completed_count investments processed");
    }

} catch (Exception $e) {
    error_log("Cron job error in check-investments.php: " . $e->getMessage());
}
?>
