<?php
// Cron job to add daily profits to running investments
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

$functions = new InvestmentFunctions();

try {
    // Get all running investments that haven't received profit today
    $stmt = $functions->db->prepare("
        SELECT i.*, p.name as plan_name, 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()
        AND (i.last_profit_date IS NULL OR i.last_profit_date < CURDATE())
    ");
    $stmt->execute();
    $active_investments = $stmt->fetchAll();

    $processed_count = 0;

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

            // Add daily profit to investment
            $update_investment = $functions->db->prepare("
                UPDATE investments SET
                    total_profit = total_profit + ?,
                    last_profit_date = CURDATE(),
                    updated_at = NOW()
                WHERE id = ?
            ");
            $update_investment->execute([$investment['daily_profit'], $investment['id']]);

            // Add profit to user balance
            $functions->updateUserBalance($investment['user_id'], $investment['daily_profit'], 'add');

            // Create transaction record
            $functions->createTransaction([
                'user_id' => $investment['user_id'],
                'type' => 'profit',
                'amount' => $investment['daily_profit'],
                'method' => 'system',
                'description' => 'Daily profit from investment #' . $investment['id'] . ' (' . $investment['plan_name'] . ')',
                'status' => 'completed',
                'reference' => 'PROF' . date('Ymd') . $investment['id'],
                'details' => [
                    'investment_id' => $investment['id'],
                    'plan_name' => $investment['plan_name'],
                    'profit_date' => date('Y-m-d')
                ]
            ]);

            // Log activity
            $functions->logActivity(
                $investment['user_id'],
                'daily_profit_added',
                'Daily profit of $' . number_format($investment['daily_profit'], 2) . ' added from investment #' . $investment['id']
            );

            $functions->db->commit();
            $processed_count++;

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

    // Log summary
    if ($processed_count > 0) {
        error_log("Daily profits cron completed: $processed_count investments processed");
    }

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