<?php
chdir(__DIR__);
require "../configs/configs.php";
require "../libs/functions.php";
$currentTime        = time();
$fortyEightHoursAgo = $currentTime - (48 * 3600);
$stmt = $pdo->prepare("
    SELECT `order_id`
    FROM `orders`
    WHERE `status` IN ('running','pending')
      AND `created_at` <= FROM_UNIXTIME(?)
      AND `members_done` < (`members_count` / 2)
    ORDER BY `created_at` ASC
    LIMIT 10
");
$stmt->execute([$fortyEightHoursAgo]);
$orderIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

if(!empty($orderIds)) {

foreach($orderIds as $orderId) {
        $orderId = intval($orderId);

if($orderId <= 0) continue;
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT * FROM `orders` WHERE `order_id` = ? FOR UPDATE");
            $stmt->execute([$orderId]);
            $order = $stmt->fetch();

if(
                !$order ||
                !in_array($order->status, ['running', 'pending'], true) ||
                strtotime($order->created_at) > $fortyEightHoursAgo ||
                floatval($order->members_done) >= (floatval($order->members_count) / 2)
            ) {
                $pdo->rollBack();
                continue;
}

            $refund = calcOrderCancelRefund($order);
            $refundTotal = floatval($refund['total_refund']);
            $refundBase = floatval($refund['base_refund']);
            $refundExtra = floatval($refund['extra_refund']);

if($refundTotal > 0) {
                $refundStmt = $pdo->prepare("UPDATE `users` SET `coins` = `coins` + ? WHERE `user_id` = ?");
                $refundStmt->execute([$refundTotal, $order->user_id]);
}

            $cancelStmt = $pdo->prepare("UPDATE `orders` SET `status` = 'cancelled', `finished_at` = NOW() WHERE `order_id` = ? AND `status` IN ('running','pending')");
            $cancelStmt->execute([$orderId]);

if($cancelStmt->rowCount() <= 0) {
                $pdo->rollBack();
                continue;
}

            $pdo->commit();
            $requestedCount = intval($order->members_count);
            $doneCount = intval($order->members_done);
            $remainingMembers = $refund['remaining'];
            $channelNameReport = $order->channel_name;
            $responseText = "⏰ *سفارش شما به صورت خودکار لغو شد*\n\n" .
                "📋 شماره سفارش: *#$orderId*\n" .
                "📢 کانال: *$channelNameReport*\n\n" .
                "👥 تعداد درخواستی: *$requestedCount* ممبر\n" .
                "✅ انجام شده: *$doneCount* ممبر\n" .
                "⏸️ باقیمانده: *$remainingMembers* ممبر\n\n" .
                "💰 بازگشت بابت اعضای انجام‌نشده: *" . formatCoins($refundBase) . "* سکه\n" .
                ($refundExtra > 0 ? ("🚀 بازگشت بابت بوست/هزینه اضافه: *" . formatCoins($refundExtra) . "* سکه\n") : "") .
                "🧾 مجموع بازگشت: *" . formatCoins($refundTotal) . "* سکه\n\n" .
                "دلیل: بیش از ۴۸ ساعت از ثبت سفارش گذشته و کمتر از ۵۰٪ سفارش انجام شده است.";
            sendMessage($order->user_id, $responseText);
} catch (Exception $e) {

if($pdo && $pdo->inTransaction()) {
                $pdo->rollBack();
}

}

}

}

