<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../core/api.php';

if (!isset($pdo) || !$pdo) {
    error_log("Error CRON: Sin conexi¨Žn DB.");
    exit(1);
}

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

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

    foreach ($recurringRules as $rule) {
        $lastGen = $rule['last_generated_date'] ? new DateTime($rule['last_generated_date']) : null;
        if ($lastGen && $lastGen->format('Y-m') === $currentYearMonth) {
            continue; 
        }

        $day = min((int)$rule['recurrence_day_of_month'], (int)date('t'));
        $transDate = $currentYearMonth . '-' . str_pad($day, 2, '0', STR_PAD_LEFT);

        $pdo->beginTransaction();

        try {
            $stmtInsert = $pdo->prepare("INSERT INTO transactions (transaction_type, description, amount, transaction_date, client_id) VALUES (?, ?, ?, ?, ?)");
            $stmtInsert->execute([
                $rule['type'],
                $rule['description'] . " (Recurrente)", 
                $rule['amount'],
                $transDate,
                $rule['client_id']
            ]);

            $stmtUpdate = $pdo->prepare("UPDATE recurring_transactions SET last_generated_date = CURDATE() WHERE id = ?");
            $stmtUpdate->execute([$rule['id']]);

            $pdo->commit();
            error_log("CRON: Generado ID {$rule['id']} para $transDate");

        } catch (Exception $ex) {
            $pdo->rollBack();
            error_log("CRON Error ID {$rule['id']}: " . $ex->getMessage());
        }
    }

} catch (Exception $e) {
    error_log("CRON Error Fatal: " . $e->getMessage());
}
?>