<?php
header('Content-Type: application/json; charset=utf-8');
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 dirname(__FILE__) . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { jsonErr(405, 'Metodo no permitido.'); }

$jwt   = auth();
$idinv = (int)$jwt['idinv'];

$body      = json_decode(file_get_contents('php://input'), true);
$pushToken = trim($body['push_token'] ?? '');

if (empty($pushToken)) {
    jsonErr(400, 'Token requerido.');
}

$db = getDB();

// Agregar columna push_token si no existe (ejecución idempotente)
try {
    $db->exec("ALTER TABLE inversionista ADD COLUMN push_token VARCHAR(200) NULL DEFAULT NULL");
} catch (PDOException $e) {
    // Columna ya existe — ignorar
}

$stmt = $db->prepare("UPDATE inversionista SET push_token = ? WHERE id_inver = ?");
$stmt->execute([$pushToken, $idinv]);

echo json_encode(['success' => true, 'message' => 'Token guardado']);
