<?php
/**
 * VIP Account Creator API Endpoint
 * این فایل باید روی سرور VPS (همون سروری که X-UI روی اون هست) قرار بگیره
 * مسیر پیشنهادی: /var/www/api/create_vip_account.php
 */

// تنظیمات امنیتی
define('API_SECRET_KEY', 'apn_vip_2024_secure_key_xyz123');

// تنظیمات پنل X-UI (روی localhost چون روی همون سرور هستیم)
define('XUI_PANEL_URL', 'https://127.0.0.1:2083/aHfvIoyNWcxlOfBfje');
define('XUI_USERNAME', 'parisa');
define('XUI_PASSWORD', '@230902Parisa');

header('Content-Type: application/json');

// بررسی متد درخواست
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// بررسی API Key
$apiKey = '';

// سعی در دریافت از header های مختلف
if (function_exists('getallheaders')) {
    $headers = getallheaders();
    $apiKey = $headers['X-API-Key'] ?? $headers['X-Api-Key'] ?? '';
}

// اگر نبود، از $_SERVER امتحان کن
if (empty($apiKey)) {
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
}

// در نهایت از POST
if (empty($apiKey)) {
    $apiKey = $_POST['api_key'] ?? '';
}

if ($apiKey !== API_SECRET_KEY) {
    http_response_code(403);
    echo json_encode([
        'success' => false, 
        'error' => 'Invalid API key',
        'debug' => 'Received: ' . substr($apiKey, 0, 10) . '...'
    ]);
    exit;
}

// دریافت داده‌ها
$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

$action = $input['action'] ?? '';
$user_id = $input['user_id'] ?? 0;
$plan_id = $input['plan_id'] ?? '';
$volume_gb = $input['volume_gb'] ?? 0;
$days = $input['days'] ?? 30;
$limit_ip = $input['limit_ip'] ?? 1;

// کلاس X-UI API (نسخه ساده شده)
class XUI_API {
    private $panel_url;
    private $username;
    private $password;
    private $session_cookie;
    
    public function __construct($panel_url, $username, $password) {
        $this->panel_url = rtrim($panel_url, '/');
        $this->username = $username;
        $this->password = $password;
    }
    
    public function login() {
        $url = $this->panel_url . '/login';
        $data = [
            'username' => $this->username,
            'password' => $this->password
        ];
        
        $response = $this->makeRequest('POST', $url, $data, false);
        return ($response && isset($response['success']) && $response['success']);
    }
    
    public function findVlessInbound() {
        $inbounds = $this->getInbounds();
        if (!$inbounds) return null;
        
        foreach ($inbounds as $inbound) {
            if (strtolower($inbound['protocol']) === 'vless') {
                return $inbound;
            }
        }
        return null;
    }
    
    public function getInbounds() {
        $url = $this->panel_url . '/panel/api/inbounds/list';
        $response = $this->makeRequest('GET', $url);
        
        if ($response && isset($response['success']) && $response['success']) {
            return $response['obj'];
        }
        return null;
    }
    
    public function addClient($inbound_id, $email, $total_gb, $expire_days, $limit_ip = 0) {
        $total_bytes = $total_gb * 1024 * 1024 * 1024;
        $expire_time = ($expire_days > 0) ? (time() + ($expire_days * 86400)) * 1000 : 0;
        $uuid = $this->generateUUID();
        
        $client_data = [
            'id' => $uuid,
            'alterId' => 0,
            'email' => $email,
            'limitIp' => (int)$limit_ip,
            'totalGB' => (int)$total_bytes,
            'expiryTime' => (int)$expire_time,
            'enable' => true,
            'tgId' => '',
            'subId' => bin2hex(random_bytes(8)),
            'reset' => 0
        ];
        
        $settings = ['clients' => [$client_data]];
        $data = [
            'id' => (int)$inbound_id,
            'settings' => json_encode($settings)
        ];
        
        $url = $this->panel_url . '/panel/api/inbounds/addClient';
        $response = $this->makeRequest('POST', $url, $data);
        
        if ($response && isset($response['success']) && $response['success']) {
            return [
                'success' => true,
                'uuid' => $uuid,
                'email' => $email,
                'subId' => $client_data['subId']
            ];
        }
        return null;
    }
    
    public function getClientLink($inbound_id, $email, $uuid) {
        $inbound = $this->getInboundById($inbound_id);
        if (!$inbound) return null;
        
        $stream_settings = json_decode($inbound['streamSettings'], true);
        $network = $stream_settings['network'] ?? 'tcp';
        
        // استفاده از IP سرور
        $address = '82.115.26.209';
        $port = $inbound['port'];
        
        $params = [
            'type' => $network,
            'security' => $stream_settings['security'] ?? 'none',
            'encryption' => 'none'
        ];
        
        if ($network === 'ws') {
            $params['path'] = $stream_settings['wsSettings']['path'] ?? '/';
            $params['host'] = $stream_settings['wsSettings']['headers']['Host'] ?? '';
        }
        
        $query = http_build_query($params);
        return "vless://{$uuid}@{$address}:{$port}?{$query}#{$email}";
    }
    
    private function getInboundById($inbound_id) {
        $inbounds = $this->getInbounds();
        if (!$inbounds) return null;
        
        foreach ($inbounds as $inbound) {
            if ($inbound['id'] == $inbound_id) {
                return $inbound;
            }
        }
        return null;
    }
    
    private function makeRequest($method, $url, $data = null, $use_cookie = true) {
        $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);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $cookie_file = sys_get_temp_dir() . '/xui_session.txt';
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            }
        }
        
        curl_setopt($ch, CURLOPT_HEADER, true);
        $response = curl_exec($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $body = substr($response, $header_size);
        curl_close($ch);
        
        return json_decode($body, true);
    }
    
    private function generateUUID() {
        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)
        );
    }
}

// پردازش درخواست
try {
    if ($action === 'create_account') {
        // ساخت اکانت
        $email = "user_{$user_id}_{$plan_id}_" . substr(md5(uniqid()), 0, 6);
        
        $xui = new XUI_API(XUI_PANEL_URL, XUI_USERNAME, XUI_PASSWORD);
        
        if (!$xui->login()) {
            throw new Exception('Failed to login to panel');
        }
        
        $inbound = $xui->findVlessInbound();
        if (!$inbound) {
            throw new Exception('No VLESS inbound found');
        }
        
        $result = $xui->addClient($inbound['id'], $email, $volume_gb, $days, $limit_ip);
        
        if (!$result) {
            throw new Exception('Failed to create account');
        }
        
        $link = $xui->getClientLink($inbound['id'], $email, $result['uuid']);
        
        echo json_encode([
            'success' => true,
            'data' => [
                'email' => $email,
                'uuid' => $result['uuid'],
                'inbound_id' => $inbound['id'],
                'vless_link' => $link,
                'volume_gb' => $volume_gb,
                'days' => $days,
                'expire_date' => date('Y-m-d', time() + ($days * 86400))
            ]
        ]);
        
    } elseif ($action === 'test_connection') {
        // تست اتصال
        $xui = new XUI_API(XUI_PANEL_URL, XUI_USERNAME, XUI_PASSWORD);
        
        if ($xui->login()) {
            $inbound = $xui->findVlessInbound();
            echo json_encode([
                'success' => true,
                'message' => 'Connection successful',
                'vless_inbound' => $inbound ? 'Found' : 'Not found'
            ]);
        } else {
            throw new Exception('Login failed');
        }
        
    } else {
        throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
