<?php
// scripts/imap_diag.php (Disney+ OTP listo)
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/crypto.php';
require_once __DIR__ . '/../includes/imap_lib.php';

header('Content-Type: text/plain; charset=utf-8');

// Parámetros GET opcionales
$limit = max(1, (int)($_GET['limit'] ?? 10)); // cantidad de correos a revisar
$useUnseen = isset($_GET['unseen']) ? (int)$_GET['unseen'] : 0; // 0 = ALL, 1 = UNSEEN

echo "== IMAP DIAGNÓSTICO DISNEY+ OTP ==\n";
echo "Params: limit={$limit}, unseen={$useUnseen}\n\n";

// Traer cuentas habilitadas
$accs = pdo()->query('SELECT * FROM imap_accounts WHERE enabled=1')->fetchAll();
if (!$accs) { echo "No hay cuentas IMAP habilitadas.\n"; exit; }

foreach ($accs as $acc) {
    echo ">> Conectando: {$acc['label']} ({$acc['username']})\n";
    $mbox = "{imap.gmail.com:993/ssl}INBOX"; // carpeta principal de Gmail
    $pass = decrypt_text($acc['password_enc']);

    $stream = @imap_open($mbox, $acc['username'], $pass);
    if (!$stream) {
        echo "   ERROR: " . imap_last_error() . "\n\n";
        continue;
    }

    // Buscar mensajes
    $searchCriteria = $useUnseen ? 'UNSEEN' : 'ALL';
    $uids = @imap_search($stream, $searchCriteria, SE_UID) ?: [];
    $uids = array_slice(array_reverse($uids), 0, $limit);

    echo "   Mensajes encontrados: ".count($uids)."\n";

    foreach ($uids as $uid) {
        $overview = imap_fetch_overview($stream, $uid, FT_UID)[0] ?? null;
        if (!$overview) continue;

        $subject = isset($overview->subject) ? imap_utf8($overview->subject) : '';
        $from = $overview->from ?? '';
        $date = $overview->date ?? '';

        // Obtener cuerpo del mensaje: intentamos text/plain, sino todo el body
        $body = imap_fetchbody($stream, $uid, 1); // text/plain
        if (!$body) $body = imap_body($stream, $uid);

        // Limpiar HTML si es necesario
        $body = strip_tags($body);

        // Extraer códigos de 6 dígitos
        preg_match_all('/\b\d{6}\b/', $subject."\n".$body, $matches);
        $codes = $matches[0] ?? [];

        echo "-----\n";
        echo "Fecha: {$date}\n";
        echo "De: {$from}\n";
        echo "Asunto: {$subject}\n";
        if ($codes) echo "Códigos encontrados: ".implode(', ', $codes)."\n";
        else echo "Códigos encontrados: NINGUNO\n";
    }

    imap_close($stream);
    echo "\n";
}

echo "Fin diag.\n";
?>
