<?php
/**
 * Auto-extracted module from the old large bot.php.
 * Loaded by bot.php in the original execution order.
 */
function send_order_post_to_user($chatID, $userID, $orderId, $Button_Home = null){
    global $chads;
    $orderId = preg_replace('/[^A-Za-z0-9_\-]/', '', (string)$orderId);
    if($orderId === '' || !bot_data_file_exists("ads/$orderId.json")){
        SM($chatID,"👈🏻 کد پیگیری سفارش نامعتبر میباشد",'html',null,$Button_Home);
        return false;
    }
    $order = bot_data_get_json("ads/$orderId.json");
    if(!is_array($order)){
        SM($chatID,"👈🏻 اطلاعات سفارش قابل خواندن نیست",'html',null,$Button_Home);
        return false;
    }
    if((string)$userID !== (string)($order['admin'] ?? $order['owner_id'] ?? '')){
        SM($chatID,"👈🏻 این سفارش متعلق به شما نمیباشد",'html',null,$Button_Home);
        return false;
    }

    $postId = (int)($order['postid'] ?? $order['post_message_id'] ?? $order['message_id'] ?? 0);
    if($postId <= 0){
        SM($chatID,"❌ شناسه پست سفارش داخل فایل سفارش ذخیره نشده است.",'html',null,$Button_Home);
        return false;
    }

    $sources = function_exists('bot_telegram_order_source_candidates') ? bot_telegram_order_source_candidates($order) : [];
    if(!$sources && trim((string)$chads) !== ''){
        $sources[] = preg_match('/^-?\d+$/', trim((string)$chads)) ? trim((string)$chads) : '@'.trim((string)$chads, '@/ ');
    }

    $errors = [];
    foreach($sources as $sourceChat){
        $res = bot('forwardMessage', [
            'chat_id' => $chatID,
            'from_chat_id' => $sourceChat,
            'message_id' => $postId,
        ]);
        if(isset($res->ok) && $res->ok){
            return true;
        }
        $errors[] = 'forward '.$sourceChat.': '.(string)($res->description ?? 'unknown');

        // Some channels disallow forwarding or Telegram may reject the forward.
        // copyMessage still shows the same order post to the user without changing channel content.
        $copy = bot('copyMessage', [
            'chat_id' => $chatID,
            'from_chat_id' => $sourceChat,
            'message_id' => $postId,
        ]);
        if(isset($copy->ok) && $copy->ok){
            return true;
        }
        $errors[] = 'copy '.$sourceChat.': '.(string)($copy->description ?? 'unknown');
    }

    $logDir = defined('BOT_ROOT_DIR') ? BOT_ROOT_DIR.'/cache' : dirname(__DIR__, 2).'/cache';
    if(!is_dir($logDir)) @mkdir($logDir, 0755, true);
    @file_put_contents($logDir.'/order_view_forward_errors.log', date('Y-m-d H:i:s').' | order='.$orderId.' | post='.$postId.' | '.implode(' | ', $errors)."\n", FILE_APPEND);

    $money = $GLOBALS['money'] ?? 'الماس';
    $summary = function_exists('bale_order_card_text') ? bale_order_card_text($orderId, $order, $money) : "📦 سفارش #{$orderId}";
    $summary .= "\n\n⚠️ پست اصلی سفارش قابل فوروارد/کپی نبود. احتمالاً پست کانال تبلیغات حذف شده، دسترسی ربات قطع شده یا شناسه کانال تبلیغات تغییر کرده است.";

    $buttons = [];
    $sourceForLink = '';
    foreach($sources as $src){ if(strpos((string)$src, '@') === 0){ $sourceForLink = substr((string)$src, 1); break; } }
    if($sourceForLink !== ''){
        $buttons[] = [['text'=>'🔗 باز کردن پست در کانال تبلیغات', 'url'=>'https://t.me/'.$sourceForLink.'/'.$postId]];
    }
    $buttons[] = [['text'=>'📋 لیست سفارش‌ها', 'callback_data'=>'payorders']];
    bot('sendMessage', [
        'chat_id' => $chatID,
        'text' => $summary,
        'parse_mode' => 'HTML',
        'reply_markup' => json_encode(['inline_keyboard'=>$buttons], JSON_UNESCAPED_UNICODE),
    ]);
    return false;
}

function bale_member_id_in_array($needle, $haystack){
    if(!is_array($haystack)) return false;
    $needle = (string)$needle;
    foreach($haystack as $item){
        if((string)$item === $needle) return true;
    }
    return false;
}


require_once __DIR__ . '/../Services/RewardService.php';

function bale_order_status_icon($status){
    $status = (string)$status;
    if(strpos($status, 'تکمیل') !== false) return '✅';
    if(strpos($status, 'کنسل') !== false || strpos($status, 'لغو') !== false) return '❌';
    return '♻️';
}

function bale_order_progress_percent($order){
    $need = max(1, (int)($order['member'] ?? 0));
    $got = (int)($order['tedad'] ?? bale_order_count_clean($order['members'] ?? []));
    $pct = (int)floor(min(100, max(0, ($got / $need) * 100)));
    return $pct;
}

function bale_order_progress_bar($percent){
    $percent = max(0, min(100, (int)$percent));
    $filled = (int)round($percent / 10);
    return str_repeat('█', $filled).str_repeat('░', 10 - $filled).' '.$percent.'%';
}

function bale_get_user_orders($userId){
    $userId = (string)$userId;
    $orders = [];

    // Fast path for large bots: read the user's latest orders directly from indexed SQL.
    // No long TTL cache here; the tracking screen must show the order immediately after creation.
    if(function_exists('bot_sql_pdo')){
        $pdo = bot_sql_pdo();
        if($pdo){
            try{
                $st = $pdo->prepare('SELECT order_id, data_json FROM bot_orders WHERE owner_id=? ORDER BY created_ts DESC, CAST(order_id AS UNSIGNED) DESC, order_id DESC LIMIT 30');
                $st->execute([$userId]);
                foreach($st as $row){
                    $data = function_exists('bot_json_decode_array') ? bot_json_decode_array((string)($row['data_json'] ?? ''), []) : json_decode((string)($row['data_json'] ?? ''), true);
                    if(!is_array($data)) $data = [];
                    if($data && (string)($data['admin'] ?? $data['owner_id'] ?? $userId) === $userId){
                        $orders[(string)$row['order_id']] = $data;
                    }
                }
                return $orders;
            }catch(Throwable $e){ error_log('BOT tracking SQL failed: '.$e->getMessage()); }
        }
    }

    // File fallback with very short cache only.
    $cacheKey = 'user_'.$userId;
    if(function_exists('bot_cache_get')){
        $cached = bot_cache_get('orders', $cacheKey, 3);
        if(is_array($cached)) return $cached;
    }
    foreach(bot_data_glob('ads/*.json') as $file){
        $id = basename($file, '.json');
        $order = bot_data_get_json($file);
        if(!is_array($order)) continue;
        if((string)($order['admin'] ?? $order['owner_id'] ?? '') !== $userId) continue;
        $orders[$id] = $order;
    }
    uksort($orders, function($a, $b){ return (int)$b <=> (int)$a; });
    if(function_exists('bot_cache_set')) bot_cache_set('orders', $cacheKey, $orders);
    return $orders;
}

function bale_order_card_text($orderId, $order, $money){
    $channel = isset($order['channel']) ? normalize_bale_channel_username($order['channel']) : '';
    $channelText = $channel !== '' ? '@'.$channel : 'نامشخص';
    $need = (int)($order['member'] ?? 0);
    $got = (int)($order['tedad'] ?? bale_order_count_clean($order['members'] ?? []));
    $left = bale_order_count_clean($order['left'] ?? []);
    $status = (string)($order['stats'] ?? 'نامشخص');
    $pct = bale_order_progress_percent($order);
    $remain = max(0, $need - $got);
    $spent = (int)($order['Points'] ?? 0);
    $date = trim((string)($order['date'] ?? ''));
    $time = trim((string)($order['time'] ?? ''));
    $created = trim($date.' '.$time);
    if($created === '') $created = 'نامشخص';
    return "📦 **سفارش #{$orderId}**  ".bale_order_status_icon($status)."\n".
        "━━━━━━━━━━━━━━\n".
        "🌐 کانال: **{$channelText}**\n".
        "📊 وضعیت: **{$status}**\n".
        "👥 دریافت‌شده: **{$got}** از **{$need}** | باقی‌مانده: **{$remain}**\n".
        "📈 پیشرفت: <code>".bale_order_progress_bar($pct)."</code>\n".
        "💔 لفت‌ها: **{$left}**\n".
        "💎 هزینه سفارش: **{$spent} {$money}**\n".
        "🗓 زمان ثبت: **{$created}**";
}

function bale_orders_dashboard_text($userId, $money){
    $orders = bale_get_user_orders($userId);
    if(!$orders) return "📭 **هنوز سفارشی ثبت نکرده‌اید.**\n\nاز بخش ثبت سفارش می‌توانید سفارش جدید ایجاد کنید.";
    $total = count($orders);
    $active = $done = $cancel = 0;
    $needAll = $gotAll = $leftAll = 0;
    foreach($orders as $order){
        $st = (string)($order['stats'] ?? '');
        if(strpos($st, 'تکمیل') !== false) $done++;
        elseif(strpos($st, 'کنسل') !== false || strpos($st, 'لغو') !== false) $cancel++;
        else $active++;
        $needAll += (int)($order['member'] ?? 0);
        $gotAll += (int)($order['tedad'] ?? bale_order_count_clean($order['members'] ?? []));
        $leftAll += bale_order_count_clean($order['left'] ?? []);
    }
    return "📋 **داشبورد پیگیری سفارشات**\n".
        "━━━━━━━━━━━━━━\n".
        "📦 کل سفارش‌ها: **{$total}**\n".
        "♻️ در حال اجرا: **{$active}** | ✅ تکمیل: **{$done}** | ❌ لغو: **{$cancel}**\n".
        "👥 مجموع دریافتی: **{$gotAll}** از **{$needAll}**\n".
        "💔 مجموع لفت‌ها: **{$leftAll}**\n\n".
        "برای دیدن جزئیات، یکی از سفارش‌ها را انتخاب کنید:";
}

function bale_orders_dashboard_keyboard($userId){
    $orders = bale_get_user_orders($userId);
    $rows = [];
    $i = 0;
    foreach($orders as $id => $order){
        if($i >= 12) break;
        $channel = isset($order['channel']) ? normalize_bale_channel_username($order['channel']) : '';
        $channel = $channel !== '' ? '@'.$channel : 'کانال';
        if(mb_strlen($channel, 'UTF-8') > 18) $channel = mb_substr($channel, 0, 17, 'UTF-8').'…';
        $got = (int)($order['tedad'] ?? bale_order_count_clean($order['members'] ?? []));
        $need = (int)($order['member'] ?? 0);
        $icon = bale_order_status_icon((string)($order['stats'] ?? ''));
        $rows[] = [[ 'text' => "{$icon} #{$id} | {$channel} | {$got}/{$need}", 'callback_data' => "orderdetail-{$id}" ]];
        $i++;
    }
    $rows[] = [['text'=>'🔄 بروزرسانی', 'callback_data'=>'orders-refresh'], ['text'=>'➡️ بازگشت', 'callback_data'=>'backpaybutton']];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}

function bale_order_detail_keyboard($orderId, $order, $cancelEnabled){
    $rows = [];
    $rows[] = [['text'=>'📇 مشاهده پست سفارش', 'callback_data'=>"vieworder-{$orderId}"]];
    if($cancelEnabled === '✅فعال' && (string)($order['stats'] ?? '') === 'در حال اجرا ♻️'){
        $rows[] = [['text'=>'❌ لغو سفارش', 'callback_data'=>"cancelask-{$orderId}"]];
    }
    $rows[] = [['text'=>'🔄 بروزرسانی همین سفارش', 'callback_data'=>"orderdetail-{$orderId}"]];
    $rows[] = [['text'=>'📋 لیست سفارش‌ها', 'callback_data'=>'payorders']];
    return json_encode(['inline_keyboard'=>$rows], JSON_UNESCAPED_UNICODE);
}

function bale_show_orders_dashboard($chatID, $msg_id, $userId, $money){
    $text = bale_orders_dashboard_text($userId, $money);
    $keyboard = bale_orders_dashboard_keyboard($userId);
    bot('editmessagetext', [
        'chat_id' => $chatID,
        'message_id' => $msg_id,
        'text' => $text,
        'parse_mode' => 'MarkDown',
        'reply_markup' => $keyboard,
    ]);
}
