<?php

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

/**
 * Asks the user to enter a discount code.
 */
function askForDiscountCode(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    // Check if already awaiting confirmation, otherwise might cause issues
    if(($session_data['state'] ?? 'idle') !== 'awaiting_payment_confirmation') {
        // Avoid changing state if not in confirmation step
        return; 
    }

    $session_data['state'] = 'awaiting_discount_code';
    updateUserField($user_id, 'session', json_encode($session_data));
    $prompt = "🎟 لطفا کد تخفیف خود را وارد کنید:";
    $cancel_keyboard = ['keyboard' => [[['text' => 'انصراف']]], 'resize_keyboard' => true, 'one_time_keyboard' => true];

    if ($message_id) {
        editMessage($chat_id, $message_id, $prompt, null); // Remove inline keyboard
    } else {
        sendMessage($chat_id, $prompt, null, $platform);
    }
    // Send reply keyboard with cancel option
    sendMessage($chat_id, "👇", $cancel_keyboard, $platform);
}

/**
 * Handles the discount code input from the user.
 */
function handleDiscountCodeInput(array $message, int $chat_id, int $user_id, string $platform, array $session_data, array $user): void {
    $code_raw = trim($message['text'] ?? '');
    if (empty($code_raw)) {
        sendMessage($chat_id, "لطفا کد تخفیف را وارد کنید یا انصراف دهید.", null, $platform);
        // Resend cancel button
        sendMessage($chat_id, "👇", ['keyboard' => [[['text' => 'انصراف']]], 'resize_keyboard' => true, 'one_time_keyboard' => true], $platform);
        return;
    }
    
    $code = strtoupper(convertPersianToEnglishDigits($code_raw)); // Normalize

    // Basic format validation
    if (!validateDiscountCodeFormat($code)) { // Assumes ValidationHelpers loaded
         sendMessage($chat_id, "❌ فرمت کد تخفیف نامعتبر است (فقط حروف انگلیسی بزرگ و اعداد). لطفا مجددا وارد کنید.", null, $platform);
         // Keep state as awaiting_discount_code, resend cancel button
         sendMessage($chat_id, "👇", ['keyboard' => [[['text' => 'انصراف']]], 'resize_keyboard' => true, 'one_time_keyboard' => true], $platform);
         return;
    }
    
    // Validate the code logic (existence, expiry, usage)
    $validation = validateDiscountCode($code); // Assumes DiscountQueries loaded

    // Calculate current subtotal (needed to apply discount)
    $cart_items = getCartContents($user_id); // Assumes CartQueries loaded
    if (empty($cart_items)) {
         sendMessage($chat_id, "سبد خرید شما خالی است. عملیات لغو شد.", ['remove_keyboard' => true], $platform);
         updateUserField($user_id, 'session', json_encode(['state' => 'idle']));
         showCustomerMainMenu($chat_id, $user_id, $platform, $user);
         return;
    }
    $subtotal = '0.00';
    foreach ($cart_items as $item) {
        $subtotal = bcadd($subtotal, bcmul((string)$item['quantity'], (string)$item['pricing']['price'], BC_SCALE), BC_SCALE);
    }

    if ($validation['valid']) {
        $discount = $validation['discount'];
        $result = applyDiscountToTotal($subtotal, $discount); // Assumes DiscountQueries loaded
        $discount_amount = $result['discount_amount'];

        // Store discount info in session
        $session_data['checkout']['discount_code'] = $code;
        $session_data['checkout']['discount_amount'] = $discount_amount;
        $session_data['state'] = 'awaiting_payment_confirmation'; // Move back to confirmation
        updateUserField($user_id, 'session', json_encode($session_data));

        // Show updated summary
        $message_body = "✅ کد تخفیف `{$code}` با موفقیت اعمال شد.";
        // Pass null message_id to send new message, removing reply keyboard
        showPaymentConfirmation($chat_id, $user_id, null, $platform, $session_data, $user, $message_body);

    } else {
         
         // Invalid code - show error and reshow confirmation without discount
        $session_data['state'] = 'awaiting_payment_confirmation'; // Go back to confirmation state
        // Remove any previous discount attempt
        unset($session_data['checkout']['discount_code'], $session_data['checkout']['discount_amount']);
        updateUserField($user_id, 'session', json_encode($session_data));
        
        $error_message = "❌ " . $validation['message'] . "\n\nلطفا مجددا کد تخفیف را وارد کنید (با استفاده از دکمه 'ثبت کد تخفیف')، پرداخت را تایید کنید یا انصراف دهید.";
        // Pass null message_id to send new message, removing reply keyboard
        showPaymentConfirmation($chat_id, $user_id, null, $platform, $session_data, $user, $error_message);
    }
}


/**
 * Handles removing an applied discount code.
 */
function handleRemoveDiscount(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    // Remove discount from session
    unset($session_data['checkout']['discount_code']);
    unset($session_data['checkout']['discount_amount']);
    $session_data['state'] = 'awaiting_payment_confirmation';
    updateUserField($user_id, 'session', json_encode($session_data));

    // Show updated summary by editing the existing message
    $message_body = "کد تخفیف حذف شد.";
    showPaymentConfirmation($chat_id, $user_id, $message_id, $platform, $session_data, $user, $message_body);
}

?>