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

function askForSearchQuery(int $chat_id, int $user_id, string $platform): void {
    $session_data = ['state' => 'awaiting_search_query'];
    updateUserField($user_id, 'session', json_encode($session_data));
    sendMessage(
        $chat_id,
        "لطفا نام محصولی که به دنبال آن هستید را وارد کنید:",
        ['keyboard' => [[['text' => 'انصراف']]], 'resize_keyboard' => true, 'one_time_keyboard' => true],
        $platform
    );
}

function handleSearchQuery(array $message, int $chat_id, int $user_id, string $platform, array $session_data, array $user): void {
    $search_term = trim($message['text'] ?? '');
    $partner_user_id = $user['referred_by_user_id'] ?? null;

    if (empty($search_term)) {
          sendMessage($chat_id, "لطفا یک عبارت برای جستجو وارد کنید یا انصراف دهید.", null, $platform);
         sendMessage($chat_id, "👇", ['keyboard' => [[['text' => 'انصراف']]], 'resize_keyboard' => true, 'one_time_keyboard' => true], $platform);
        return;
    }

    $total_results = 0;
    if ($partner_user_id !== null) {
        $total_results = countSearchPartnerActiveProducts($partner_user_id, $search_term);
    } else {
        $total_results = countSearchedProducts($search_term);
    }

    if ($total_results == 0) {
        $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);
        sendMessage($chat_id, "متاسفانه محصولی با نام `" . htmlspecialchars($search_term) . "` یافت نشد.", $mainMenuKeyboard, $platform);
        updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
    } else {
        $session_data['search_term'] = $search_term;
        $session_data['state'] = 'idle';
        updateUserField($user_id, 'session', json_encode($session_data));

        $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);
        sendMessage($chat_id, "نتایج جستجو برای `" . htmlspecialchars($search_term) . "`: ({$total_results} مورد)", $mainMenuKeyboard, $platform);
        
        showSearchResult(['offset' => 0], $chat_id, null, $user_id, $platform, $session_data, $user);
    }
}

function showSearchResult(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
     $offset = (int)($params['offset'] ?? 0);
    $search_term = $session_data['search_term'] ?? '';
    $can_edit = ($message_id !== null);
    $is_photo_message = $can_edit && isset($GLOBALS['update']['callback_query']['message']['photo']);
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null;
    $partner_user_id = $user['referred_by_user_id'] ?? null;
    
    $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);

    if (empty($search_term)) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: عبارت جستجو یافت نشد.', 'show_alert' => true], $platform);
        
        if ($message_id) {
            apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform);
        }
        showCustomerMainMenu($chat_id, $user_id, $platform, $user);
        return;
    }

    $total_results = 0;
    if ($partner_user_id !== null) {
        $total_results = countSearchPartnerActiveProducts($partner_user_id, $search_term);
    } else {
        $total_results = countSearchedProducts($search_term);
    }
    
    $base_buttons[] = [['text' => '🔙 بازگشت به منو اصلی', 'callback_data' => buildCallbackData('mainMenu')]];

    if ($total_results == 0) {
        $error_text = "محصولی یافت نشد.";
        $mainMenuKeyboard['inline_keyboard'] = $base_buttons;
        
         if ($is_photo_message && $can_edit) { apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform); sendMessage($chat_id, $error_text, $mainMenuKeyboard, $platform); }
        elseif ($can_edit) { editMessage($chat_id, $message_id, $error_text, ['inline_keyboard' => $base_buttons]); }
        else { sendMessage($chat_id, $error_text, $mainMenuKeyboard, $platform); }
        return;
    }

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

    $products = [];
    if ($partner_user_id !== null) {
        $products = searchPartnerActiveProductsPaginated($partner_user_id, $search_term, 1, $offset);
    } else {
        $products = searchActiveProducts($search_term, 1, $offset);
    }

    if (empty($products)) {
         $error_text = "خطا در بارگذاری نتیجه جستجو.";
         $reply_markup_with_main = $mainMenuKeyboard;
         $reply_markup_with_main['inline_keyboard'] = $base_buttons;
         
         if ($is_photo_message && $can_edit) { apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform); }
         if ($can_edit && !$is_photo_message) { editMessage($chat_id, $message_id, $error_text, ['inline_keyboard' => $base_buttons]); }
         else { sendMessage($chat_id, $error_text, $reply_markup_with_main, $platform); }
        return;
    }
    
    $product = $products[0];
    
    $caption = "";
    $action_buttons = [];
  
    if ($partner_user_id !== null) {
        list($caption, $action_buttons) = buildPartnerCustomerProductDisplay($product, $user_id, $session_data);
    } else {
        list($caption, $action_buttons) = buildProductDisplay($product, $user_id, $session_data);
    }
    
    $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_buttons = $action_buttons;
    if ($total_results > 1) {
        $prev_offset = ($offset - 1 < 0) ? $total_results - 1 : $offset - 1;
        $next_offset = ($offset + 1 >= $total_results) ? 0 : $offset + 1;
        $pagination_row = buildPaginationRowForProductView('searchNav', $offset, $total_results, [], $prev_offset, $next_offset);
        if(!empty($pagination_row)) $final_buttons[] = $pagination_row;
    }
    $final_buttons[] = [['text' => '🔙 بازگشت به منو اصلی', 'callback_data' => buildCallbackData('mainMenu')]];
    
    $mainMenuKeyboard['inline_keyboard'] = $final_buttons;
    $reply_markup = $mainMenuKeyboard;

    if (empty($file_to_send)) {
         $caption .= "\n\n⚠️ *خطا: عکس محصول برای نمایش در دسترس نیست.*";
         if ($is_photo_message && $can_edit) {
             apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform);
             sendMessage($chat_id, $caption, $reply_markup, $platform);
         } elseif ($can_edit) {
             editMessage($chat_id, $message_id, $caption, ['inline_keyboard' => $final_buttons]);
         } else {
             sendMessage($chat_id, $caption, $reply_markup, $platform);
         }
    } else {
        $media = ['type' => 'photo', 'media' => $file_to_send, 'caption' => $caption, 'parse_mode' => 'Markdown'];
        if (!$is_photo_message && $can_edit) {
            apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform);
            apiRequest('sendPhoto', [
                'chat_id' => $chat_id,
                'photo' => $file_to_send,
                'caption' => $caption,
                'parse_mode' => 'Markdown',
                'reply_markup' => $reply_markup
            ], $platform);
        } elseif ($is_photo_message && $can_edit) {
             $current_caption = $GLOBALS['update']['callback_query']['message']['caption'] ?? null;
             $current_photo_id = $GLOBALS['update']['callback_query']['message']['photo'][0]['file_id'] ?? null;
             
             $force_edit_media = ($file_to_send instanceof CURLFile);

             if ($force_edit_media || $current_caption != $caption || $current_photo_id != $file_to_send) {
                apiRequest('editMessageMedia', ['chat_id' => $chat_id, 'message_id' => $message_id, 'media' => json_encode($media), 'reply_markup' => json_encode($reply_markup)], $platform);
             } else {
                apiRequest('editMessageReplyMarkup', ['chat_id' => $chat_id, 'message_id' => $message_id, 'reply_markup' => json_encode($reply_markup)], $platform);
             }
         } else {
             apiRequest('sendPhoto', [
                'chat_id' => $chat_id,
                'photo' =>
$file_to_send,
                'caption' => $caption,
                'parse_mode' => 'Markdown',
                'reply_markup' => $reply_markup
            ], $platform);
         }
    }
}

?>