<?php
/**
 * vpns.php — VPN profile API endpoint
 * 
 * Called by the app at: {panel_url}api/vpns.php?list=1
 * Returns JSON with VPN profiles for the StreamVault VPN system.
 */

require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json; charset=UTF-8');

require_valid_signature();

logRequest('api/vpns.php');

if (!isset($_GET['list'])) {
    echo json_encode(['success' => false, 'error' => 'Missing parameter']);
    exit;
}

$profiles = $db->select('vpn_profiles', '*', 'enabled = 1', 'id ASC');

$vpns = [];
foreach ($profiles as $profile) {
    $item = [
        'id' => (int) $profile['id'],
        'name' => $profile['name'] ?? '',
        'country' => $profile['country'] ?? '',
        'city' => $profile['city'] ?? '',
        'protocol' => $profile['protocol'] ?? 'udp',
        'port' => $profile['port'] ?? '1194',
        'enabled' => true,
    ];

    // Inline config takes priority over URL
    if (!empty($profile['ovpn_config'])) {
        $item['ovpn'] = $profile['ovpn_config'];
    } elseif (!empty($profile['config_url'])) {
        $item['config_url'] = $profile['config_url'];
    }

    if (!empty($profile['username'])) {
        $item['username'] = $profile['username'];
    }
    if (!empty($profile['password'])) {
        $item['password'] = $profile['password'];
    }

    $vpns[] = $item;
}

echo json_encode([
    'success' => true,
    'vpns' => $vpns,
], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
