<?php
// marzban_api.php - توابع کامل پنل مرزبان

function marzban_generate_uuid() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

function marzban_get_token($url, $username, $password) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, rtrim($url, '/') . '/api/admin/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'username' => $username,
        'password' => $password
    ]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded',
        'Accept: application/json'
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code == 200) {
        $data = json_decode($response, true);
        return $data['access_token'] ?? null;
    }
    return null;
}

function marzban_call_api($url, $token, $method = 'GET', $data = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $headers = ['Accept: application/json', 'Authorization: Bearer ' . $token];
    
    if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            $headers[] = 'Content-Type: application/json';
        }
    } elseif ($method == 'PUT') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            $headers[] = 'Content-Type: application/json';
        }
    } elseif ($method == 'DELETE') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    }
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return ['code' => $http_code, 'body' => json_decode($response, true)];
}

// 1. ساخت سرویس
function marzban_create_client($panel, $username, $volume_gb, $days, $selected_inbounds = null) {
    $token = marzban_get_token($panel['url'], $panel['marzban_username'], $panel['marzban_password']);
    if (!$token) return ['success' => false, 'msg' => 'خطا در دریافت توکن'];
    
    $data_limit = $volume_gb * 1024 * 1024 * 1024;
    $expire = ($days > 0) ? time() + ($days * 86400) : 0;
    
    $inbounds_list = $selected_inbounds ?: (isset($panel['selected_inbounds']) ? json_decode($panel['selected_inbounds'], true) : []);
    $proxies = [];
    $inbounds_config = [];
    
    foreach ($inbounds_list as $tag) {
        $tag_lower = strtolower($tag);
        if (strpos($tag_lower, 'vmess') !== false) {
            if (!isset($proxies['vmess'])) {
                $proxies['vmess'] = ['id' => marzban_generate_uuid()];
                $inbounds_config['vmess'] = [];
            }
            $inbounds_config['vmess'][] = $tag;
        } elseif (strpos($tag_lower, 'vless') !== false) {
            if (!isset($proxies['vless'])) {
                $proxies['vless'] = ['id' => marzban_generate_uuid(), 'flow' => ''];
                $inbounds_config['vless'] = [];
            }
            $inbounds_config['vless'][] = $tag;
        } elseif (strpos($tag_lower, 'trojan') !== false) {
            if (!isset($proxies['trojan'])) {
                $proxies['trojan'] = ['password' => bin2hex(random_bytes(16))];
                $inbounds_config['trojan'] = [];
            }
            $inbounds_config['trojan'][] = $tag;
        } elseif (strpos($tag_lower, 'shadowsocks') !== false) {
            if (!isset($proxies['shadowsocks'])) {
                $proxies['shadowsocks'] = ['password' => bin2hex(random_bytes(16)), 'method' => 'chacha20-ietf-poly1305'];
                $inbounds_config['shadowsocks'] = [];
            }
            $inbounds_config['shadowsocks'][] = $tag;
        }
    }
    
    $data = [
        'username' => $username,
        'data_limit' => $data_limit,
        'expire' => $expire,
        'status' => 'active',
        'proxies' => $proxies,
        'inbounds' => $inbounds_config,
        'data_limit_reset_strategy' => 'no_reset'
    ];
    
    $result = marzban_call_api(rtrim($panel['url'], '/') . '/api/user', $token, 'POST', $data);
    
    if ($result['code'] == 200 || $result['code'] == 201) {
        $user = $result['body'];
        
        // فقط و فقط از subscription_url خود مرزبان استفاده کن
        return [
            'success' => true,
            'uuid' => $user['proxies']['vmess']['id'] ?? $user['proxies']['vless']['id'] ?? '',
            'subId' => $username,
            'sub_link' => $user['subscription_url']  // همین خط کافیه
        ];
    }
    
    return ['success' => false, 'msg' => 'خطا در ساخت سرویس: ' . json_encode($result['body'])];
}

// 2. دریافت اطلاعات کاربر
function marzban_get_client_info($panel, $username) {
    $token = marzban_get_token($panel['url'], $panel['marzban_username'], $panel['marzban_password']);
    if (!$token) return ['success' => false, 'msg' => 'خطا در دریافت توکن'];
    
    $result = marzban_call_api(rtrim($panel['url'], '/') . '/api/user/' . $username, $token, 'GET');
    
    if ($result['code'] == 200 && $result['body']) {
        $user = $result['body'];
        return [
            'success' => true,
            'obj' => [
                'totalGB' => $user['data_limit'] ?? 0,
                'total' => $user['data_limit'] ?? 0,
                'up' => $user['used_traffic'] ?? 0,
                'down' => 0,
                'uuid' => $user['proxies']['vmess']['id'] ?? $user['proxies']['vless']['id'] ?? '',
                'enable' => $user['status'] == 'active',
                'expiryTime' => ($user['expire'] ?? 0) * 1000
            ]
        ];
    }
    
    return ['success' => false, 'msg' => 'کاربر یافت نشد'];
}

// 3. افزایش حجم (بدون ریست)
function marzban_add_volume($panel, $username, $extra_gb) {
    $token = marzban_get_token($panel['url'], $panel['marzban_username'], $panel['marzban_password']);
    if (!$token) return false;
    
    $info = marzban_get_client_info($panel, $username);
    if (!$info['success']) return false;
    
    $current_limit = $info['obj']['totalGB'];
    $extra_bytes = $extra_gb * 1024 * 1024 * 1024;
    
    if ($current_limit == 0) {
        $new_limit = $extra_bytes;
    } else {
        $new_limit = $current_limit + $extra_bytes;
    }
    
    $data = ['data_limit' => $new_limit];
    $result = marzban_call_api(rtrim($panel['url'], '/') . '/api/user/' . $username, $token, 'PUT', $data);
    
    return ($result['code'] == 200 || $result['code'] == 204);
}

// 4. تمدید سرویس (ریست مصرف + حجم جدید + زمان جدید)
function marzban_renew_service($panel, $username, $new_volume_gb, $new_days) {
    $token = marzban_get_token($panel['url'], $panel['marzban_username'], $panel['marzban_password']);
    if (!$token) return false;
    
    $new_data_limit = $new_volume_gb * 1024 * 1024 * 1024;
    $new_expire = ($new_days > 0) ? time() + ($new_days * 86400) : 0;
    
    $data = [
        'data_limit' => $new_data_limit,
        'expire' => $new_expire,
        'used_traffic' => 0
    ];
    
    $result = marzban_call_api(rtrim($panel['url'], '/') . '/api/user/' . $username, $token, 'PUT', $data);
    
    return ($result['code'] == 200 || $result['code'] == 204);
}

// 5. تغییر وضعیت (فعال/غیرفعال)
function marzban_toggle_status($panel, $username, $status) {
    $token = marzban_get_token($panel['url'], $panel['marzban_username'], $panel['marzban_password']);
    if (!$token) return ['success' => false, 'msg' => 'خطا در دریافت توکن'];
    
    $data = ['status' => $status];
    $result = marzban_call_api(rtrim($panel['url'], '/') . '/api/user/' . $username, $token, 'PUT', $data);
    
    if ($result['code'] == 200 || $result['code'] == 204) {
        return ['success' => true];
    }
    return ['success' => false, 'msg' => 'خطا در تغییر وضعیت'];
}

// 6. حذف سرویس
function marzban_delete_service($panel, $username) {
    $token = marzban_get_token($panel['url'], $panel['marzban_username'], $panel['marzban_password']);
    if (!$token) return false;
    
    $result = marzban_call_api(rtrim($panel['url'], '/') . '/api/user/' . $username, $token, 'DELETE');
    
    return ($result['code'] == 200 || $result['code'] == 204);
}
?>