<?php
include_once dirname(__DIR__) . '/settings/config_xui_api.php';
include_once dirname(__DIR__) . '/settings/config_utils.php';
global $connection, $plan_id, $payInfoResult, $user_id, $amount, $botUrl, $gateType, $admin;

        $fid = $plan_id;
        $time = time();

        $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();

        $days = $file_detail['days'];
        $volume = $file_detail['volume'];
        $server_id = $file_detail['server_id'];

        // ✨ فیکس حیاتی: اصلاح خواندن متغیر آرایه دیکد شده درست از فیلد دیتابیس
        $configInfo = json_decode($payInfoResult['description'], true);
        $uuid = $configInfo['uuid'];
        $remark = $configInfo['remark'];
        $isMarzban = $configInfo['marzban'] ?? false;
        $inbound_id = $payInfoResult['volume'];

        if ($isMarzban) {
            $response = editMarzbanConfig($server_id, ['remark' => $remark, 'days' => $days, 'volume' => $volume]);
        }
        else {
            if ($inbound_id > 0)
                $response = editClientTraffic($server_id, $inbound_id, $uuid, $volume, $days, "renew");
            else
                $response = editInboundTraffic($server_id, $uuid, $volume, $days, "renew");
        }

        if (is_null($response) || (isset($response->success) && !$response->success)) {
            showForm('🔻مشکل فنی در اتصال به سرور. تمدید ناموفق بود و وجه به کیف پول واریز شد.', $payDescription);
            $stmt = $connection->prepare("UPDATE `users` SET `wallet` = `wallet` + ? WHERE `userid` = ?");
            $stmt->bind_param("ii", $amount, $user_id); $stmt->execute(); $stmt->close();
            exit;
        }

        // ✨ فیکس: تمدید زمان انقضای کانفیگ در سفارشات لوکال ربات
        $stmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `uuid` = ? AND `server_id` = ?");
        $stmt->bind_param("si", $uuid, $server_id); $stmt->execute();
        $order_detail = $stmt->get_result()->fetch_assoc(); $stmt->close();

        if ($order_detail) {
            $baseExpire = ($order_detail['expire_date'] > $time) ? $order_detail['expire_date'] : $time;
            $new_expire_date = $baseExpire + ($days * 86400);

            $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = ?, `status` = 1 WHERE `uuid` = ? AND `server_id` = ?");
            $stmt->bind_param("isi", $new_expire_date, $uuid, $server_id); $stmt->execute(); $stmt->close();
        }

        $stmt = $connection->prepare("INSERT INTO `increase_order` VALUES (NULL, ?, ?, ?, ?, ?, ?);");
        $stmt->bind_param("iiisii", $user_id, $server_id, $inbound_id, $remark, $amount, $time);
        $stmt->execute(); $stmt->close();

        showForm("✅سرویس $remark با موفقیت تمدید شد", $payDescription, true);

        // ارسال لوکس مشخصات و QR جدید برای کاربر
        if (!empty($uuid)) {
            $safeLink = htmlspecialchars($uuid, ENT_QUOTES, 'UTF-8');
            $acc_text = "✅ تمدید انجام شد\n\n🔮 نام سرویس: $remark\n🔋حجم سرویس: $volume گیگ\n⏰ مدت سرویس: $days روز\n💝 config : <code>$safeLink</code>";

            $file = RandomString() . ".png";
            QRcode::png($uuid, $file, 'L', 11, 0);
            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);
        }

