<?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 = 0;
$dueActions = 0;
$mvpResult = array('processed' => 0, 'high_value_stalled' => 0, 'quote_no_tax_document' => 0, 'billing_due_today' => 0, 'billing_overdue_critical' => 0);
$emailResult = array('processed' => 0, 'sent' => 0, 'failed' => 0);

try {
    $updatedOverdue = PaymentStatusService::processOverdueOpportunities($pdo);
    $service = new NotificationService($pdo);
    $dueActions = $service->processDueActionNotifications(1);
    $mvpResult = $service->processExecutiveMvpNotifications();
    $emailResult = $service->processEmailQueue(100);
} catch (Throwable $e) {
    error_log('process_notifications error: ' . $e->getMessage());
    if (PHP_SAPI !== 'cli') {
        http_response_code(500);
    }
}

if (PHP_SAPI !== 'cli') {
    header('Content-Type: text/plain; charset=utf-8');
}

echo 'process_notifications OK' . PHP_EOL;
echo 'Overdue opportunities: ' . (int)$updatedOverdue . PHP_EOL;
echo 'Due action notifications: ' . (int)$dueActions . PHP_EOL;
echo 'Executive MVP processed: ' . (int)$mvpResult['processed'] . PHP_EOL;
echo 'High value stalled: ' . (int)$mvpResult['high_value_stalled'] . PHP_EOL;
echo 'Accepted quotes without tax document: ' . (int)$mvpResult['quote_no_tax_document'] . PHP_EOL;
echo 'Billing due today: ' . (int)$mvpResult['billing_due_today'] . PHP_EOL;
echo 'Billing overdue critical: ' . (int)$mvpResult['billing_overdue_critical'] . PHP_EOL;
echo 'Email processed: ' . (int)$emailResult['processed'] . PHP_EOL;
echo 'Email sent: ' . (int)$emailResult['sent'] . PHP_EOL;
echo 'Email failed: ' . (int)$emailResult['failed'] . PHP_EOL;
