<?php
// 파일위치 : /mylib/strongswan_profile_common_lib.php

define ('VPN_USAGE_HOURS', 1); // 무료 공공 VPN 이용 시간 공통 설정 (예 2 = 2시간)

function sync_strongswan_ipsec_secrets_vpnid(
    $type,
    $server_domain,
    $vpn_user_id,
    $vpn_user_pwd,
    $expire_time = '0000-00-00 00:00:00'
) {
    $encryption_key = 'f9d8a7c6b5e4f3a2d1c0b9e8f7a6d5c5';

    try {
        $payload = [
            'type'       => $type,
            'vpn_user_id'  => $vpn_user_id,
            'vpn_user_pwd' => $vpn_user_pwd,
            'timestamp'  => time(),
            'expire_time' => $expire_time
        ];

        $json_data = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        if ($json_data === false) {
            throw new Exception('JSON encoding failed');
        }

        $iv = substr(hash('sha256', $encryption_key), 0, 16);
        $encrypted = openssl_encrypt($json_data, 'AES-256-CBC', $encryption_key, 0, $iv);
        if ($encrypted === false) {
            throw new Exception('Encryption failed');
        }

        $post_data = ['encrypted_data' => $encrypted];
        $url = sprintf('http://%s/IKEv2SellerOffice/sync_strongswan_ipsec_secrets_vpnid.php', $server_domain);

        $ch = curl_init($url);
        if ($ch === false) {
            throw new Exception('cURL initialization failed');
        }

        curl_setopt_array($ch, [
            CURLOPT_POST            => true,
            CURLOPT_POSTFIELDS      => http_build_query($post_data, '', '&', PHP_QUERY_RFC3986),
            CURLOPT_RETURNTRANSFER  => true,
            CURLOPT_HEADER          => false,
            CURLOPT_CONNECTTIMEOUT  => 5,
            CURLOPT_TIMEOUT         => 15,
            CURLOPT_HTTP_VERSION    => CURL_HTTP_VERSION_1_1,
            CURLOPT_USERAGENT       => 'VPNSync/1.0',
            CURLOPT_HTTPHEADER      => ['Content-Type: application/x-www-form-urlencoded; charset=UTF-8'],
        ]);

        $response   = curl_exec($ch);
        $curl_info  = curl_getinfo($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);

        if ($response === false) {
            throw new Exception('cURL request failed: ' . ($curl_error !== '' ? $curl_error : 'unknown error'));
        }

        $responseBody = trim($response);
        $http_code    = (int)($curl_info['http_code'] ?? 0);

        if ($http_code === 200 && $responseBody === 'success') {
            return true;
        }

        throw new Exception(
            sprintf('Unexpected response (HTTP %d): %s', $http_code, $responseBody === '' ? '(empty)' : $responseBody)
        );
    } catch (Exception $e) {

        return false;
    }
}

if (!function_exists('vpnlink_paid_profile_item_label')) {
    function vpnlink_paid_profile_item_label($mbId, $serverName, $vpnUserId)
    {
        global $g5;

        $mbId = trim((string)$mbId);
        $serverName = trim((string)$serverName);
        $vpnUserId = trim((string)$vpnUserId);

        if ($mbId === '' || $serverName === '' || $vpnUserId === '') {
            return 'VPN';
        }

        if (!isset($g5['g5_shop_item_table'])) {
            return 'VPN';
        }

        static $cache = array();
        $cacheKey = $mbId . '|' . $serverName . '|' . $vpnUserId;
        if (isset($cache[$cacheKey])) {
            return $cache[$cacheKey];
        }

        $safeMb = function_exists('sql_real_escape_string') ? sql_real_escape_string($mbId) : addslashes($mbId);
        $safeServer = function_exists('sql_real_escape_string') ? sql_real_escape_string($serverName) : addslashes($serverName);
        $safeUser = function_exists('sql_real_escape_string') ? sql_real_escape_string($vpnUserId) : addslashes($vpnUserId);

        $q = sql_fetch("SELECT it_id
                          FROM app_ikev2_provision_queue
                         WHERE mb_id = '{$safeMb}'
                           AND server_ip = '{$safeServer}'
                           AND vpn_user_id = '{$safeUser}'
                         ORDER BY queue_id DESC
                         LIMIT 1", false);

        $itId = isset($q['it_id']) ? trim((string)$q['it_id']) : '';
        if ($itId === '') {
            $cache[$cacheKey] = 'VPN';
            return $cache[$cacheKey];
        }

        $safeItId = function_exists('sql_real_escape_string') ? sql_real_escape_string($itId) : addslashes($itId);
        $item = sql_fetch("SELECT it_name
                             FROM {$g5['g5_shop_item_table']}
                            WHERE it_id = '{$safeItId}'
                            LIMIT 1", false);

        $itName = isset($item['it_name']) ? trim((string)$item['it_name']) : '';
        if ($itName === '') {
            $itName = 'VPN-' . $itId;
        }

        $cache[$cacheKey] = $itName;
        return $cache[$cacheKey];
    }
}
?>