<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/database.php';
require_once '../../services/crm/RestockForecastService.php';

require_login();
require_permission('module.crm');
csrf_require_valid_request();
$user = current_user() ?: array();
if (!in_array((string)($user['role'] ?? ''), array('admin','administracion'), true)) {
    http_response_code(403);
    die('No autorizado.');
}
try {
    $result = (new RestockForecastService(db()))->processDaily();
    $message = 'Motor ejecutado. Clientes evaluados: ' . (int)($result['customers_evaluated'] ?? 0)
        . '; pronósticos creados/actualizados: ' . (int)($result['forecasts_refreshed'] ?? 0)
        . '; omitidos por reglas: ' . (int)($result['forecasts_skipped'] ?? 0)
        . '; convertidos en oportunidades: ' . (int)($result['forecasts_converted'] ?? 0)
        . '; compras conciliadas: ' . (int)($result['purchases_reconciled'] ?? 0)
        . '; oportunidades vencidas: ' . (int)($result['stale_opportunities_closed'] ?? 0) . '.';
    if (!empty($result['forecast_refresh_errors'])) {
        $message .= ' Errores de actualización: ' . (int)$result['forecast_refresh_errors'] . '.';
    }
    if (!empty($result['skip_reasons']) && is_array($result['skip_reasons'])) {
        $reasons = array();
        foreach (array_slice($result['skip_reasons'], 0, 3, true) as $reason => $count) {
            $reasons[] = $reason . ' (' . (int)$count . ')';
        }
        if ($reasons) $message .= ' Principales omisiones: ' . implode('; ', $reasons) . '.';
    }
    $_SESSION['restock_flash'] = array('ok'=>true,'message'=>$message);
} catch (Throwable $e) {
    $_SESSION['restock_flash'] = array('ok'=>false,'message'=>'No fue posible ejecutar el motor: ' . $e->getMessage());
}
header('Location: /modules/crm/restock_forecasts.php');
exit;
