<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../config.php';

$data   = json_decode(file_get_contents('php://input'), true);
$accion = trim($data['accion'] ?? 'buscar');
$apiKey = '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';

// PASO 1: Buscar usuario por RFC
if ($accion === 'buscar') {
    $rfc = strtoupper(trim($data['rfc'] ?? ''));
    if (!$rfc) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'RFC requerido']);
        exit;
    }
    $db = getDB();
    $stmt = $db->prepare(
        "SELECT u.idusuario, u.nom_usr, i.id_inver, i.nombre, i.appat, i.apmat, i.email, i.tel1, i.tel2, i.wa
         FROM usuario u
         INNER JOIN inversionista i ON i.id_inver = u.inversionista_id_inver
         WHERE u.nom_usr = ? LIMIT 1"
    );
    $stmt->execute([$rfc]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'No se encontro una cuenta con ese RFC']);
        exit;
    }
    $opciones = [];
    if (!empty($user['email'])) {
        $parts = explode('@', $user['email']);
        $mask  = substr($parts[0], 0, 3) . '***@' . ($parts[1] ?? '');
        $opciones[] = ['tipo' => 'email', 'label' => 'Correo: ' . $mask, 'valor' => $user['email']];
    }
    $telesVistos = [];
    foreach (['tel1', 'tel2', 'wa'] as $campo) {
        if (!empty($user[$campo])) {
            $tel = preg_replace('/[\s\-\(\)]/', '', $user[$campo]);
            if (!in_array($tel, $telesVistos)) {
                $telesVistos[] = $tel;
                $etiqueta = $campo === 'wa' ? 'SMS (WhatsApp): ***' : 'SMS: ***';
                $opciones[] = ['tipo' => 'sms', 'label' => $etiqueta . substr($tel, -4), 'valor' => $user[$campo]];
            }
        }
    }
    if (empty($opciones)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Esta cuenta no tiene correo ni telefonos registrados. Contacta a tu centro de distribucion.']);
        exit;
    }
    echo json_encode([
        'success' => true,
        'data'    => [
            'id_inver' => $user['id_inver'],
            'nombre'   => trim($user['nombre'] . ' ' . $user['appat']),
            'opciones' => $opciones,
        ],
    ]);
    exit;
}

// PASO 2: Enviar código de 6 dígitos
if ($accion === 'enviar') {
    $idInver = (int)($data['id_inver'] ?? 0);
    $tipo    = trim($data['tipo']    ?? '');
    $destino = trim($data['destino'] ?? '');
    if (!$idInver || !$tipo || !$destino) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
        exit;
    }
    $db = getDB();
    $stmt = $db->prepare(
        "SELECT u.idusuario, i.nombre, i.appat, i.email, i.tel1, i.tel2, i.wa
         FROM inversionista i
         INNER JOIN usuario u ON u.inversionista_id_inver = i.id_inver
         WHERE i.id_inver = ? LIMIT 1"
    );
    $stmt->execute([$idInver]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Distribuidor no encontrado']);
        exit;
    }

    // Verificar que el destino pertenece a la cuenta
    $permitido   = false;
    $destinoNorm = preg_replace('/[\s\-\(\)]/', '', $destino);
    $campos = $tipo === 'email' ? [$user['email']] : [$user['tel1'], $user['tel2'], $user['wa']];
    foreach ($campos as $d) {
        if (!$d) continue;
        $dNorm = preg_replace('/[\s\-\(\)]/', '', $d);
        if ($dNorm === $destinoNorm || $d === $destino) { $permitido = true; break; }
    }
    if (!$permitido) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'El destino seleccionado no esta registrado en la cuenta']);
        exit;
    }

    // Crear tabla verify_codes si no existe (misma estructura que send-bank-verify.php)
    $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 DEFAULT 'banco',
        codigo VARCHAR(10) NOT NULL,
        expira DATETIME NOT NULL,
        usado TINYINT(1) NOT NULL DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_inver_tipo (id_inver, tipo)
    )");

    // Eliminar códigos anteriores de recuperación para este usuario
    $db->prepare("DELETE FROM verify_codes WHERE id_inver = ? AND tipo = 'recover'")->execute([$idInver]);

    // Generar código de 6 dígitos e insertar
    $codigo = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
    $expira = date('Y-m-d H:i:s', strtotime('+10 minutes'));
    $db->prepare("INSERT INTO verify_codes (id_inver, tipo, codigo, expira) VALUES (?, 'recover', ?, ?)")
       ->execute([$idInver, $codigo, $expira]);

    $nombre = trim($user['nombre'] . ' ' . $user['appat']);

    if ($tipo === 'email') {
        $html = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>
<body style="font-family:Arial,sans-serif;background:#f5f5f5;margin:0;padding:20px;">
  <div style="max-width:500px;margin:0 auto;background:#fff;border-radius:12px;padding:32px;">
    <h2 style="color:#1a1a2e;">Recuperacion de contrasena</h2>
    <p style="color:#555;">Hola <strong>' . htmlspecialchars($nombre) . '</strong>,</p>
    <p style="color:#555;">Tu codigo de verificacion es:</p>
    <div style="background:#f0f4ff;border-radius:8px;padding:16px;text-align:center;margin:20px 0;">
      <span style="font-size:36px;font-weight:bold;letter-spacing:8px;color:#1a1a2e;">' . $codigo . '</span>
    </div>
    <p style="color:#555;">Este codigo es valido por <strong>10 minutos</strong>.</p>
    <p style="color:#999;font-size:12px;">Si no solicitaste este cambio, ignora este mensaje.<br>Real Rich Business &bull; Correo automatico.</p>
  </div></body></html>';
        $payload = json_encode([
            'sender'      => ['name' => 'Real Rich Business', 'email' => 'noreply@productosrrb.com'],
            'to'          => [['email' => $destino, 'name' => $nombre]],
            'subject'     => 'Codigo de recuperacion - Real Rich Business',
            'htmlContent' => $html,
        ]);
        $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 => ['accept: application/json', 'api-key: ' . $apiKey, 'content-type: application/json'],
            CURLOPT_TIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $parts = explode('@', $destino);
        $mask  = substr($parts[0], 0, 3) . '***@' . ($parts[1] ?? '');
        if ($httpCode >= 200 && $httpCode < 300) {
            echo json_encode(['success' => true, 'message' => 'Codigo enviado a ' . $mask]);
        } else {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Error al enviar el correo. Intenta de nuevo.']);
        }
        exit;
    }

    if ($tipo === 'sms') {
        $telefono = preg_replace('/[\s\-\(\)]/', '', $destino);
        if (!str_starts_with($telefono, '+')) {
            if (strlen($telefono) === 10) $telefono = '+52' . $telefono;
            elseif (strlen($telefono) === 12 && str_starts_with($telefono, '52')) $telefono = '+' . $telefono;
        }
        $mensaje = "RRBMexico: Tu codigo de recuperacion es: {$codigo}. Valido 10 min. No lo compartas.";
        $payload = json_encode([
            'sender' => 'RRBMexico', 'recipient' => $telefono,
            'content' => $mensaje, 'type' => 'transactional',
        ]);
        $ch = curl_init('https://api.brevo.com/v3/transactionalSMS/sms');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => ['accept: application/json', 'api-key: ' . $apiKey, 'content-type: application/json'],
            CURLOPT_TIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $mask = '***' . substr(preg_replace('/[\s\-\(\)]/', '', $destino), -4);
        if ($httpCode >= 200 && $httpCode < 300) {
            echo json_encode(['success' => true, 'message' => 'Codigo enviado al numero ' . $mask]);
        } else {
            $errData = json_decode($response, true);
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => $errData['message'] ?? 'Error al enviar el SMS.']);
        }
        exit;
    }
}

http_response_code(400);
echo json_encode(['success' => false, 'message' => 'Accion no valida']);
