<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

set_error_handler(function($errno, $errstr, $errfile, $errline) {
    echo "<div style='font-family:monospace; background:#fff0f0; border:1px solid red; padding:15px; margin:10px;'>";
    echo "<b>PHP Error [{$errno}]:</b> {$errstr}<br>";
    echo "<b>File:</b> {$errfile} (Line {$errline})";
    echo "</div>";
    exit();
});

try {
    if (file_exists(__DIR__ . '/../baseInfo.php')) {
        include_once __DIR__ . '/../baseInfo.php';
    } else {
        throw new Exception("File not found: " . __DIR__ . '/../baseInfo.php');
    }

    if (file_exists(__DIR__ . '/../config.php')) {
        include_once __DIR__ . '/../config.php';
    } else {
        throw new Exception("File not found: " . __DIR__ . '/../config.php');
    }

    $time = time();

    if (!isset($connection) || !($connection instanceof mysqli)) {
        throw new Exception("Database connection variable \$connection is not valid.");
    }

// ایجاد جدول gift_list در صورت عدم وجود
$connection->query("CREATE TABLE IF NOT EXISTS `gift_list` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `server_id` int(255) NOT NULL,
  `volume` int(255) NOT NULL,
  `day` int(255) NOT NULL,
  `offset` int(255) NOT NULL DEFAULT 0,
  `message_id` int(255) NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// بررسی و اضافه کردن ستون message_id در صورت عدم وجود
$chkCol = $connection->query("SHOW COLUMNS FROM `gift_list` LIKE 'message_id'");
if ($chkCol && $chkCol->num_rows == 0) {
    $connection->query("ALTER TABLE `gift_list` ADD COLUMN `message_id` INT NULL DEFAULT NULL;");
}

$stmt = $connection->prepare("SELECT * FROM `gift_list` LIMIT 1");
if (!$stmt) {
    echo "OK";
    exit();
}
$stmt->execute();
$giftList = $stmt->get_result();
$stmt->close();

if ($giftList && $giftList->num_rows > 0) {
    $info = $giftList->fetch_assoc();
    $rowId = $info['id'];
    $server_id = $info['server_id'];
    $volume = $info['volume'];
    $day = $info['day'];
    $offset = $info['offset'];

    $stmt = $connection->prepare("SELECT `title` FROM `server_info` WHERE `id` = ?");
    $stmt->bind_param("i", $server_id);
    $stmt->execute();
    $srvInfoRes = $stmt->get_result();
    $serverName = ($srvInfoRes && $srvInfoRes->num_rows > 0) ? $srvInfoRes->fetch_assoc()['title'] : "سرور {$server_id}";
    $stmt->close();

    $stmt = $connection->prepare("SELECT * FROM `server_config` WHERE `id` = ?");
    $stmt->bind_param('i', $server_id);
    $stmt->execute();
    $srvCfgRes = $stmt->get_result();
    $serverConfig = ($srvCfgRes && $srvCfgRes->num_rows > 0) ? $srvCfgRes->fetch_assoc() : null;
    $serverType = $serverConfig['type'] ?? 'normal';
    $stmt->close();

    // استخراج لیست کامل کلاینت‌های مجاز برای هدیه (حذف کانفیگ‌های Gift)
    $validClients = [];
    if ($serverType == "marzban") {
        $usersList = getMarzbanJson($server_id)->users ?? [];
        foreach ($usersList as $config) {
            $remark = $config->username;
            if (stripos($remark, 'Gift') !== false) continue;
            $validClients[] = $config;
        }
    } else {
        include_once __DIR__ . '/config_xui_api.php';
        // ابتدا تلاش از لیست کلاینت‌های سراسری
        $clientsListRes = callXuiApi($serverConfig, '/panel/api/clients/list');
        if ($clientsListRes && isset($clientsListRes->success) && $clientsListRes->success && is_array($clientsListRes->obj)) {
            foreach ($clientsListRes->obj as $c) {
                $email = $c->email ?? '';
                if (stripos($email, 'Gift') !== false) continue;
                $validClients[] = [
                    'email' => $email,
                    'uuid' => $c->uuid ?? ($c->id ?? ($c->password ?? '')),
                    'inbound_id' => $c->inboundId ?? 1,
                    'total' => $c->totalGB ?? 0,
                    'expiryTime' => $c->expiryTime ?? 0,
                    'enable' => $c->enable ?? true,
                    'type' => 'clients_list'
                ];
            }
        } else {
            // فال‌بک به لیست اینباندها
            $response = getJson($server_id)->obj ?? [];
            foreach ($response as $row) {
                $inbound_id = $row->id;
                $settings = json_decode($row->settings ?? '{}', true);
                $clients = $settings['clients'] ?? [];
                foreach ($clients as $client) {
                    $email = $client['email'] ?? '';
                    if (stripos($email, 'Gift') !== false) continue;
                    $validClients[] = [
                        'email' => $email,
                        'uuid' => $client['id'] ?? ($client['password'] ?? ''),
                        'inbound_id' => $inbound_id,
                        'total' => $client['totalGB'] ?? 0,
                        'expiryTime' => $client['expiryTime'] ?? 0,
                        'enable' => $client['enable'] ?? true,
                        'type' => 'inbounds_list'
                    ];
                }
            }
        }
    }

    $totalClients = count($validClients);

    // ثبت یا واکشی آیدی پیام پیشرفت لحظه‌ای
    $progress_msg_id = 0;
    if ($offset == 0) {
        $resMsg = sendMessage("⏳ عملیات هدیه حجم و زمان سرور <b>$serverName</b> شروع شد...\n\n👥 تعداد کل کاربران: <code>$totalClients</code>\n🔄 پردازش شده: <code>0 / $totalClients</code>", null, "HTML", $admin);
        if (is_string($resMsg)) {
            $resDecoded = json_decode($resMsg, true);
            if (isset($resDecoded['result']['message_id'])) $progress_msg_id = $resDecoded['result']['message_id'];
        } elseif (is_object($resMsg)) {
            if (isset($resMsg->result->message_id)) $progress_msg_id = $resMsg->result->message_id;
        } elseif (is_array($resMsg)) {
            if (isset($resMsg['result']['message_id'])) $progress_msg_id = $resMsg['result']['message_id'];
        }
        $connection->query("UPDATE `gift_list` SET `message_id` = $progress_msg_id WHERE `id` = $rowId");
    } else {
        $progress_msg_id = intval($info['message_id'] ?? 0);
    }

    $processed = $offset;
    $found = false;

    // پردازش کلاینت‌ها بر اساس آفست جاری
    for ($i = $offset; $i < count($validClients); $i++) {
        $c = $validClients[$i];
        $found = true;

        $responseEdit = null;
        $orderExistStmt = null;

        if ($serverType == "marzban") {
            $remark = $c->username;
            $total = $c->data_limit;
            $expiry_time = $c->expire;
            $state = $c->status == "active" ? true : false;

            $applyVolume = ($volume > 0 && $total > 0) ? ($volume / 1024) : 0;
            $applyDay = ($day > 0 && $expiry_time > 0) ? $day : 0;

            if (($applyVolume > 0 || $applyDay > 0) && $state) {
                $responseEdit = editMarzbanConfig($server_id, ['remark' => $remark, 'plus_volume' => $applyVolume, 'plus_day' => $applyDay]);
            }

            if ($responseEdit) {
                $orderExistStmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `server_id` = ? AND `inbound_id` = 0 AND `remark` = ?");
                $orderExistStmt->bind_param("is", $server_id, $remark);
            }
        } else {
            $email = $c['email'];
            $uuid = $c['uuid'];
            $inbound_id = $c['inbound_id'];
            $clientTotal = $c['total'];
            $clientExpiry = $c['expiryTime'];
            $clientEnable = $c['enable'];

            $applyVolume = ($volume > 0 && $clientTotal > 0) ? ($volume / 1024) : 0;
            $applyDay = ($day > 0 && $clientExpiry > 0) ? $day : 0;

            if (($applyVolume > 0 || $applyDay > 0) && $clientEnable) {
                $responseEdit = editClientTraffic($server_id, $inbound_id, $uuid, $applyVolume, $applyDay);
                $orderExistStmt = $connection->prepare("SELECT * FROM `orders_list` WHERE `server_id` = ? AND `inbound_id` = ? AND `uuid` = ?");
                $orderExistStmt->bind_param("iis", $server_id, $inbound_id, $uuid);
            }
        }

        if (!is_null($responseEdit) && $orderExistStmt) {
            $orderExistStmt->execute();
            $orderExist = $orderExistStmt->get_result();
            $orderExistStmt->close();

            if ($orderExist->num_rows > 0) {
                $orderInfo = $orderExist->fetch_assoc();
                $orderId = $orderInfo['id'];
                $user_id = $orderInfo['userid'];
                $gift = "";
                if ($volume != 0) $gift = "$volume مگابایت حجم ";
                if ($day != 0) {
                    $expire_date = $day * 86400;
                    $gift .= " و $day روز زمان";
                    $stmt = $connection->prepare("UPDATE `orders_list` SET `expire_date` = `expire_date` + ? WHERE `id` = ?");
                    $stmt->bind_param("ii", $expire_date, $orderId);
                    $stmt->execute();
                    $stmt->close();
                }

                $clientRemark = $serverType == "marzban" ? $remark : $email;
                sendMessage("به اشتراک $clientRemark شما $gift اضافه شد", null, null, $user_id);
            }
        }

        $processed++;

        $stmt = $connection->prepare("UPDATE `gift_list` SET `offset` = `offset` + 1 WHERE `id` = ?");
        $stmt->bind_param("i", $rowId);
        $stmt->execute();
        $stmt->close();

        // ادیت پیام پیشرفت هر ۵ کاربر یک‌بار یا در گام آخر جهت بهینه‌سازی تعداد ریکوئست‌ها
        if ($progress_msg_id > 0 && ($processed % 5 == 0 || $processed == $totalClients)) {
            $progressMsg = "⏳ عملیات هدیه حجم و زمان سرور <b>$serverName</b> در حال اجراست...\n\n👥 تعداد کل کاربران: <code>$totalClients</code>\n🔄 پردازش شده: <code>$processed / $totalClients</code>";
            bot('editMessageText', [
                'chat_id' => $admin,
                'message_id' => $progress_msg_id,
                'text' => $progressMsg,
                'parse_mode' => 'HTML'
            ]);
        }
    }

    if ($found == false) {
        $stmt = $connection->prepare("DELETE FROM `gift_list` WHERE `id` = ?");
        $stmt->bind_param("i", $rowId);
        $stmt->execute();
        $stmt->close();

        if ($progress_msg_id > 0) {
            $progressMsg = "✅ عملیات هدیه حجم و زمان سرور <b>$serverName</b> به اتمام رسید.\n\n👥 تعداد کل کاربران: <code>$totalClients</code>\n🔄 پردازش شده: <code>$totalClients / $totalClients</code>";
            bot('editMessageText', [
                'chat_id' => $admin,
                'message_id' => $progress_msg_id,
                'text' => $progressMsg,
                'parse_mode' => 'HTML'
            ]);
        } else {
            sendMessage("✅ عملیات هدیه حجم و زمان سرور $serverName به اتمام رسید", null, null, $admin);
        }
    }
}
echo "OK";

} catch (Throwable $e) {
    echo "<div style='font-family:monospace; background:#fff0f0; border:1px solid red; padding:15px; margin:10px;'>";
    echo "<h3 style='color:red; margin-top:0;'>Fatal Error Caught</h3>";
    echo "<b>Message:</b> " . htmlspecialchars($e->getMessage()) . "<br>";
    echo "<b>File:</b> " . htmlspecialchars($e->getFile()) . " (Line " . $e->getLine() . ")<br>";
    echo "<pre style='background:#f5f5f5; padding:10px; border:1px solid #ccc;'>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
    echo "</div>";
}
