<?php

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

function showStewardSelectionList(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data): void {
    $product_id = (int)($params['id'] ?? ($session_data['editing_product_id'] ?? 0));
    $offset = (int)($params['offset'] ?? 0);
    $limit = defined('ADMIN_USERS_PER_PAGE') ? ADMIN_USERS_PER_PAGE : 5;
    $can_edit = ($message_id !== null);

    if ($product_id <= 0) {
        if ($can_edit) {
            editMessage($chat_id, $message_id, "خطا: محصول نامشخص است.", null);
        } else {
            sendMessage($chat_id, "خطا: محصول نامشخص است.", null, $platform);
        }
        showAdminMainMenu($chat_id, $user_id, $platform);
        return;
    }
    
    $product = getProduct($product_id);
    if (!$product) {
        if ($can_edit) {
            editMessage($chat_id, $message_id, "خطا: محصول یافت نشد.", null);
        } else {
            sendMessage($chat_id, "خطا: محصول یافت نشد.", null, $platform);
        }
        showAdminMainMenu($chat_id, $user_id, $platform);
        return;
    }

    $session_data['editing_product_id'] = $product_id;
    updateUserField($user_id, 'session', json_encode($session_data));

    $users_list = getAllUsers($limit, $offset, null);
    $total_users = countAllUsers(null);

    $buttons = [];
    
    $current_steward_text = "ندارد";
    if (!empty($product['steward_user_id'])) {
        $steward = getUserById($product['steward_user_id']);
        if ($steward) {
            $current_steward_text = htmlspecialchars($steward['first_name'] ?? 'N/A') . " (`{$steward['phone_number']}`)";
        } else {
            $current_steward_text = "ID: `{$product['steward_user_id']}` (کاربر یافت نشد)";
        }
    }

    $text = "👤 *انتخاب انباردار برای محصول: {$product['name']}*\n";
    $text .= "انباردار فعلی: *{$current_steward_text}*\n\n";
    $text .= "لطفا کاربر مورد نظر را برای انبارداری این محصول انتخاب کنید:";

    if (empty($users_list) && $offset === 0) {
        $text .= "\n\n(هیچ کاربری یافت نشد)";
    } else {
         foreach ($users_list as $u) {
            $user_name = htmlspecialchars($u['first_name'] ?? 'بدون نام');
            $user_phone = $u['phone_number'] ? "`{$u['phone_number']}`" : "(`{$u['id']}`)";
            $buttons[] = [['text' => "{$user_name} - {$user_phone}", 'callback_data' => buildCallbackData('confirmSteward', ['pid' => $product_id, 'uid' => $u['id']])]];
        }

        $pagination_row = buildPaginationRow('setSteward', $offset, $limit, $total_users, ['id' => $product_id]);
        if (!empty($pagination_row)) {
            $buttons[] = $pagination_row;
        }
    }

    if (!empty($product['steward_user_id'])) {
        $buttons[] = [['text' => '❌ حذف انباردار فعلی', 'callback_data' => buildCallbackData('confirmSteward', ['pid' => $product_id, 'uid' => '0'])]];
    }
    
    $buttons[] = [['text' => '🔙 بازگشت به ویرایش محصول', 'callback_data' => buildCallbackData('editProd', ['id' => $product_id])]];
    $reply_markup = ['inline_keyboard' => $buttons];

    if ($can_edit) {
        editMessage($chat_id, $message_id, $text, $reply_markup);
    } else {
        sendMessage($chat_id, $text, $reply_markup, $platform);
    }
}

function handleStewardSelection(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data): void {
    $product_id = (int)($params['pid'] ?? 0);
    $steward_user_id_raw = (string)($params['uid'] ?? '-1');
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null;

    if ($product_id <= 0 || $steward_user_id_raw === '-1') {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: اطلاعات ناقص است.', 'show_alert' => true], $platform);
        return;
    }

    $steward_user_id = ($steward_user_id_raw === '0') ? null : (int)$steward_user_id_raw;
    $new_steward_name = "هیچکس";

    if ($steward_user_id !== null) {
        $steward = getUserById($steward_user_id);
        if (!$steward) {
            if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: کاربر انباردار یافت نشد.', 'show_alert' => true], $platform);
            return;
        }
        $new_steward_name = htmlspecialchars($steward['first_name'] ?? 'N/A');
    }

    if (updateProductField($product_id, 'steward_user_id', $steward_user_id)) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => "✅ انباردار به '{$new_steward_name}' تغییر یافت."], $platform);
    } else {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => '❌ خطا در ذخیره انباردار.', 'show_alert' => true], $platform);
    }

    showEditOptions(['id' => $product_id], $chat_id, $message_id, $user_id, $platform, $session_data);
}
?>