<?php
/**
 * distribuidor-actualizar-email.php
 * POST { id_inv, email } → Actualiza el email del distribuidor en inversionista
 */
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Método no permitido']);
    exit;
}

require_once __DIR__ . '/../../config.php';
$db = getDB();

// ── Validar token admin ───────────────────────────────────────────────────────
$headers    = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!preg_match('/Bearer\s+(.+)/i', $authHeader, $m)) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Token requerido']);
    exit;
}
$token = trim($m[1]);
$stmtTok = $db->prepare("SELECT idusuarios_sist FROM admin_sessions WHERE token = ? AND expira > NOW()");
$stmtTok->execute([$token]);
if (!$stmtTok->fetch()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Sesión inválida o expirada']);
    exit;
}

// ── Leer payload ──────────────────────────────────────────────────────────────
$b     = json_decode(file_get_contents('php://input'), true) ?? [];
$idInv = (int)($b['id_inv'] ?? 0);
$email = trim($b['email']   ?? '');

if ($idInv <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'id_inv requerido']);
    exit;
}
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Correo electrónico inválido']);
    exit;
}

// ── Actualizar email ──────────────────────────────────────────────────────────
$stmt = $db->prepare("UPDATE inversionista SET email = ? WHERE id_inver = ?");
$stmt->execute([$email, $idInv]);

if ($stmt->rowCount() === 0) {
    // Puede que el email sea el mismo — verificar que exista el distribuidor
    $check = $db->prepare("SELECT id_inver FROM inversionista WHERE id_inver = ?");
    $check->execute([$idInv]);
    if (!$check->fetch()) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'Distribuidor no encontrado']);
        exit;
    }
}

echo json_encode(['ok' => true, 'id_inv' => $idInv, 'email' => $email]);
