<?php

error_log("WALLET_TRANSFER_FILE_LOADED");

if (!isset($states[$chat_id]['wallet_transfer']) || !is_array($states[$chat_id]['wallet_transfer'])) {
    $states[$chat_id]['wallet_transfer'] = [];
}

$wt =& $states[$chat_id]['wallet_transfer'];

function wt_save_state(array $states, string $state_file): void
{
    file_put_contents($state_file, json_encode($states, JSON_UNESCAPED_UNICODE));
}

function wt_fetch_transfer_by_reference(PDO $pdo, string $reference): ?array
{
    $sql = "SELECT 
                id,
                reference,
                beneficiary_name,
                beneficiary_mobile,
                send_amount,
                payout_currency,
                status_code,
                status_reason,
                created_at
            FROM new_mw_transfers
            WHERE TRIM(reference) = TRIM(:reference)
            LIMIT 1";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':reference' => trim($reference)
    ]);

    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    return $row ?: null;
}

function wt_format_status($status): string
{
    $status = trim((string)$status);

    // Numeric or code-based mapping
    return match ($status) {
        '0' => 'PENDING',
        '1' => 'COMPLETED',
        '2' => 'FAILED',
        '3' => 'REJECTED',
        '4' => 'UNDER REVIEW',
        default => match (strtoupper($status)) {
            'COMPLETED' => 'COMPLETED',
            'PENDING' => 'PENDING',
            'FAILED' => 'FAILED',
            'REJECTED' => 'REJECTED',
            'UNDER_REVIEW' => 'UNDER REVIEW',
            default => ($status !== '' ? strtoupper($status) : 'UNKNOWN'),
        }
    };
}

function wt_wallet_menu($chat_id): void
{
    sendInlineKeyboard(
        $chat_id,
        "Welcome to the FinoviaPay Digital Wallet Transfer Assistance Center.\n\nPlease choose one of the options below to check your transfer status, report an issue, create a support ticket, or connect with a Wallet Transfer Support Officer.\n\nAll support options below are provided through our secure digital banking support system.",
        [
            [
                ['text' => 'Transfer Status', 'callback_data' => 'wt_status'],
                ['text' => 'Report Transfer Issue', 'callback_data' => 'wt_issue']
            ],
            [
                ['text' => 'Create Wallet Transfer', 'callback_data' => 'wt_ticket'],
                ['text' => 'Talk to Transfer Officer', 'callback_data' => 'wt_agent']
            ],
            [
                ['text' => 'Return to Main Menu', 'callback_data' => 'main_menu']
            ]
        ]
    );
}

# =========================
# MAIN WALLET TRANSFER MENU
# =========================

if (($callbackData ?? '') === 'wallet_transfer') {
    error_log("WT_CALLBACK: wallet_transfer");

    $wt['active'] = true;
    $wt['step'] = 'wallet_menu';
    wt_save_state($states, $state_file);
    wt_wallet_menu($chat_id);
    exit;
}

# =========================
# RETURN TO WALLET MENU
# =========================

if (($callbackData ?? '') === 'wt_back_menu') {
    error_log("WT_CALLBACK: wt_back_menu");

    $wt['active'] = true;
    $wt['step'] = 'wallet_menu';
    wt_save_state($states, $state_file);
    wt_wallet_menu($chat_id);
    exit;
}

# =========================
# TRANSFER STATUS BUTTON
# =========================

if (($callbackData ?? '') === 'wt_status') {
    error_log("WT_CALLBACK: wt_status");

    $wt['active'] = true;
    $wt['step'] = 'await_reference_status';
    wt_save_state($states, $state_file);

    error_log("WT_STATE_SET: await_reference_status");

    sendMessage(
        $chat_id,
        "FinoviaPay Wallet Transfer Status Check\n\nPlease enter your Wallet Transfer Reference Number so that we may retrieve the current status of your transaction from our secure processing system."
    );
    exit;
}

# =======================================
# REPORT TRANSFER ISSUE BUTTON
# =======================================

if (($callbackData ?? '') === 'wt_issue') {
    error_log("WT_CALLBACK: wt_issue");

    $wt['active'] = true;
    $wt['step'] = 'await_reference_issue';
    wt_save_state($states, $state_file);

    error_log("WT_STATE_SET: await_reference_issue");

    sendMessage(
        $chat_id,
        "FinoviaPay Wallet Transfer Issue Reporting\n\nPlease enter your Wallet Transfer Reference Number so that we may review the transfer linked to your issue before proceeding further."
    );
    exit;
}

# =======================================
# CREATE WALLET TRANSFER TICKET BUTTON
# =======================================

if (($callbackData ?? '') === 'wt_ticket') {
    error_log("WT_CALLBACK: wt_ticket");

    $wt['active'] = true;
    $wt['step'] = 'await_reference_ticket';
    wt_save_state($states, $state_file);

    error_log("WT_STATE_SET: await_reference_ticket");

    sendMessage(
        $chat_id,
        "FinoviaPay Wallet Transfer Ticket Creation\n\nPlease enter your Wallet Transfer Reference Number so that we may create a support ticket linked to the correct transaction."
    );
    exit;
}

# =======================================
# TALK TO TRANSFER OFFICER BUTTON
# =======================================

if (($callbackData ?? '') === 'wt_agent') {
    error_log("WT_CALLBACK: wt_agent");

    $wt['active'] = false;
    unset($states[$chat_id]['wallet_transfer']);
    wt_save_state($states, $state_file);

    sendMessage(
        $chat_id,
        "Thank you for contacting FinoviaPay Wallet Transfer Support.\n\nYour request to speak with a Wallet Transfer Support Officer has been successfully submitted and registered in our secure support system.\n\nPlease remain connected while we assign the next available officer from the Wallet Transfer Operations Department.\n\nOnce your assigned officer joins the conversation, you will receive a confirmation message with the officer’s name, Banker Officer ID, and department details."
    );
    exit;
}

# =======================================
# STATUS REFERENCE ENTRY
# =======================================

if (($wt['step'] ?? '') === 'await_reference_status' && !empty($text)) {
    error_log("REFERENCE_ENTERED: " . $text);

    $reference = trim($text);

    try {
        $transfer = wt_fetch_transfer_by_reference($pdo, $reference);
        error_log("DB_RESULT: " . json_encode($transfer));

        if (!$transfer) {
            sendInlineKeyboard(
                $chat_id,
                "FinoviaPay Wallet Transfer Status Check\n\nWe were unable to locate any wallet transfer record matching the reference number you provided.\n\nPlease verify the reference number carefully and try again.\n\nIf you still require assistance, you may create a support ticket or speak with a FinoviaPay Support Officer.",
                [
                    [
                        ['text' => 'Try Again', 'callback_data' => 'wt_status']
                    ],
                    [
                        ['text' => 'Create Ticket', 'callback_data' => 'wt_ticket'],
                        ['text' => 'Talk to Officer', 'callback_data' => 'wt_agent']
                    ],
                    [
                        ['text' => 'Return to Wallet Menu', 'callback_data' => 'wt_back_menu']
                    ]
                ]
            );
            exit;
        }

        $status = wt_format_status($transfer['status_code'] ?? '');
        $statusReason = trim((string)($transfer['status_reason'] ?? ''));

        $msg  = "FinoviaPay Wallet Transfer Status\n\n";
        $msg .= "Transfer Reference: " . ($transfer['reference'] ?? '-') . "\n";
        $msg .= "Beneficiary Name: " . ($transfer['beneficiary_name'] ?? '-') . "\n";
        $msg .= "Beneficiary Mobile: " . ($transfer['beneficiary_mobile'] ?? '-') . "\n";
        $msg .= "Transfer Amount: " . ($transfer['send_amount'] ?? '0') . " " . ($transfer['payout_currency'] ?? '-') . "\n";
        $msg .= "Transaction Date: " . ($transfer['created_at'] ?? '-') . "\n\n";
        $msg .= "Current Status: " . $status;

        if ($statusReason !== '') {
            $msg .= "\nReason / Note: " . $statusReason;
        }

        $msg .= "\n\nIf you are experiencing any issue regarding this transfer, please select one of the support options below.";

        sendInlineKeyboard(
            $chat_id,
            $msg,
            [
                [
                    ['text' => 'Report Issue', 'callback_data' => 'wt_issue'],
                    ['text' => 'Create Ticket', 'callback_data' => 'wt_ticket']
                ],
                [
                    ['text' => 'Talk to Officer', 'callback_data' => 'wt_agent']
                ],
                [
                    ['text' => 'Wallet Menu', 'callback_data' => 'wt_back_menu']
                ]
            ]
        );

        $wt['step'] = 'wallet_menu';
        wt_save_state($states, $state_file);
        exit;

    } catch (Throwable $e) {
        error_log("WT STATUS ERROR: " . $e->getMessage());

        sendMessage(
            $chat_id,
            "We are unable to process your wallet transfer status request at this moment due to a system validation issue.\n\nPlease try again shortly or contact a FinoviaPay Support Officer for assistance."
        );
        exit;
    }
}

# =======================================
# ISSUE FLOW: REFERENCE ENTRY
# =======================================

if (($wt['step'] ?? '') === 'await_reference_issue' && !empty($text)) {
    error_log("ISSUE_REFERENCE_ENTERED: " . $text);

    $reference = trim($text);
    $transfer = wt_fetch_transfer_by_reference($pdo, $reference);

    error_log("ISSUE_DB_RESULT: " . json_encode($transfer));

    if (!$transfer) {
        sendInlineKeyboard(
            $chat_id,
            "FinoviaPay Wallet Transfer Issue Reporting\n\nWe were unable to locate any wallet transfer record matching the reference number you provided.\n\nPlease verify the reference number and try again.\n\nIf you still require assistance, you may return to the Wallet Transfer menu or speak with a Wallet Transfer Support Officer.",
            [
                [
                    ['text' => 'Try Again', 'callback_data' => 'wt_issue']
                ],
                [
                    ['text' => 'Talk to Officer', 'callback_data' => 'wt_agent']
                ],
                [
                    ['text' => 'Return to Wallet Menu', 'callback_data' => 'wt_back_menu']
                ]
            ]
        );
        exit;
    }

    $wt['reference'] = $reference;
    $wt['step'] = 'await_issue_description';
    wt_save_state($states, $state_file);

    sendMessage(
        $chat_id,
        "FinoviaPay Wallet Transfer Issue Reporting\n\nYour reference number has been verified successfully.\n\nPlease briefly describe the issue you are experiencing with this wallet transfer.\n\nYour explanation will help our Wallet Transfer Support Team review your request more efficiently."
    );
    exit;
}

# =======================================
# ISSUE FLOW: DESCRIPTION ENTRY
# =======================================

if (($wt['step'] ?? '') === 'await_issue_description' && !empty($text)) {
    error_log("ISSUE_DESCRIPTION_ENTERED: " . $text);

    $wt['issue_description'] = trim($text);
    $wt['step'] = 'wallet_menu';
    wt_save_state($states, $state_file);

    sendInlineKeyboard(
        $chat_id,
        "Thank you. Your wallet transfer issue details have been recorded successfully.\n\nYou may now create a wallet transfer support ticket or speak directly with a Wallet Transfer Support Officer for further assistance.",
        [
            [
                ['text' => 'Create Support Ticket', 'callback_data' => 'wt_ticket']
            ],
            [
                ['text' => 'Talk to Transfer Officer', 'callback_data' => 'wt_agent']
            ],
            [
                ['text' => 'Return to Wallet Menu', 'callback_data' => 'wt_back_menu']
            ]
        ]
    );
    exit;
}

# =======================================
# TICKET FLOW: REFERENCE ENTRY
# =======================================

if (($wt['step'] ?? '') === 'await_reference_ticket' && !empty($text)) {
    error_log("TICKET_REFERENCE_ENTERED: " . $text);

    $reference = trim($text);
    $transfer = wt_fetch_transfer_by_reference($pdo, $reference);

    error_log("TICKET_DB_RESULT: " . json_encode($transfer));

    if (!$transfer) {
        sendInlineKeyboard(
            $chat_id,
            "FinoviaPay Wallet Transfer Ticket Creation\n\nWe were unable to locate any wallet transfer record matching the reference number you provided.\n\nPlease verify the reference number carefully and try again.\n\nIf you require immediate assistance, you may also speak with a Wallet Transfer Support Officer.",
            [
                [
                    ['text' => 'Try Again', 'callback_data' => 'wt_ticket']
                ],
                [
                    ['text' => 'Talk to Officer', 'callback_data' => 'wt_agent']
                ],
                [
                    ['text' => 'Return to Wallet Menu', 'callback_data' => 'wt_back_menu']
                ]
            ]
        );
        exit;
    }

    $wt['ticket_reference'] = $reference;
    $wt['step'] = 'await_ticket_description';
    wt_save_state($states, $state_file);

    sendMessage(
        $chat_id,
        "FinoviaPay Wallet Transfer Ticket Creation\n\nYour transfer reference number has been verified successfully.\n\nPlease enter a brief description of the issue so that we may create a support ticket for the Wallet Transfer Operations Department."
    );
    exit;
}

# =======================================
# TICKET FLOW: DESCRIPTION ENTRY
# =======================================

if (($wt['step'] ?? '') === 'await_ticket_description' && !empty($text)) {
    error_log("TICKET_DESCRIPTION_ENTERED: " . $text);

    $description = trim($text);
    $reference = trim((string)($wt['ticket_reference'] ?? ''));

    $ticketId = 'FP-WT-' . rand(10000, 99999);

    if (!empty($reference)) {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO support_tickets
                (ticket_id, customer_name, telegram_id, category, department, issue_type, description, status, transfer_reference)
                VALUES
                (:ticket_id, :customer_name, :telegram_id, :category, :department, :issue_type, :description, :status, :transfer_reference)
            ");

            $customerName = $states[$chat_id]['user']['name'] ?? 'Customer';

            $stmt->execute([
                ':ticket_id' => $ticketId,
                ':customer_name' => $customerName,
                ':telegram_id' => $chat_id,
                ':category' => 'Wallet Transfer',
                ':department' => 'Wallet Transfer Operations',
                ':issue_type' => 'Wallet Transfer Issue',
                ':description' => $description,
                ':status' => 'Open',
                ':transfer_reference' => $reference
            ]);

            $stmtMsg = $pdo->prepare("
                INSERT INTO ticket_messages (ticket_id, sender, message, created_at)
                VALUES (:ticket_id, 'user', :message, NOW())
            ");
            $stmtMsg->execute([
                ':ticket_id' => $ticketId,
                ':message' => $description
            ]);

            error_log("TICKET_CREATED_SUCCESS: " . $ticketId);
        } catch (Throwable $e) {
            error_log("TICKET_CREATE_ERROR: " . $e->getMessage());
        }
    }

    unset($states[$chat_id]['wallet_transfer']);
    wt_save_state($states, $state_file);

    sendInlineKeyboard(
        $chat_id,
        "Your wallet transfer support ticket has been successfully created.\n\nTicket ID: {$ticketId}\nDepartment: Wallet Transfer Operations\n\nYour request has been forwarded to the FinoviaPay Wallet Transfer Operations Department for review.\n\nA support officer will review your case and respond to your ticket as soon as possible.\n\nIf additional information is required, you may be contacted through the official FinoviaPay support channel.\n\nThank you for choosing FinoviaPay.",
        [
            [
                ['text' => 'Talk to Transfer Officer', 'callback_data' => 'wt_agent']
            ],
            [
                ['text' => 'Return to Wallet Menu', 'callback_data' => 'wallet_transfer']
            ]
        ]
    );
    exit;
}
?>