<?php
// Ejecutar el send-bank-verify.php directamente con error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';

// Simular que ya tenemos el JWT payload (sin pasar por auth())
$db = getDB();
$row = $db->query("SELECT id_inver, nombre, apellido, email, tel1, tel2, wa FROM inversionista WHERE email IS NOT NULL AND email != '' LIMIT 1")->fetch(PDO::FETCH_ASSOC);

if (!$row) { echo json_encode(['error' => 'No hay distribuidores']); exit; }

$idinv = $row['id_inver'];
$canal = 'email';
$nombre = trim(($row['nombre'] ?? '') . ' ' . ($row['apellido'] ?? ''));

// Verificar tabla verify_codes
try {
    $db->exec("CREATE TABLE IF NOT EXISTS verify_codes (
        id INT AUTO_INCREMENT PRIMARY KEY,
        id_inver INT NOT NULL,
        tipo VARCHAR(20) NOT NULL,
        codigo VARCHAR(10) NOT NULL,
        expira DATETIME NOT NULL,
        INDEX idx_inver_tipo (id_inver, tipo)
    )");
    echo json_encode(['step' => 'tabla_ok']);
} catch (Exception $e) {
    echo json_encode(['error_tabla' => $e->getMessage()]);
    exit;
}

// Generar código
$codigo = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);
$expira = date('Y-m-d H:i:s', time() + 600);

// Insertar código
try {
    $stmt = $db->prepare("DELETE FROM verify_codes WHERE id_inver = ? AND tipo = 'banco'");
    $stmt->execute([$idinv]);
    $stmt = $db->prepare("INSERT INTO verify_codes (id_inver, tipo, codigo, expira) VALUES (?, 'banco', ?, ?)");
    $stmt->execute([$idinv, $codigo, $expira]);
    echo json_encode(['step' => 'codigo_insertado', 'codigo' => $codigo]);
} catch (Exception $e) {
    echo json_encode(['error_insert' => $e->getMessage()]);
    exit;
}

// Probar envío de correo con Brevo
$brevoKey = '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';
$payload = json_encode([
    'sender'     => ['name' => 'Real Rich Business', 'email' => 'noreply@productosrrb.com'],
    'to'         => [['email' => $row['email'], 'name' => $nombre]],
    'subject'    => 'Código de verificación',
    'htmlContent'=> "<p>Tu código es: <strong>$codigo</strong></p>",
]);
$ch = curl_init('https://api.brevo.com/v3/smtp/email');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'api-key: ' . $brevoKey,
    ],
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT        => 15,
]);
$resp     = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr  = curl_error($ch);
curl_close($ch);

echo json_encode([
    'step'      => 'correo_enviado',
    'http_code' => $httpCode,
    'curl_err'  => $curlErr,
    'brevo_resp'=> json_decode($resp, true) ?? $resp,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
