<?php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/cron_errors.log');
error_reporting(E_ALL);

include_once 'db_connection.php';

if (!isset($pdo) || !$pdo) {
    error_log("Error fatal: La conexión a la base de datos no está disponible en generate-recurring-instances.php.");
    exit(1);
}

try {
    $currentDate = new DateTime();
    $currentYearMonth = $currentDate->format('Y-m'); 

    $sql = "SELECT id, type, description, amount, recurrence_day_of_month, start_date, end_date, client_id, last_generated_date
            FROM recurring_finances 
            WHERE start_date <= CURDATE() 
            AND (end_date IS NULL OR end_date >= CURDATE())";
    
    $stmt = $pdo->query($sql);
    $recurringRules = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($recurringRules)) {
        error_log("CRON: No hay reglas recurrentes para generar en el mes actual.");
        exit(0);
    }

    foreach ($recurringRules as $rule) {
        $lastGeneratedDate = !empty($rule['last_generated_date']) ? new DateTime($rule['last_generated_date']) : null;
        $lastGeneratedYearMonth = $lastGeneratedDate ? $lastGeneratedDate->format('Y-m') : null;

        if ($lastGeneratedYearMonth === $currentYearMonth) {
            continue; 
        }

        $recurrenceDay = (int)$rule['recurrence_day_of_month'];
        $tempDate = new DateTime($currentYearMonth . '-01');
        $daysInMonth = (int)$tempDate->format('t'); 
        $dayForTransaction = min($recurrenceDay, $daysInMonth); 

        $transactionDateStr = $currentYearMonth . '-' . str_pad($dayForTransaction, 2, '0', STR_PAD_LEFT);
        $transactionDate = new DateTime($transactionDateStr);

        $startDate = new DateTime($rule['start_date']);
        $endDate = !empty($rule['end_date']) ? new DateTime($rule['end_date']) : null;

        if ($transactionDate >= $startDate && (!$endDate || $transactionDate <= $endDate)) {
            
            $insertSql = "INSERT INTO finances (type, description, amount, transaction_date, client_id) VALUES (?, ?, ?, ?, ?)";
            $insertStmt = $pdo->prepare($insertSql);
            $success = $insertStmt->execute([
                $rule['type'],
                $rule['description'] . " (Recurrente)", 
                $rule['amount'],
                $transactionDateStr,
                $rule['client_id']
            ]);

            if ($success) {
                $updateSql = "UPDATE recurring_finances SET last_generated_date = CURDATE() WHERE id = ?";
                $updateStmt = $pdo->prepare($updateSql);
                $updateStmt->execute([$rule['id']]);
                error_log("CRON: Transacción recurrente generada para regla ID: {$rule['id']} (Cliente ID: {$rule['client_id']}) por \${$rule['amount']} para {$transactionDateStr}");
            } else {
                error_log("CRON: FALLO al insertar la transacción recurrente para la regla ID: {$rule['id']}. SQLSTATE: " . ($insertStmt->errorCode() ?: 'N/A'));
            }
        } else {
             error_log("CRON: Regla ID {$rule['id']} no generada. La fecha calculada para este mes ($transactionDateStr) está fuera de rango de inicio/fin ({$rule['start_date']} - {$rule['end_date']}).");
        }
    }

} catch (PDOException $e) {
    error_log("CRON PDO Error en generate-recurring-instances.php: " . $e->getMessage());
    exit(1);
} catch (Exception $e) {
    error_log("CRON General Error en generate-recurring-instances.php: " . $e->getMessage());
    exit(1);
}

exit(0);
?>