<?php
/**
 * NEXUS IT - Cron: Procesar correos → tickets
 * Ejecutar cada 5 minutos via cPanel Cron Jobs
 * Comando: php /home/evolucionamos/public_html/ana/cron/email_to_ticket.php
 */

require_once dirname(__DIR__) . '/api/config/app.php';
require_once dirname(__DIR__) . '/api/config/database.php';

if (file_exists(dirname(__DIR__) . '/api/helpers/EmailToTicket.php')) {
    require_once dirname(__DIR__) . '/api/helpers/EmailToTicket.php';
} else {
    echo "EmailToTicket helper not found\n";
    exit(1);
}

$db = getDB();

// Verificar si está habilitado
$stmt = $db->prepare("SELECT valor FROM configuracion WHERE clave = 'imap_enabled'");
$stmt->execute();
$enabled = $stmt->fetchColumn();
if (!$enabled || $enabled === '0') {
    echo "[" . date('Y-m-d H:i:s') . "] Email-to-ticket deshabilitado\n";
    exit(0);
}

echo "[" . date('Y-m-d H:i:s') . "] Procesando correos...\n";

try {
    $result = EmailToTicket::procesar();
    echo "Resultado: " . ($result['message'] ?? 'OK') . "\n";
    if (!empty($result['log'])) {
        foreach ($result['log'] as $line) {
            echo "  $line\n";
        }
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
