<?php
declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(dirname(__DIR__));
$dotenv->safeLoad();

define('BASE_PATH', dirname(__DIR__));
define('APP_ENV', $_ENV['APP_ENV'] ?? 'development');

date_default_timezone_set('America/Lima');

echo "=== DIAGNÓSTICO DE CORREO ===\n\n";

// 1. Verificar configuración actual
$config = require BASE_PATH . '/config/mail.php';
echo "Config actual (desde .env):\n";
echo "  Host: {$config['host']}:{$config['port']}\n";
echo "  User: {$config['user']}\n";
echo "  Pass: " . (!empty($config['pass']) ? '******' : 'VACÍO') . "\n";
echo "  Enc:  {$config['encryption']}\n\n";

// 2. Verificar si hay configuraciones en BD que sobreescriben
try {
    $dbConfig = require BASE_PATH . '/config/database.php';
    $pdo = new PDO("mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset=utf8mb4", $dbConfig['user'], $dbConfig['pass']);
    $stmt = $pdo->query("SELECT `key`, `value` FROM configurations WHERE `key` LIKE 'smtp_%'");
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (count($rows) > 0) {
        echo "⚠️  CONFIGURACIONES SMTP EN BD (SOBREESCRIBEN .env):\n";
        foreach ($rows as $r) {
            $val = str_contains($r['key'], 'pass') ? '******' : $r['value'];
            echo "  {$r['key']} = {$val}\n";
        }
        echo "\n⚠️  EJECUTA EN MYSQL PARA LIMPIAR:\n";
        echo "  DELETE FROM configurations WHERE `key` LIKE 'smtp_%';\n\n";
    } else {
        echo "✅ No hay configuraciones SMTP en BD. Se usa .env correctamente.\n\n";
    }
} catch (\Throwable $e) {
    echo "⚠️  No se pudo verificar BD: " . $e->getMessage() . "\n\n";
}

// 3. Probar envío
echo "=== Probando envío de correo ===\n";
try {
    $mailService = new \App\Services\MailService();
    echo "MailService configurado: " . ($mailService->isConfigured() ? '✅ SI' : '❌ NO') . "\n";
    
    if ($mailService->isConfigured()) {
        $mailService->sendTaskReminder(
            'nextboost53@gmail.com',
            'TEST diagnóstico',
            'Prueba sistema',
            date('Y-m-d'),
            date('H:i')
        );
        echo "✅ Correo de prueba enviado correctamente\n";
    }
} catch (\Throwable $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}

echo "\n=== DIAGNÓSTICO COMPLETADO ===\n";
