<?php

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


function showProvinceSelector(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    $offset = (int)($params['offset'] ?? 0);
    $can_edit = ($message_id !== null);
    $callback_query_id = $can_edit ? ($GLOBALS['update']['callback_query']['id'] ?? null) : null;


    $session_data['state'] = 'awaiting_checkout_province';
    unset($session_data['checkout']['city'], $session_data['checkout']['address_text']);
    unset($session_data['checkout']['postal_code'], $session_data['checkout']['note']);
    updateUserField($user_id, 'session', json_encode($session_data));

    $province_keyboard_markup = buildProvinceKeyboard($offset);
    $limit = defined('PROVINCES_CITIES_PER_PAGE') ? PROVINCES_CITIES_PER_PAGE : 8;
    $page = floor($offset / $limit) + 1;
    $prov_text = "لطفا استان محل سکونت خود را انتخاب کنید" . ($page > 1 ? " (صفحه {$page})" : '') . ":";

    if ($can_edit) {
        
        $current_text = $GLOBALS['update']['callback_query']['message']['text'] ?? null;
        $current_markup_json = isset($GLOBALS['update']['callback_query']['message']['reply_markup']) ? json_encode($GLOBALS['update']['callback_query']['message']['reply_markup']) : null;
        $new_markup_json = json_encode($province_keyboard_markup);

        if ($current_text !== $prov_text || $current_markup_json !== $new_markup_json) {
            editMessage($chat_id, $message_id, $prov_text, $province_keyboard_markup);
        } elseif ($callback_query_id) {
            
             apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id], $platform);
        }
        
    } else {
        
        $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);
        $mainMenuKeyboard['inline_keyboard'] = $province_keyboard_markup['inline_keyboard'];
        sendMessage($chat_id, $prov_text, $mainMenuKeyboard, $platform);
    }
}


function handleProvinceSelection(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    $province_index = $params['p_idx'] ?? -1;
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null;
    $can_edit = ($message_id !== null);


    $provinces_cities = $GLOBALS['provinces_cities'] ?? [];
    if (empty($provinces_cities) && function_exists('get_iran_provinces_and_cities')) {
         $GLOBALS['provinces_cities'] = get_iran_provinces_and_cities();
         $provinces_cities = $GLOBALS['provinces_cities'];
    }
    $provinces = array_keys($provinces_cities);
    sort($provinces);

    if ($province_index >= 0 && isset($provinces[$province_index])) {
        $selected_province = $provinces[$province_index];
        $session_data['checkout']['province'] = $selected_province;
        $session_data['checkout']['province_index'] = $province_index;
        unset($session_data['checkout']['city'], $session_data['checkout']['address_text']);
        unset($session_data['checkout']['postal_code'], $session_data['checkout']['note']);
        $session_data['state'] = 'awaiting_checkout_city';
        updateUserField($user_id, 'session', json_encode($session_data));


        $city_keyboard_markup = buildCityKeyboard($province_index, 0);
        $city_text = "استان '{$selected_province}' انتخاب شد. لطفا شهر خود را انتخاب کنید:";
        if ($can_edit) {
            editMessage($chat_id, $message_id, $city_text, $city_keyboard_markup);
        } else {
            $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);
            $mainMenuKeyboard['inline_keyboard'] = $city_keyboard_markup['inline_keyboard'];
            sendMessage($chat_id, $city_text, $mainMenuKeyboard, $platform);
        }
    } else {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: استان نامعتبر.', 'show_alert' => true], $platform);

        showProvinceSelector([], $chat_id, $message_id, $user_id, $platform, $session_data, $user);
    }
}


function showCitySelector(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    $offset = (int)($params['offset'] ?? 0);
    $province_index = (int)($params['p_idx'] ?? ($session_data['checkout']['province_index'] ?? -1));
    $can_edit = ($message_id !== null);
    $callback_query_id = $can_edit ? ($GLOBALS['update']['callback_query']['id'] ?? null) : null;

    if ($province_index < 0) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: استان مشخص نیست.', 'show_alert' => true], $platform);
        showProvinceSelector([], $chat_id, $message_id, $user_id, $platform, $session_data, $user);
        return;
    }


    $session_data['state'] = 'awaiting_checkout_city';
    updateUserField($user_id, 'session', json_encode($session_data));

    $provinces_cities = $GLOBALS['provinces_cities'] ?? [];
     if (empty($provinces_cities) && function_exists('get_iran_provinces_and_cities')) {
         $GLOBALS['provinces_cities'] = get_iran_provinces_and_cities();
         $provinces_cities = $GLOBALS['provinces_cities'];
     }
    $provinces = array_keys($provinces_cities);
    sort($provinces);
    $province_name = $provinces[$province_index] ?? 'نامشخص';

    $city_keyboard_markup = buildCityKeyboard($province_index, $offset);
    $limit = defined('PROVINCES_CITIES_PER_PAGE') ? PROVINCES_CITIES_PER_PAGE : 8;
    $page = floor($offset / $limit) + 1;
    $city_text = "لطفا شهر خود را در استان '{$province_name}' انتخاب کنید" . ($page > 1 ? " (صفحه {$page})" : '') . ":";

    if ($can_edit) {
        
        $current_text = $GLOBALS['update']['callback_query']['message']['text'] ?? null;
        $current_markup_json = isset($GLOBALS['update']['callback_query']['message']['reply_markup']) ? json_encode($GLOBALS['update']['callback_query']['message']['reply_markup']) : null;
        $new_markup_json = json_encode($city_keyboard_markup);

        if ($current_text !== $city_text || $current_markup_json !== $new_markup_json) {
             editMessage($chat_id, $message_id, $city_text, $city_keyboard_markup);
        } elseif ($callback_query_id) {
             apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id], $platform);
        }
        
    } else {
        $mainMenuKeyboard = getCustomerMainMenuKeyboard($user);
        $mainMenuKeyboard['inline_keyboard'] = $city_keyboard_markup['inline_keyboard'];
        sendMessage($chat_id, $city_text, $mainMenuKeyboard, $platform);
    }
}


function handleCitySelection(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    $province_index = (int)($params['p_idx'] ?? ($session_data['checkout']['province_index'] ?? -1));
    $city_index = (int)($params['c_idx'] ?? -1);
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null;
    $can_edit = ($message_id !== null);

    if ($province_index < 0) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: استان مشخص نیست.', 'show_alert' => true], $platform);
        showProvinceSelector([], $chat_id, $message_id, $user_id, $platform, $session_data, $user);
        return;
    }

    $provinces_cities = $GLOBALS['provinces_cities'] ?? [];
     if (empty($provinces_cities) && function_exists('get_iran_provinces_and_cities')) {
         $GLOBALS['provinces_cities'] = get_iran_provinces_and_cities();
         $provinces_cities = $GLOBALS['provinces_cities'];
     }
    $provinces = array_keys($provinces_cities);
    sort($provinces);
    $province_name = $provinces[$province_index] ?? null;
    $cities = isset($GLOBALS['provinces_cities'][$province_name]) ? $GLOBALS['provinces_cities'][$province_name] : [];
    sort($cities);

    if ($city_index >= 0 && isset($cities[$city_index])) {
        $selected_city = $cities[$city_index];
        $session_data['checkout']['city'] = $selected_city;
        unset($session_data['checkout']['address_text'], $session_data['checkout']['postal_code'], $session_data['checkout']['note']);
        $session_data['state'] = 'awaiting_checkout_address';
        updateUserField($user_id, 'session', json_encode($session_data));

        $address_prompt = "شهر '{$selected_city}' انتخاب شد.\n\nلطفا آدرس دقیق پستی خود را (شامل خیابان، کوچه، پلاک، واحد) وارد کنید:";
        
        $cancel_keyboard = ['keyboard' => [[['text' => 'انصراف']]], 'resize_keyboard' => true, 'one_time_keyboard' => true];
        
        
        if ($can_edit) {
             apiRequest('deleteMessage', ['chat_id' => $chat_id, 'message_id' => $message_id], $platform);
        }
        sendMessage($chat_id, $address_prompt, null, $platform); 
        sendMessage($chat_id, "👇", $cancel_keyboard, $platform); 

    } else {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: شهر نامعتبر است.', 'show_alert' => true], $platform);
        showCitySelector(['p_idx' => $province_index], $chat_id, $message_id, $user_id, $platform, $session_data, $user);
    }
}


function handleAddressInput(array $message, int $chat_id, int $user_id, string $platform, array $session_data, array $user): void {
    $address_text = trim($message['text'] ?? '');

    if (!empty($address_text)) {
        $session_data['checkout']['address_text'] = strip_tags($address_text);
        $session_data['state'] = 'awaiting_checkout_postalcode';
        updateUserField($user_id, 'session', json_encode($session_data));
        sendMessage($chat_id, "آدرس دریافت شد.\n\nلطفا کد پستی ۱۰ رقمی معتبر را وارد کنید:", ['keyboard' => [[['text' => 'انصراف']]], 'resize_keyboard' => true], $platform);
    } else {
        sendMessage($chat_id, "آدرس نمی‌تواند خالی باشد. لطفا آدرس دقیق خود را وارد کنید یا انصراف دهید.", null, $platform);
    }
}


function handlePostalCodeInput(array $message, int $chat_id, int $user_id, string $platform, array $session_data, array $user): void {
    $postal_code_raw = trim($message['text'] ?? '');
    $postal_code = convertPersianToEnglishDigits($postal_code_raw);

    if (validatePostalCodeFormat($postal_code)) {
        $session_data['checkout']['postal_code'] = $postal_code;
        $session_data['state'] = 'awaiting_order_note';
        updateUserField($user_id, 'session', json_encode($session_data));
        sendMessage(
             $chat_id,
             "کد پستی `{$postal_code}` دریافت شد.\n\nاگر توضیحات یا یادداشتی برای سفارش خود دارید (مثلا رنگ خاص، زمان ارسال و...) آن را بنویسید. در غیر این صورت، دکمه 'رد شدن' را بزنید.",
             ['keyboard' => [[['text' => 'رد شدن و ادامه']]], 'resize_keyboard' => true, 'one_time_keyboard' => true],
             $platform
        );
    } else {
        sendMessage($chat_id, "کد پستی نامعتبر است. لطفا یک کد ۱۰ رقمی صحیح وارد کنید یا انصراف دهید.", null, $platform);
    }
}

?>