<?php

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


/**
 * Displays a paginated list of active products for the admin.
 * Signature corrected to accept $params array first.
 */
function showProductList(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data): void {
    $offset = (int)($params['offset'] ?? 0);
    $limit = defined('ADMIN_PRODUCTS_PER_PAGE') ? ADMIN_PRODUCTS_PER_PAGE : 5;
    
    $products = getActiveProducts(null, $limit, $offset); 
    $total_products = countActiveProducts(); 

    if (empty($products) && $offset === 0) {
        sendMessage($chat_id, "هیچ محصول فعالی برای مدیریت وجود ندارد.", null, $platform);
        return;
    }

    // Send header message
    $page = floor($offset / $limit) + 1;
    sendMessage($chat_id, "-- 📝 مدیریت محصولات (صفحه {$page}) --", null, $platform); 

    // Send each product as a separate photo message with buttons
    foreach ($products as $product) {
        $stock_text = ($product['stock'] === null) ? 'نامحدود' : (bccomp((string)$product['stock'], '0', 1) > 0 ? $product['stock'] : 'ناموجود');
        $price_text = number_format($product['price'] ?? 0);
        $unit = $product['unit'] ?? '';
        $name = htmlspecialchars($product['name'] ?? 'نامشخص');

        $caption = "*{$name}*\n"; 
        $caption .= "قیمت: {$price_text} تومان / {$unit}\n";
        $caption .= "موجودی: `{$stock_text}`";
        
        if($product['pricing']['on_sale'] ?? false) {
            $caption .= "\n🏷 تخفیف فعال";
        }

        $buttons = [[ 
            ['text' => 'ویرایش ✏️', 'callback_data' => buildCallbackData('editProd', ['id' => $product['id']])],
            ['text' => 'حذف 🗑', 'callback_data' => buildCallbackData('deleteProd', ['id' => $product['id']])]
        ]];

        
        $photo_id = $product['platform_photo_id'] ?? null;
        if ($photo_id) {
            sendPhotoWithButtons($chat_id, $photo_id, $caption, $buttons, $platform);
        } else {
            
            $caption .= "\n\n⚠️ عکس محصول یافت نشد.";
            sendMessage($chat_id, $caption, ['inline_keyboard' => $buttons], $platform);
        }
        usleep(150000); 
    }

    // Send pagination controls if needed
    $pagination_row = buildPaginationRow('adminPage', $offset, $limit, $total_products); 
    if (!empty($pagination_row)) {
        sendMessage(
            $chat_id,
            "برای جابجایی بین صفحات از دکمه‌های زیر استفاده کنید:",
            ['inline_keyboard' => [$pagination_row]],
            $platform
        );
    }
}

?>