<?php

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

function showPartnerProductList(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    
    $category_id_param = $params['id'] ?? null;
    $offset = (int)($params['offset'] ?? 0);
    $limit = 1;
    $can_edit = ($message_id !== null);

    if ($can_edit) {
        apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform);
        $message_id = null;
        $can_edit = false;
    }

    $category_id = null;
    $show_all_products = false;

    if (is_numeric($category_id_param)) {
        $category_id = (int)$category_id_param;
    } elseif ($category_id_param === 'all') {
        $show_all_products = true;
    }

    if (!$show_all_products) {
        $subcategories = getActiveCategories($category_id);
        if (!empty($subcategories)) {
            displayPartnerSubcategories($subcategories, $category_id, $chat_id, $platform, $user);
            return;
        } elseif ($category_id === null) {
            $show_all_products = true;
        }
    }

    $query_category_id = $show_all_products ? null : $category_id;
    $total_products = countActiveProducts($query_category_id);

    $base_inline_buttons = [];
    if ($category_id !== null && !$show_all_products) {
         $parent_cat = getCategoryById($category_id);
         $back_target_id = $parent_cat['parent_id'] ?? null;
         $base_inline_buttons[] = [['text' => '⬆️ بازگشت به دسته‌بندی‌ها', 'callback_data' => buildCallbackData('managePartnerProds', ['id' => $back_target_id, 'offset' => 0])]];
    } elseif ($category_id === null && !$show_all_products && $total_products > 0) {
         $base_inline_buttons[] = [['text' => 'همه محصولات فروشگاه', 'callback_data' =>
buildCallbackData('managePartnerProds', ['id' => 'all', 'offset' => 0])]];
    }

    $base_inline_buttons[] = [['text' => '🔙 بازگشت به فروشگاه من', 'callback_data' => buildCallbackData('manageShop')]];

    $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);

    if ($total_products == 0) {
        $error_text = $show_all_products ? "متاسفانه هیچ محصول فعالی در فروشگاه یافت نشد." : "متاسفانه محصول فعالی در این دسته‌بندی یافت نشد.";
        $reply_markup_with_main = $mainMenuKeyboard;
        $reply_markup_with_main['inline_keyboard'] = $base_inline_buttons;
        sendMessage($chat_id, $error_text, $reply_markup_with_main, $platform);
        return;
    }

    if ($offset < 0) $offset = max(0, $total_products - 1);
    if ($offset >= $total_products) $offset = 0;

    $products = getActiveProducts($query_category_id, $limit, $offset);
      if (empty($products)) {
         $error_text = "خطا در بارگذاری محصول.";
         $reply_markup_with_main = $mainMenuKeyboard;
         $reply_markup_with_main['inline_keyboard'] = $base_inline_buttons;
         sendMessage($chat_id, $error_text, $reply_markup_with_main, $platform);
         return;
    }

    $product = $products[0];
    
    list($caption, $action_buttons) = buildPartnerProductDisplay($product, $user_id);
    
    $photo_url = $product['platform_photo_id'] ?? null;
    $relative_path = $product['image_path'] ?? null;
    $file_to_send = null;
    $local_file_path = null;

    if ($relative_path && defined('PRODUCT_IMAGE_STORAGE_PATH')) {
        $local_file_path = rtrim(PRODUCT_IMAGE_STORAGE_PATH, '/') . '/' . ltrim($relative_path, '/');
    }

    if ($platform === 'bale' && $local_file_path && file_exists($local_file_path)) {
        $file_to_send = new CURLFile(realpath($local_file_path));
    } else {
        $file_to_send = $photo_url;
    }

    $final_inline_buttons = $action_buttons;
    
    if ($total_products > 1) {
        $nav_action = 'managePartnerProds';
        $nav_id_param = $category_id_param ?? ($show_all_products ? 'all' : 'root');
        $prev_offset = ($offset - 1 < 0) ? $total_products - 1 : $offset - 1;
        $next_offset = ($offset + 1 >= $total_products) ? 0 : $offset + 1;
        $pagination_row = buildPaginationRowForProductView($nav_action, $offset, $total_products, ['id' => $nav_id_param], $prev_offset, $next_offset);
        if(!empty($pagination_row)) $final_inline_buttons[] = $pagination_row;
    }
    $final_inline_buttons = array_merge($final_inline_buttons, $base_inline_buttons);
    
    sendMessage($chat_id, " ", $mainMenuKeyboard, $platform);

    $reply_markup_inline_only = ['inline_keyboard' => $final_inline_buttons];

    if (empty($file_to_send)) {
         $caption .= "\n\n⚠️ *خطا: عکس محصول برای نمایش در دسترس نیست.*";
         sendMessage($chat_id, $caption, $reply_markup_inline_only, $platform);
    } else {
        apiRequest('sendPhoto', [
            'chat_id' => $chat_id,
            'photo' => $file_to_send,
            'caption' => $caption,
            'parse_mode' => 'Markdown',
            'reply_markup' => $reply_markup_inline_only
        ], $platform);
    }
}


function displayPartnerSubcategories(array $subcategories, ?int $category_id, int $chat_id, string $platform, array $user): void {
    $path_text = "دسته‌بندی اصلی";
    if ($category_id !== null) {
        $path_array = getCategoryPath($category_id);
        $path_names = array_map(function($p) { return htmlspecialchars($p['name'] ?? '?'); }, $path_array);
        $path_text = implode(" > ", $path_names);
    }
    
    $message_text_body = "شما در مسیر *{$path_text}* هستید.\nلطفا یک زیردسته را انتخاب کنید:";

    $inline_buttons = [];
    foreach ($subcategories as $subcat) {
       $cat_name = htmlspecialchars($subcat['name'] ?? 'نامشخص');
         $cat_id = $subcat['id'] ?? 0;
         if ($cat_id > 0) {
              $inline_buttons[] = [['text' => "📁 {$cat_name}", 'callback_data' => buildCallbackData('managePartnerProds', ['id' => $cat_id, 'offset' => 0])]];
         }
    }
    
    if ($category_id !== null) {
        $parent_cat = getCategoryById($category_id);
        $back_target_id = $parent_cat['parent_id'] ?? null;
        $inline_buttons[] = [['text' => '⬆️ بازگشت به سطح قبل', 'callback_data' => buildCallbackData('managePartnerProds', ['id' => $back_target_id, 'offset' => 0])]];
    } else {
         $inline_buttons[] = [['text' => 'همه محصولات فروشگاه', 'callback_data' => buildCallbackData('managePartnerProds', ['id' => 'all', 'offset' => 0])]];
    }

    $inline_buttons[] = [['text' => '🔙 بازگشت به فروشگاه من', 'callback_data' => buildCallbackData('manageShop')]];
    
    $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);
    $reply_markup_inline_only = ['inline_keyboard' => $inline_buttons];

    sendMessage($chat_id, $message_text_body, $mainMenuKeyboard, $platform);
    sendMessage($chat_id, "گزینه‌ها:", $reply_markup_inline_only, $platform);
}


function buildPartnerProductDisplay(array $product, int $partner_user_id): array {
    $product_name = htmlspecialchars($product['name'] ?? 'نامشخص');
    $description = htmlspecialchars($product['description'] ?? '');
    $unit = $product['unit'] ?? '';
    $stock = $product['stock'] ?? null;
    $product_id = $product['id'] ?? 0;
    $product_type = $product['type'] ?? 'simple';
    $pricing = $product['pricing'] ?? ['price' => '0.00', 'on_sale' => false, 'base_price' => '0.00'];

    $base_price_text = "*" . number_format($pricing['price']) . "* تومان";
    if($pricing['on_sale'] && bccomp((string)$pricing['base_price'], (string)$pricing['price'], BC_SCALE) > 0){
        $base_price_text = "~" . number_format($pricing['base_price']) . "~ " . $base_price_text;
    }
    
    $caption = "*{$product_name}*\n\n";
    $caption .= "قیمت پایه: {$base_price_text} / `{$unit}`\n";
    
    $action_buttons = [];

    if ($product_type === 'simple') {
        $stock_text = '';
        if ($stock === null) {
            $stock_text = '✅ موجود';
        } elseif (bccomp((string)$stock, '0', 1) > 0) {
            $stock_formatted = number_format((float)$stock, (strpos($stock, '.') !== false) ? 1 : 0, '.', '');
            $stock_text = "موجودی: `{$stock_formatted}` {$unit}";
        } else {
            $stock_text = "❌ *ناموجود*";
        }
        $caption .= "{$stock_text}\n\n";

        $partner_setting = getPartnerProductSetting($partner_user_id, $product_id);
        $partner_extra_price = $partner_setting['extra_price'] ?? '0.00';
        $partner_is_active = $partner_setting['is_active'] ?? false;

        if ($partner_is_active) {
            $final_price = bcadd($pricing['price'], $partner_extra_price, BC_SCALE);
            $caption .= "✅ *فعال برای مشتریان شما*\n";
            $caption .= "سود شما: `" . number_format($partner_extra_price) . "` تومان\n";
            $caption .= "قیمت نهایی مشتری: `" . number_format($final_price) . "` تومان\n";
            
            $action_buttons[] = ['text' => '✏️ ویرایش سود', 'callback_data' => buildCallbackData('setPartnerPrice', ['id' => $product_id])];
            $action_buttons[] = ['text' => '❌ غیرفعال کردن', 'callback_data' => buildCallbackData('deactPartnerProd', ['id' => $product_id])];
        } else {
            $caption .= "❌ *غیرفعال برای مشتریان شما*\n";
            if (bccomp($partner_extra_price, '0', BC_SCALE) > 0) {
                 $caption .= "سود قبلی شما: `" . number_format($partner_extra_price) . "` تومان\n";
            }
            $action_buttons[] = ['text' => '✅ فعال‌سازی / تنظیم سود', 'callback_data' => buildCallbackData('setPartnerPrice', ['id' => $product_id])];
        }
    } else {
        $caption .= "این یک محصول متغیر است.\n\n";
        $caption .= "شما باید سود و وضعیت هر ترکیب (مانند قرمز-کوچک) را به صورت جداگانه در بخش «مدیریت ترکیب‌ها» تنظیم کنید.";
        $action_buttons[] = ['text' => '🔧 مدیریت ترکیب‌ها', 'callback_data' => buildCallbackData('managePartnerVariations', ['pid' => $product_id, 'offset' => 0])];
    }
    
    return [$caption, [$action_buttons]];
}


function askPartnerForPrice(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data): void {
    $product_id = (int)($params['id'] ?? 0);
    $variation_id = (int)($params['var_id'] ?? 0);
    
    if ($product_id <= 0 && $variation_id <= 0) {
        sendMessage($chat_id, "خطا: محصول یا ترکیب نامشخص است.", null, $platform);
        return;
    }

    $session_data['state'] = 'awaiting_partner_price';
    $session_data['partner_product_id'] = $product_id;
    $session_data['partner_variation_id'] = ($variation_id > 0) ? $variation_id : null;
    updateUserField($user_id, 'session', json_encode($session_data));
    
    $base_price_text = '0.00';
    $item_name = 'نامشخص';
    $current_extra_price = '0.00';

    if ($variation_id > 0) {
        $variation = getVariationById($variation_id);
        $product = getProduct($variation['product_id']);
        if (!$variation || !$product) {
            sendMessage($chat_id, "خطا: ترکیب یافت نشد.", null, $platform);
            return;
        }
        $item_name = htmlspecialchars($product['name'] . ' - ' . $variation['full_name']);
        
        $var_pricing_data = ['price' => $variation['price'] ?? $product['price']] + $product;
        $pricing = calculateCurrentPrice($var_pricing_data);
        $base_price_text = number_format($pricing['price'] ?? 0);
        
        $partner_setting = getPartnerVariationProfit($user_id, $variation_id);
        $current_extra_price = $partner_setting['extra_price'] ?? '0.00';
        
    } else {
        $product = getProduct($product_id);
        if (!$product) {
            sendMessage($chat_id, "خطا: محصول یافت نشد.", null, $platform);
            return;
        }
        $item_name = htmlspecialchars($product['name'] ?? '');
        $base_price_text = number_format($product['pricing']['price'] ?? 0);
        
        $partner_setting = getPartnerProductSetting($user_id, $product_id);
        $current_extra_price = $partner_setting['extra_price'] ?? '0.00';
    }
    
    $text = " محصول: *{$item_name}*\n";
    $text .= " قیمت پایه فعلی: `{$base_price_text}` تومان\n\n";
    $text .= "لطفا *مبلغ سود* خود (قیمت افزایشی) را به تومان وارد کنید (مثال: `50000`).\n";
    $text .= "مبلغ نهایی که مشتری می‌بیند، (قیمت پایه + سود شما) خواهد بود.\n\n";
    if (bccomp($current_extra_price, '0', BC_SCALE) > 0) {
        $text .= "سود فعلی شما: `" . number_format($current_extra_price) . "` تومان";
    }

    if ($message_id) {
        apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform);
    }
    
    sendMessage($chat_id, $text, ['keyboard' => [[['text' => 'انصراف']]], 'resize_keyboard' => true], $platform);
}


function handlePartnerPriceInput(array $message, int $chat_id, int $user_id, string $platform, array $session_data, array $user): void {
    $product_id = $session_data['partner_product_id'] ?? null;
    $variation_id = $session_data['partner_variation_id'] ?? null;
    $extra_price_str = trim($message['text'] ?? '');

    if (!$product_id) {
         sendMessage($chat_id, "خطا: محصول هدف مشخص نیست. عملیات لغو شد.", ['remove_keyboard' => true], $platform);
        updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
        showCustomerMainMenu($chat_id, $user_id, $platform, $user);
        return;
    }
    
    if (isValidNonNegativeNumber($extra_price_str)) {
        $extra_price = convertPersianToEnglishDigits($extra_price_str);
        $success = false;
        
        if ($variation_id) {
            $success = updatePartnerVariationProfit($user_id, $variation_id, $extra_price, true);
        } else {
            $success = updatePartnerProductSetting($user_id, $product_id, $extra_price, true);
        }

        if ($success) {
            sendMessage($chat_id, "✅ سود شما به مبلغ `" . number_format($extra_price) . "` تومان ثبت شد و محصول/ترکیب برای مشتریان شما *فعال* گردید.", ['remove_keyboard' => true], $platform);
            updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
            
            showPartnerShopMenu($chat_id, $user_id, $platform, $user, null);
        } else {
            sendMessage($chat_id, "❌ خطایی در ذخیره اطلاعات رخ داد. لطفا مجددا تلاش کنید.", ['remove_keyboard' => true], $platform);
             updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
            showCustomerMainMenu($chat_id, $user_id, $platform, $user);
        }
    } else {
        sendMessage($chat_id, "❌ مبلغ نامعتبر است. لطفا یک عدد مثبت (مانند `50000`) یا `0` وارد کنید.", null, $platform);
    }
}


function handlePartnerProductDeactivate(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    $product_id = (int)($params['id'] ?? 0);
    $variation_id = (int)($params['var_id'] ?? 0);
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null;

    if ($product_id <= 0 && $variation_id <= 0) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: محصول نامشخص.', 'show_alert' => true], $platform);
        return;
    }
    
    $success = false;
    $current_extra_price = '0.00';
    
    if ($variation_id > 0) {
        $partner_setting = getPartnerVariationProfit($user_id, $variation_id);
        $current_extra_price = $partner_setting['extra_price'] ?? '0.00';
        $success = updatePartnerVariationProfit($user_id, $variation_id, $current_extra_price, false);
    } else {
        $partner_setting = getPartnerProductSetting($user_id, $product_id);
        $current_extra_price = $partner_setting['extra_price'] ?? '0.00';
        $success = updatePartnerProductSetting($user_id, $product_id, $current_extra_price, false);
    }

    if ($success) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'محصول/ترکیب برای مشتریان شما غیرفعال شد.'], $platform);
        
        if ($variation_id > 0) {
            $variation = getVariationById($variation_id);
            showPartnerVariationList(['pid' => $variation['product_id']], $chat_id, $message_id, $user_id, $platform, $session_data, $user);
        } else {
            showPartnerProductList($params, $chat_id, $message_id, $user_id, $platform, $session_data, $user);
        }
    } else {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا در غیرفعال‌سازی.', 'show_alert' => true], $platform);
    }
}


function showPartnerVariationList(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    $product_id = (int)($params['pid'] ?? 0);
    $offset = (int)($params['offset'] ?? 0);
    $limit = 5;
    $can_edit = ($message_id !== null);

    if ($product_id <= 0) {
        if ($can_edit) editMessage($chat_id, $message_id, "خطا: محصول نامعتبر است.", null);
        showPartnerProductList(['id' => null, 'offset' => 0], $chat_id, null, $user_id, $platform, $session_data, $user);
        return;
    }

    $product = getProduct($product_id);
    if (!$product) {
        if ($can_edit) editMessage($chat_id, $message_id, "خطا: محصول یافت نشد.", null);
        showPartnerProductList(['id' => null, 'offset' => 0], $chat_id, null, $user_id, $platform, $session_data, $user);
        return;
    }

    $variations = getProductVariations($product_id);
    $partner_profits = getPartnerVariationProfitsForProduct($user_id, $product_id);
    
    $total = count($variations);
    $page = floor($offset / $limit) + 1;
    
    $text = "⚙️ *مدیریت ترکیب‌های محصول: {$product['name']}*\n(صفحه {$page})\n\n";
    $buttons = [];
    
    if (empty($variations)) {
        $text .= "هیچ ترکیبی برای این محصول یافت نشد.";
    } else {
        $page_variations = array_slice($variations, $offset, $limit);
        
        foreach ($page_variations as $var) {
            $var_id = $var['id'];
            $var_name = $var['full_name'];
            $partner_setting = $partner_profits[$var_id] ?? null;
            
            $var_text = "{$var_name}\n";
            $var_buttons = [];
            
            if ($partner_setting && $partner_setting['is_active']) {
                $profit = $partner_setting['extra_price'] ?? '0.00';
                $var_text .= "✅ فعال | سود: `" . number_format($profit) . "` تومان";
                $var_buttons[] = ['text' => '✏️ ویرایش', 'callback_data' => buildCallbackData('setPartnerPrice', ['id' => $product_id, 'var_id' => $var_id])];
                $var_buttons[] = ['text' => '❌ غیرفعال', 'callback_data' => buildCallbackData('deactPartnerProd', ['id' => $product_id, 'var_id' => $var_id])];
            } else {
                $var_text .= "❌ غیرفعال";
                $var_buttons[] = ['text' => '✅ فعال/تنظیم سود', 'callback_data' => buildCallbackData('setPartnerPrice', ['id' => $product_id, 'var_id' => $var_id])];
            }
            
            $buttons[] = [['text' => $var_text, 'callback_data' => 'noop']];
            $buttons[] = $var_buttons;
        }
    }
    
    $pagination_row = buildPaginationRow('managePartnerVariations', $offset, $limit, $total, ['pid' => $product_id]);
    if (!empty($pagination_row)) {
        $buttons[] = $pagination_row;
    }
    
    $buttons[] = [['text' => '🔙 بازگشت به محصول', 'callback_data' => buildCallbackData('managePartnerProds', ['id' => $product['category_id'], 'offset' => 0])]];

    $reply_markup = ['inline_keyboard' => $buttons];
    
    if ($can_edit) {
        editMessage($chat_id, $message_id, $text, $reply_markup);
    } else {
        sendMessage($chat_id, $text, $reply_markup, $platform);
    }
}

?>