<?php

require_once __DIR__ . '/../core/config.php';
require_once __DIR__ . '/../core/database.php';
require_once __DIR__ . '/../services/crm/PaymentStatusService.php';
require_once __DIR__ . '/../services/notifications/NotificationService.php';

$pdo = db();
$updatedOverdue = PaymentStatusService::processOverdueOpportunities($pdo);

$notificationResult = array('processed' => 0, 'sent' => 0, 'failed' => 0);
$mvpResult = array('processed' => 0, 'high_value_stalled' => 0, 'quote_no_tax_document' => 0, 'billing_due_today' => 0, 'billing_overdue_critical' => 0);
$dueActions = 0;
try {
    $notificationService = new NotificationService($pdo);
    $dueActions = $notificationService->processDueActionNotifications(1);
    $mvpResult = $notificationService->processExecutiveMvpNotifications();
    $notificationResult = $notificationService->processEmailQueue(50);
} catch (Throwable $e) {
    error_log('daily_jobs notifications error: ' . $e->getMessage());
}

header('Content-Type: text/plain; charset=utf-8');
echo 'daily_jobs OK' . PHP_EOL;
echo 'Oportunidades marcadas como atrasadas: ' . (int)$updatedOverdue . PHP_EOL;
echo 'Recordatorios de próxima acción generados: ' . (int)$dueActions . PHP_EOL;
echo 'Alertas MVP ejecutivas generadas: ' . (int)$mvpResult['processed'] . PHP_EOL;
echo 'Emails procesados: ' . (int)$notificationResult['processed'] . PHP_EOL;
echo 'Emails enviados: ' . (int)$notificationResult['sent'] . PHP_EOL;
echo 'Emails fallidos: ' . (int)$notificationResult['failed'] . PHP_EOL;
