<?php
function sync_strongswan_ipsec_secrets_vpnid(
    $type,
    $server_domain,
    $member_id,
    $member_pwd,
    $expire_time = '0000-00-00 00:00:00'
) {
    $encryption_key = 'f9d8a7c6b5e4f3a2d1c0b9e8f7a6d5c5';

    try {
        $payload = [
            'type'       => $type,
            'member_id'  => $member_id,
            'member_pwd' => $member_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;
    }
}
?>