<?php

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

require_once __DIR__ . '/../../../Database/TransactionQueries.php';

function showCustomerOrderDetails(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $user): void {
    $order_id = (int)($params['id'] ?? 0);
     $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null;
    $can_edit = ($message_id !== null);

    if ($order_id <= 0) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: شماره سفارش نامعتبر.', 'show_alert' => true], $platform);
        
        showCustomerProductOrderList(['offset' => 0], $chat_id, $message_id, $user_id, $platform, $user);
        return;
    }

    $order = getOrderDetails($order_id);

    if ($order && isset($order['user_id']) && $order['user_id'] 
== $user_id) {
        $message_body = buildCustomerOrderDetailsText($order);
        $buttons = [];


        if (in_array($order['status'], ['awaiting_online_payment', 'payment_failed'])) {
 
       
            $payment_page_url = PAYMENT_PAGE_URL . '?order_id=' . $order_id; 
             $buttons[] = [['text' => '💰 تلاش مجدد برای پرداخت', 'url' => $payment_page_url]]; 

        }

        
if ($order['status'] === 'awaiting_shipping_fee') {
            $payment_page_url = PAYMENT_PAGE_URL . '?order_id=' . $order_id;
            $formatted_shipping_fee = number_format($order['shipping_fee'] ?? '0.00');
            $buttons[] = [['text' => '🚚 پرداخت هزینه پست (' . $formatted_shipping_fee . ' تومان)', 'url' => $payment_page_url]];
        }

        
        $back_action = ($order['order_type'] ?? 'product') === 'invoice' ? 'custInvoicePage' : 'custProdOrderPage';
        $back_text = ($order['order_type'] ?? 'product') === 'invoice' ? '🔙 بازگشت به لیست فاکتورها' : '🔙 بازگشت به لیست سفارشات';

        $buttons[] = [['text' => $back_text, 'callback_data' => buildCallbackData($back_action, ['offset' => 0])]];
        
        $reply_markup = ['inline_keyboard' 
=> $buttons];

         if ($can_edit) {

             editMessage($chat_id, $message_id, $message_body, $reply_markup);
         } else {
             
             sendMessage($chat_id, "جزئیات سفارش:", getCustomerMainMenuKeyboard($user), $platform);
       sendMessage($chat_id, $message_body, $reply_markup, $platform);
           }
    } else {
        if ($callback_query_id) {
           apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: سفارش یافت نشد.', 'show_alert' => true], $platform);
           }
        
        if ($can_edit) {
            apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], 
$platform);
        }
        showCustomerProductOrderList(['offset' => 0], $chat_id, null, $user_id, $platform, $user); 
    }
}


?>