<?php

if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed');
}

function showOrderList(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data): void {
    $action = $params['action'] ?? 'adminOrderPage';
    $can_edit = ($message_id !== null);

    $order_view_type = $session_data['order_view_type'] ?? 'normal';
    $status_filter = $session_data['order_filter'] ?? 'all';
    $offset = (int)($params['offset'] ?? 0);

    if (strpos($action, 'filterOrderReferralStatus') !== false) {
        $order_view_type = 'referral';
        $status_filter = $params['status'] ?? 'all';
        $offset = 0;
    } elseif (strpos($action, 'filterOrderStatus') !== false) {
        $order_view_type = 'normal';
        $status_filter = $params['status'] ?? 'all';
        $offset = 0;
    } elseif (strpos($action, 'adminOrderReferralPage') !== false) {
        $order_view_type = 'referral';
    } elseif (strpos($action, 'adminOrderPage') !== false) {
        $order_view_type = 'normal';
    }

    $session_data['order_filter'] = $status_filter;
    $session_data['order_view_type'] = $order_view_type;
    updateUserField($user_id, 'session', json_encode($session_data));

    $limit = defined('ADMIN_ORDERS_PER_PAGE') ? ADMIN_ORDERS_PER_PAGE : 5;
    
    $orders = getOrdersByFilterPaginated($status_filter, $limit, $offset, $order_view_type);
    $total_orders = countOrdersByFilter($status_filter, $order_view_type);

    $pagination_action = ($order_view_type === 'referral') ? 'adminOrderReferralPage' : 'adminOrderPage';
    $filter_action = ($order_view_type === 'referral') ? 'filterOrderReferralStatus' : 'filterOrderStatus';
    $title = ($order_view_type === 'referral') ? '📈 سفارشات ارجاعی' : '📋 سفارشات عادی';
    
    $status_text_fa_translated = translate_status_to_persian($status_filter);
    $status_text_fa_display = ($status_filter === 'all') ? 'همه' : $status_text_fa_translated;
    $page = floor($offset / $limit) + 1;
    $message_text_body = "{$title} (وضعیت: *{$status_text_fa_display}* - صفحه {$page}):";

    if (empty($orders) && $offset === 0) {
        $message_text_body = "هیچ سفارشی با وضعیت `{$status_text_fa_translated}` در بخش '{$title}' یافت نشد.";
    }

    $buttons = [];
    foreach($orders as $order){
        $date_fa = to_jalali_datetime($order['created_at']);
        $customer_name = htmlspecialchars($order['first_name'] ?? 'کاربر');
        $order_label = "#{$order['id']} - {$customer_name} - {$date_fa}";

        if ($order_view_type === 'referral' && isset($order['total_partner_profit'])) {
             $profit_formatted = number_format($order['total_partner_profit']);
             $partner_name = htmlspecialchars($order['partner_first_name'] ?? 'همکار');
             $order_label = "#{$order['id']} ({$customer_name} -> {$partner_name}) - سود: {$profit_formatted} ت' - {$date_fa}";
        }

        $buttons[] = [['text' => $order_label, 'callback_data' => buildCallbackData('viewOrder', ['id' => $order['id']])]];
    }

    $pagination_row = buildPaginationRow($pagination_action, $offset, $limit, $total_orders);
    if (!empty($pagination_row)) {
        $buttons[] = $pagination_row;
    }

    $filter_buttons = [
        [
            ['text' => ($status_filter === 'all' ? '✅ همه' : 'همه'), 'callback_data' => buildCallbackData($filter_action, ['status' => 'all'])],
            ['text' => ($status_filter === 'awaiting_online_payment' ? '✅ منتظر پرداخت' : 'منتظر پرداخت'), 'callback_data' => buildCallbackData($filter_action, ['status' => 'awaiting_online_payment'])]
        ],
         [
            ['text' => ($status_filter === 'processing' ? '✅ درحال پردازش' : 'درحال پردازش'), 'callback_data' => buildCallbackData($filter_action, ['status' => 'processing'])],
            ['text' => ($status_filter === 'awaiting_shipping_fee' ? '✅ منتظر هزینه پست' : 'منتظر هزینه پست'), 'callback_data' => buildCallbackData($filter_action, ['status' => 'awaiting_shipping_fee'])]
         ],
        [
            ['text' => ($status_filter === 'shipped' ? '✅ ارسال شده' : 'ارسال شده'), 'callback_data' => buildCallbackData($filter_action, ['status' => 'shipped'])],
            ['text' => ($status_filter === 'completed' ? '✅ تکمیل شده' : 'تکمیل شده'), 'callback_data' => buildCallbackData($filter_action, ['status' => 'completed'])]
        ],
        [
            ['text' => ($status_filter === 'canceled' ? '✅ لغو شده' : 'لغو شده'), 'callback_data' => buildCallbackData($filter_action, ['status' => 'canceled'])],
             ['text' => ($status_filter === 'payment_failed' ? '✅ پرداخت ناموفق' : 'پرداخت ناموفق'), 'callback_data' => buildCallbackData($filter_action, ['status' => 'payment_failed'])]
        ]
    ];
    $buttons = array_merge($buttons, [[['text' => '--- فیلتر وضعیت ---', 'callback_data' => 'noop']]], $filter_buttons);
    
    $buttons[] = [['text' => '🔙 بازگشت به منو اصلی', 'callback_data' => buildCallbackData('adminMainMenu')]];
    $reply_markup = ['inline_keyboard' => $buttons];

    if ($can_edit && (strpos($action, 'filter') !== false || strpos($action, 'Page') !== false)) {
        
        $current_text = $GLOBALS['update']['callback_query']['message']['text'] ?? null;
        if ($current_text === $message_text_body) {
            
            apiRequest('editMessageReplyMarkup', ['chat_id' => $chat_id, 'message_id' => $message_id, 'reply_markup' => json_encode($reply_markup)], $platform);
        } else {
            editMessage($chat_id, $message_id, $message_text_body, $reply_markup);
        }
    } else {
         
         if ($can_edit) {
             apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform);
         }
         sendMessage($chat_id, $message_text_body, $reply_markup, $platform);
    }
}

?>