<?php

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

function showPartnerOrderList(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $user): void {
    $offset = (int)($params['offset'] ?? 0);
    $view_type = $params['type'] ?? 'self'; 
    $limit = defined('CUSTOMER_ORDERS_PER_PAGE') ? CUSTOMER_ORDERS_PER_PAGE : 5;
    $can_edit = ($message_id !== null);

    $is_self_orders = ($view_type === 'self');
    
    $orders = getPartnerOrders($user_id, $limit, $offset, $is_self_orders);
    $total_orders = countPartnerOrders($user_id, $is_self_orders);
    
    $buttons = [];
    $text = '';
    
    $action = $is_self_orders ? 'listPartnerOrders' : 'listCustomerOrders';
    $title = $is_self_orders ? '📦 *لیست سفارشات شما*' : '📈 *لیست سفارشات مشتریان شما*';

    if ($total_orders == 0) {
        $text = $is_self_orders ? "شما هیچ سفارشی ثبت نکرده‌اید." : "مشتریان شما هنوز هیچ سفارشی ثبت نکرده‌اند.";
    } else {
        $page = floor($offset / $limit) + 1;
        $text = "{$title} (صفحه {$page}):\n\nبرای مشاهده جزئیات، روی هر مورد کلیک کنید.";
         foreach ($orders as $order) {
            $order_id_safe = $order['id'] ?? 0;
            $status_safe = $order['status'] ?? 'نامشخص';
            $created_at_safe = $order['created_at'] ?? null;
            $status_fa = translate_status_to_persian($status_safe);
            $date_fa = to_jalali_datetime($created_at_safe);
            
            if ($is_self_orders) {
                $buttons[] = [['text' => "سفارش #{$order_id_safe} - {$status_fa} - {$date_fa}", 'callback_data' => buildCallbackData('viewCustProdOrder', ['id' => $order_id_safe])]];
            } else {
                $customer_name = htmlspecialchars($order['first_name'] ?? 'مشتری');
                $profit_formatted = number_format($order['total_partner_profit'] ?? 0);
                $buttons[] = [['text' => "#{$order_id_safe} ({$customer_name}) - سود: {$profit_formatted} ت' - {$date_fa}", 'callback_data' => buildCallbackData('viewPartnerCustomerOrder', ['id' => $order_id_safe])]];
            }
        }

        $pagination_row = buildPaginationRow($action, $offset, $limit, $total_orders, ['type' => $view_type]);
    
        if (!empty($pagination_row)) {
            $buttons[] = $pagination_row;
        }
    }
    
    $buttons[] = [['text' => '🔙 بازگشت به منو اصلی', 'callback_data' => buildCallbackData('mainMenu')]];
    $reply_markup_inline_only = ['inline_keyboard' => $buttons];

     if ($can_edit) {
         editMessage($chat_id, $message_id, $text, $reply_markup_inline_only);
     } else {
         $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);
         $mainMenuKeyboard['inline_keyboard'] = $buttons;
         sendMessage($chat_id, $text, $mainMenuKeyboard, $platform);
     }
}

?>