<?php

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

function handleVariationSelection(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data): void {
    
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null;
    $can_edit = ($message_id !== null);
    
    if (!$can_edit) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id], $platform);
        return;
    }

    $selection_data = $session_data['product_variation_selection'] ?? null;
    if (!$selection_data) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: اطلاعات انتخاب منقضی شده است.', 'show_alert' => true], $platform);
        editMessage($chat_id, $message_id, "خطا: اطلاعات انتخاب منقضی شده است. لطفا مجددا محصول را انتخاب کنید.", null);
        return;
    }
    
    $product_id = $selection_data['product_id'];
    $attributes = $selection_data['attributes'];
    $current_attr_index = $selection_data['current_attr_index'];
    $selected_values = $selection_data['selected_values'];
    
    $action = $params['action'] ?? 'selectAttributeValue';
    
    if ($action === 'selectAttributeValue') {
        $value_id = (int)($params['val_id'] ?? 0);
        if ($value_id <= 0) {
            if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id], $platform);
            return;
        }
        
        $current_attribute_id = $attributes[$current_attr_index]['attribute_id'];
        $selected_values[$current_attribute_id] = $value_id;
        $session_data['product_variation_selection']['selected_values'] = $selected_values;
        
        $next_attr_index = $current_attr_index + 1;
        
        if (isset($attributes[$next_attr_index])) {
            $session_data['product_variation_selection']['current_attr_index'] = $next_attr_index;
            updateUserField($user_id, 'session', json_encode($session_data));
            displayNextAttributeOptions($chat_id, $message_id, $platform, $session_data);
        } else {
            updateUserField($user_id, 'session', json_encode($session_data));
            displayFinalVariation($chat_id, $message_id, $platform, $session_data);
        }
        
    } elseif ($action === 'backToAttribute') {
        $target_index = (int)($params['idx'] ?? 0);
        
        $new_selected_values = [];
        foreach ($selected_values as $attr_id => $val_id) {
            $found_index = array_search($attr_id, array_column($attributes, 'attribute_id'));
            if ($found_index !== false && $found_index < $target_index) {
                $new_selected_values[$attr_id] = $val_id;
            }
        }
        
        $session_data['product_variation_selection']['selected_values'] = $new_selected_values;
        $session_data['product_variation_selection']['current_attr_index'] = $target_index;
        updateUserField($user_id, 'session', json_encode($session_data));
        
        displayNextAttributeOptions($chat_id, $message_id, $platform, $session_data);
    }
}

function displayNextAttributeOptions(int $chat_id, int $message_id, string $platform, array $session_data): void {
    $selection_data = $session_data['product_variation_selection'];
    $product_id = $selection_data['product_id'];
    $attributes = $selection_data['attributes'];
    $current_attr_index = $selection_data['current_attr_index'];
    $selected_values = $selection_data['selected_values'];
    
    $product = getProduct($product_id);
    if (!$product) {
        editMessage($chat_id, $message_id, "خطا: محصول یافت نشد.", null);
        return;
    }
    
    $caption = "*" . htmlspecialchars($product['name']) . "*\n\n";
    $buttons = [];
    $selected_path = [];
    
    foreach ($attributes as $index => $attribute) {
        $attr_id = $attribute['attribute_id'];
        $attr_name = $attribute['attribute_name'];
        
        if (isset($selected_values[$attr_id])) {
            $value_id = $selected_values[$attr_id];
            $value_name = '?';
            foreach ($attribute['values'] as $value) {
                if ($value['id'] == $value_id) {
                    $value_name = $value['value'];
                    break;
                }
            }
            $selected_path[] = "*" . htmlspecialchars($attr_name) . ":* " . htmlspecialchars($value_name);
        }
        
        if ($index == $current_attr_index) {
            $caption .= "انتخاب *" . htmlspecialchars($attr_name) . "*:";
            
            $row = [];
            foreach ($attribute['values'] as $value) {
                $row[] = ['text' => $value['value'], 'callback_data' => buildCallbackData('selectAttributeValue', ['val_id' => $value['id']])];
                if (count($row) == 2) {
                    $buttons[] = $row;
                    $row = [];
                }
            }
            if (!empty($row)) $buttons[] = $row;
        }
    }
    
    if (!empty($selected_path)) {
        $caption = "*" . htmlspecialchars($product['name']) . "*\n" . implode("\n", $selected_path) . "\n\n" . $caption;
    }
    
    if ($current_attr_index > 0) {
        $buttons[] = [['text' => '🔙 بازگشت (ویرایش قبلی)', 'callback_data' => buildCallbackData('backToAttribute', ['idx' => $current_attr_index - 1])]];
    }
    
    $reply_markup = ['inline_keyboard' => $buttons];
    editMessage($chat_id, $message_id, $caption, $reply_markup, true);
}

function displayFinalVariation(int $chat_id, int $message_id, string $platform, array $session_data): void {
    $selection_data = $session_data['product_variation_selection'];
    $product_id = $selection_data['product_id'];
    $selected_value_ids = array_values($selection_data['selected_values']);
    $user_id = $GLOBALS['user']['id'];
    $user = $GLOBALS['user'];
    $partner_user_id = $user['referred_by_user_id'] ?? null;
    
    $product = getProduct($product_id);
    if (!$product) {
        editMessage($chat_id, $message_id, "خطا: محصول یافت نشد.", null);
        return;
    }

    $variation = findVariationByOptions($product_id, $selected_value_ids);
    
    if (!$variation) {
        $caption = "*" . htmlspecialchars($product['name']) . "*\n\n";
        $caption .= "❌ ترکیب انتخاب شده ناموجود یا نامعتبر است.";
        $buttons = [[['text' => '🔙 بازگشت و تغییر انتخاب', 'callback_data' => buildCallbackData('backToAttribute', ['idx' => 0])]]];
        editMessage($chat_id, $message_id, $caption, ['inline_keyboard' => $buttons], true);
        return;
    }

    $variation_pricing_data = [
        'price' => $variation['price'] ?? $product['price'],
        'discount_price' => $product['discount_price'],
        'discount_type' => $product['discount_type'],
        'discount_start_date' => $product['discount_start_date'],
        'discount_end_date' => $product['discount_end_date']
    ];
    $pricing = calculateCurrentPrice($variation_pricing_data);
    
    $partner_profit = '0.00';
    if ($partner_user_id !== null) {
        $profit_setting = getPartnerVariationProfit($partner_user_id, $variation['id']);
        if ($profit_setting && $profit_setting['is_active']) {
            $partner_profit = $profit_setting['extra_price'];
        } else {
            $profit_setting_prod = getPartnerProductSetting($partner_user_id, $product_id);
            if (!$profit_setting_prod || !$profit_setting_prod['is_active']) {
                 $caption = "*" . htmlspecialchars($product['name']) . "*\n\n";
                 $caption .= "❌ این محصول توسط همکار شما ارائه نشده است.";
                 $buttons = [[['text' => '🔙 بازگشت', 'callback_data' => buildCallbackData('viewCat', ['id' => $product['category_id']])]]];
                 editMessage($chat_id, $message_id, $caption, ['inline_keyboard' => $buttons], true);
                 return;
            }
        }
    }

    $final_price = bcadd($pricing['price'], $partner_profit, BC_SCALE);
    $price_text = "*" . number_format($final_price) . "* تومان";
    if($pricing['on_sale'] && bccomp((string)$pricing['base_price'], (string)$pricing['price'], BC_SCALE) > 0){
         $original_final_price = bcadd($pricing['base_price'], $partner_profit, BC_SCALE);
        $price_text = "~" . number_format($original_final_price) . "~ " . $price_text;
    }
    
    $stock = $variation['stock'];
    $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}` {$product['unit']}";
    } else {
        $stock_text = "❌ *ناموجود*";
    }

    $caption = "*" . htmlspecialchars($product['name']) . "*\n";
    $caption .= "*" . htmlspecialchars($variation['full_name']) . "*\n\n";
    $caption .= htmlspecialchars($product['description']) . "\n\n";
    $caption .= "قیمت: {$price_text} / `{$product['unit']}`\n{$stock_text}";

    $buttons = [];
    if ($stock === null || bccomp((string)$stock, '0', 1) > 0) {
        $buttons[] = [['text' => '➕ افزودن به سبد خرید', 'callback_data' => buildCallbackData('addToCart', ['id' => $product_id, 'var_id' => $variation['id']])]];
    }
    
    $buttons[] = [['text' => '🔙 بازگشت و تغییر انتخاب', 'callback_data' => buildCallbackData('backToAttribute', ['idx' => 0])]];
    
    $session_data['product_variation_selection']['variation_id'] = $variation['id'];
    updateUserField($user_id, 'session', json_encode($session_data));
    
    editMessage($chat_id, $message_id, $caption, ['inline_keyboard' => $buttons], true);
}

?>