<?php
/**
 * api/device/vpn.php — GET /api/device/vpn
 *
 * Devuelve la lista de servidores VPN (OpenVPN) habilitados por el admin. La app
 * los muestra en su sección VPN e importa el `.ovpn` como perfil para conectar.
 *
 * Contrato (igual a la referencia, key "vpns"): la app importa el .ovpn inline.
 * Response: { "vpns": [ { "name", "ovpn", "username", "password", "country", "flag" }, ... ] }
 * (country/flag son extra nuestro, opcionales; un picker mínimo usa sólo los 4 primeros.)
 */

declare(strict_types=1);

require_once __DIR__ . '/../../lib/helpers.php';
require_once __DIR__ . '/../../lib/device.php';
require_once __DIR__ . '/../../lib/vpn.php';

try {
    $pdo = db();
    ensure_vpn_schema($pdo);

    $rows = $pdo->query(
        'SELECT name, country, flag, username, password, ovpn
         FROM vpn_servers WHERE enabled = 1 ORDER BY country ASC, name ASC, id ASC'
    )->fetchAll(PDO::FETCH_ASSOC);

    $list = [];
    foreach ($rows as $row) {
        $ovpn = (string) ($row['ovpn'] ?? '');
        if (trim($ovpn) === '') {
            continue;
        }
        $list[] = [
            'name'     => (string) ($row['name'] ?? ''),
            'ovpn'     => $ovpn,
            'username' => (string) ($row['username'] ?? ''),
            'password' => (string) ($row['password'] ?? ''),
            'country'  => (string) ($row['country'] ?? ''),
            'flag'     => (string) ($row['flag'] ?? ''),
        ];
    }

    json_out(['vpns' => $list], 200);
} catch (Throwable $ex) {
    error_log('[api/device/vpn] ' . $ex->getMessage());
    json_out(['vpns' => [], 'error' => 'server_error'], 500);
}
