<?php
global $connection, $plan_id, $user_id, $volume, $days, $amount, $payParam, $botState, $description, $botUrl, $admin, $mainValues, $agentBought;

$fid = $plan_id;
$acctxt = '';

$stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$userinfo = $stmt->get_result()->fetch_assoc();
$stmt->close();

$stmt = $connection->prepare("SELECT * FROM `server_plans` WHERE `id`=?");
$stmt->bind_param("i", $fid);
$stmt->execute();
$file_detail = $stmt->get_result()->fetch_assoc();
$stmt->close();

if ($volume == 0 && $days == 0) {
    $volume = $file_detail['volume'];
    $days = $file_detail['days'];
}

$date = time();
$expire_microdate = ($days > 0) ? floor(microtime(true) * 1000) + (864000 * $days * 100) : 0;
$expire_date = ($days > 0) ? $date + (86400 * $days) : 0;

$server_id = $file_detail['server_id'];
$protocol = $file_detail['protocol'];
$inbound_id_raw = $file_detail['inbound_id']; // تغییر مهم برای مولتی اینباند
$limitip = $file_detail['limitip'];
$rahgozar = $file_detail['rahgozar'];

$accountCount = $payParam['agent_count'] != 0 ? $payParam['agent_count'] : 1;
$eachPrice = $amount / $accountCount;

// تبدیل اینباندهای دیتابیس به آرایه (پشتیبانی ۱۰۰٪ از مولتی اینباند)
if (strpos($inbound_id_raw, '[') !== false || strpos($inbound_id_raw, ',') !== false) {
    $inboundIdsArray = array_map('intval', explode(',', str_replace(['[', ']'], '', $inbound_id_raw)));
} else {
    $inboundIdsArray = [intval($inbound_id_raw)];
}
if (empty($inboundIdsArray) || $inboundIdsArray[0] == 0) $inboundIdsArray = [1];
$inbound_id_db = $inboundIdsArray[0];

$stmt = $connection->prepare("SELECT * FROM `server_info` WHERE `id`=?");
$stmt->bind_param("i", $server_id);
$stmt->execute();
$serverInfo = $stmt->get_result()->fetch_assoc();
$srv_remark = $serverInfo['remark'];
$serverTitle = $serverInfo['title'];
$stmt->close();

$stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id`=?");
$stmt->bind_param("i", $server_id);
$stmt->execute();
$server_info = $stmt->get_result()->fetch_assoc();
$serverType = $server_info['type'];
$panelUrl = rtrim($server_info['panel_url'], '/');
$apiToken = trim($server_info['password']);
$stmt->close();

sendMessage("⏳ پرداخت تایید شد. در حال آماده‌سازی سرویس و صدور لایسنس... لطفاً چند لحظه صبر کنید.", null, null, $user_id);

define('IMAGE_WIDTH', 540);
define('IMAGE_HEIGHT', 540);

for ($i = 1; $i <= $accountCount; $i++) {
    if ($botState['remark'] == "digits") {
        $rnd = rand(10000, 99999);
        $remark = "{$srv_remark}-{$rnd}";
    } elseif ($botState['remark'] == "manual") {
        $remark = $description;
    } else {
        $rnd = rand(1111, 99999);
        $remark = "{$srv_remark}-{$user_id}-{$rnd}";
    }
    if (!empty($description)) $remark = $description;
    if ($accountCount > 1) $remark .= "-$i";

    $finalEmail = $remark . "@tg.com";
    $volumeBytes = $volume * 1073741824;
    $expiryTimestamp = ($days > 0) ? (time() + ($days * 86400)) * 1000 : 0;

    $configLinks = [];
    $clientSubId = "";
    $clientUuid = "";

    if ($serverType == "marzban") {
        $response = addMarzbanUser($server_id, $remark, $volume, $days, $fid);
        if (is_object($response) && isset($response->sub_link)) {
            $configLinks[] = $panelUrl . $response->sub_link;
            $clientSubId = $clientUuid = str_replace("/sub/", "", $response->sub_link);
        }
    } else {
        // متد API نسخه 3.1.0 سنایی (جایگزین تابع قدیمی و کرش‌دار addInboundAccount)
        $groupName = determineClientGroup($finalEmail);
        $postData = [
            "client" => [
                "email" => $finalEmail,
                "totalGB" => $volumeBytes,
                "expiryTime" => $expiryTimestamp,
                "tgId" => intval($user_id),
                "limitIp" => $limitip,
                "enable" => true,
                "group_name" => $groupName,
                "groupName" => $groupName,
                "group" => $groupName
            ],
            "inboundIds" => $inboundIdsArray
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $panelUrl . '/panel/api/clients/add');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
        $raw_res = curl_exec($ch);
        curl_close($ch);

        $resDec = json_decode($raw_res, true);

        if (isset($resDec['success']) && $resDec['success'] == true) {
            $getClientUrl = $panelUrl . "/panel/api/clients/get/" . urlencode($finalEmail);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $getClientUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
            $clientRes = curl_exec($ch);
            curl_close($ch);

            $clientDecoded = json_decode($clientRes, true);
            if (isset($clientDecoded['success']) && $clientDecoded['success'] && isset($clientDecoded['obj']['client'])) {
                $clientSubId = $clientDecoded['obj']['client']['subId'] ?? "";
                $clientUuid = $clientDecoded['obj']['client']['id'] ?? "";
            }

            $subUrl = $panelUrl . "/panel/api/clients/links/" . urlencode($finalEmail);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $subUrl);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer ' . $apiToken]);
            $subRes = curl_exec($ch);
            curl_close($ch);
            $subDec = json_decode($subRes, true);

            if (isset($subDec['success']) && $subDec['success'] && isset($subDec['obj'])) {
                $rawObj = $subDec['obj'];
                if (is_array($rawObj)) {
                    foreach ($rawObj as $val) {
                        if (is_array($val)) {
                            foreach ($val as $subVal) {
                                if (is_string($subVal)) $configLinks[] = $subVal;
                            }
                        } elseif (is_string($val)) {
                            $configLinks[] = $val;
                        }
                    }
                }
            }
        }
    }

    // فیکس مشکل اسپم پیام‌ها: استخراج فقط لینک اول برای تولید بارکد
    $firstLink = "";
    if (!empty($configLinks)) {
        $firstLink = $configLinks[0];
    } else {
        $firstLink = "vless://{$clientUuid}@" . parse_url($panelUrl, PHP_URL_HOST) . ":2096?type=tcp&security=none#{$remark}";
        $configLinks[] = $firstLink;
    }

    $token = $clientSubId;
    $parsedPanelUrl = parse_url($panelUrl);
    $panelHost = $parsedPanelUrl['host'] ?? '';
    $panelScheme = $parsedPanelUrl['scheme'] ?? 'https';
    $subLink = "{$panelScheme}://{$panelHost}:2096/sub/{$clientSubId}";

    // ساخت یک فاکتور متنی واحد برای جلوگیری از ارسال چندباره
    $acc_text = "
😍 <b>سفارش جدید شما با موفقیت صادر شد</b>
📡 پروتکل: <code>$protocol</code>
🔮 نام سرویس: <code>$remark</code>
🔋حجم سرویس: <code>$volume گیگ</code>
⏰ مدت سرویس: <code>$days روز</code>

💝 <b>config 1:</b> <code>$firstLink</code>

🔗 <b>لینک اشتراک هوشمند (شامل تمامی کانفیگ‌ها):</b>
<code>$subLink</code>

⚠️ <b>آموزش:</b> لینک اشتراک بالا را کپی کرده و در نرم‌افزار (V2RayNG / V2Box) گزینه Update Subscription را بزنید.

🔋 مشاهده آنلاین حجم: 
<code>{$botUrl}search.php?id={$clientSubId}</code>
";

    include_once '../phpqrcode/qrlib.php';
    $file = RandomString() . ".png";
    // ایجاد بارکد منحصراً برای لینک اینباند اول
    QRcode::png($firstLink, $file, 'L', 10, 2);

    if (function_exists('addBorderImage')) addBorderImage($file);

    if (file_exists(dirname(__DIR__) . "/settings/QRCode.jpg")) {
        $backgroundImage = imagecreatefromjpeg(dirname(__DIR__) . "/settings/QRCode.jpg");
        $qrImage = imagecreatefrompng($file);
        $qrWidth = imagesx($qrImage); $qrHeight = imagesy($qrImage);
        $newWidth = round($qrWidth * 1.5); $newHeight = round($qrHeight * 1.5);
        $startX = round((imagesx($backgroundImage) - $newWidth) / 2);
        $startY = round(300 - ($newHeight - $qrHeight) / 2);
        imagecopyresampled($backgroundImage, $qrImage, $startX, $startY, 0, 0, $newWidth, $newHeight, $qrWidth, $qrHeight);
        imagepng($backgroundImage, $file);
        imagedestroy($backgroundImage);
        imagedestroy($qrImage);
    }

    // ارسال فقط یـک پیام عکس‌دار نهایی
    sendPhoto($file, $acc_text, json_encode(['inline_keyboard' => [[['text' => "صفحه اصلی 🏘", 'callback_data' => "mainMenu"]]]]), "HTML", $user_id);
    if (file_exists($file)) @unlink($file);

    $linkForDb = json_encode($configLinks, JSON_UNESCAPED_UNICODE);

    $stmt = $connection->prepare("INSERT INTO `orders_list` 
                (`userid`, `token`, `transid`, `fileid`, `server_id`, `inbound_id`, `remark`, `uuid`, `protocol`, `expire_date`, `link`, `amount`, `status`, `date`, `notif`, `rahgozar`, `agent_bought`)
                VALUES (?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, 0, ?, ?);");
    $stmt->bind_param("ssiiisssisiiii", $user_id, $token, $fid, $server_id, $inbound_id_db, $remark, $clientSubId, $protocol, $expire_date, $linkForDb, $eachPrice, $date, $rahgozar, $agentBought);
    $stmt->execute();
    $stmt->close();
}

// پورسانت نماینده
$stmt = $connection->prepare("SELECT * FROM `users` WHERE `userid` = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user_detail = $stmt->get_result()->fetch_assoc();
$stmt->close();

if ($user_detail['refered_by'] != null) {
    $stmt = $connection->prepare("SELECT `value` FROM `setting` WHERE `type` = 'INVITE_BANNER_AMOUNT'");
    $stmt->execute();
    $inviteAmount = $stmt->get_result()->fetch_assoc()['value'] ?? 0;
    $stmt->close();

    $inviterId = $user_detail['refered_by'];
    $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
    $stmt->bind_param("ii", $inviteAmount, $inviterId);
    $stmt->execute();
    $stmt->close();

    sendMessage("🎉 تبریک! یکی از زیرمجموعه‌های شما خرید انجام داد و شما مبلغ " . number_format($inviteAmount) . " تومان جایزه دریافت کردید.", null, null, $inviterId);
}

$stmt = $connection->prepare("UPDATE `server_info` SET `ucount` = `ucount` - ? WHERE `id`=?");
$stmt->bind_param("ii", $accountCount, $server_id);
$stmt->execute();
$stmt->close();

$keys = json_encode(['inline_keyboard' => [[['text' => "بنازم خرید جدید 💸❤️", 'callback_data' => "NetFreedomVPN"]]]]);
$msgAdmin = str_replace(
    ['SERVERNAME', 'TYPE', 'USER-ID', 'USERNAME', 'NAME', 'PRICE', 'REMARK', 'VOLUME', 'DAYS'],
    [$serverTitle, 'درگاه آنلاین', $user_id, $user_detail['username'], $user_detail['name'], $amount, $remark, $volume, $days],
    $mainValues['buy_new_account_request']
);
sendMessage($msgAdmin, $keys, "html", $admin);
