<?php

function cardServicesMainMenu($chat_id)
{
    $message = "💳 <b>FinoviaPay Card Services</b>\n\nWelcome to the secure FinoviaPay card services section.\n\nPlease select the card service you would like to continue with. Once selected, our secure support flow will guide your request to the appropriate card operations process.";

    $buttons = [
        [
            ['text' => '💳 Physical Card', 'callback_data' => 'ticket_card_type_physical'],
            ['text' => '🪪 Virtual Card', 'callback_data' => 'ticket_card_type_virtual']
        ],
        [
            ['text' => '🔐 One-Time Card', 'callback_data' => 'ticket_card_type_onetime']
        ],
        [
            ['text' => '↩️ Back to Main Menu', 'callback_data' => 'main_menu']
        ]
    ];

    sendInlineKeyboard($chat_id, $message, $buttons);
}

function physicalCardMenu($chat_id)
{
    $message = "💳 <b>FinoviaPay Physical Card Services</b>\n\nWelcome to the FinoviaPay physical card services menu.\n\nFrom this section, you may review your existing physical card information, request support regarding your physical card, or begin the secure process of requesting a new card.\n\nPlease select one of the professional service options below to continue.";

    $buttons = [
        [
            ['text' => '💳 My Card', 'callback_data' => 'physical_card_my_card']
        ],
        [
            ['text' => '🛠️ Card Support', 'callback_data' => 'physical_card_support']
        ],
        [
            ['text' => '📦 Order New Card', 'callback_data' => 'physical_card_order_new']
        ],
        [
            ['text' => '↩️ Back to Card Services', 'callback_data' => 'card_order']
        ]
    ];

    sendInlineKeyboard($chat_id, $message, $buttons);
}

function cardServicesIssueMenu($chat_id, $cardType)
{
    $message = "💳 <b>FinoviaPay Card Services</b>\n\nSelected Card Type: <b>" . htmlspecialchars((string)$cardType, ENT_QUOTES, 'UTF-8') . "</b>\n\nPlease select the issue category you are experiencing so we may guide your request to the appropriate card operations workflow.";

    $buttons = [
        [
            ['text' => 'Card Declined', 'callback_data' => 'ticket_issue_declined'],
            ['text' => 'Online Payment Failed', 'callback_data' => 'ticket_issue_online_failed']
        ],
        [
            ['text' => 'Card Not Activated', 'callback_data' => 'ticket_issue_not_activated'],
            ['text' => 'Card Blocked', 'callback_data' => 'ticket_issue_blocked']
        ],
        [
            ['text' => 'Other Issue', 'callback_data' => 'ticket_issue_other']
        ],
        [
            ['text' => '↩️ Back to Card Services', 'callback_data' => 'card_order']
        ]
    ];

    sendInlineKeyboard($chat_id, $message, $buttons);
}

function physicalCardPlaceholderMessage($type)
{
    if ($type === 'order_new') {
        return "📦 <b>Order a New Physical Card</b>\n\nThis section will allow customers to begin the secure request process for issuing a new FinoviaPay physical card, including eligibility checks, delivery preference selection, and operational review by our Card Operations Department.\n\nThis feature is currently under preparation and will be introduced shortly.\n\nPlease select another physical card service option or return to the previous menu.";
    }

    return "🛠️ <b>Physical Card Support</b>\n\nYou may continue with secure support for your FinoviaPay physical card.\n\nPlease select the issue category you are experiencing so that we may direct your request to the relevant Card Operations workflow.";
}

function cardServicesGetUserId($states, $chat_id)
{
    return (int)($states[$chat_id]['user']['id'] ?? $states[$chat_id]['identified_user_id'] ?? 0);
}


function cardServicesFetchPhysicalCards(PDO $pdo, int $userId): array
{
    if ($userId <= 0) {
        return [];
    }

    try {
        $stmt = $pdo->prepare("
            SELECT *
            FROM telegram_bot_card_profiles
            WHERE user_id = :user_id
              AND card_type = 'Physical Card'
            ORDER BY id DESC
            LIMIT 10
        ");
        $stmt->execute([':user_id' => $userId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

function cardServicesFindCardById(PDO $pdo, int $userId, int $cardId): ?array
{
    if ($userId <= 0 || $cardId <= 0) {
        return null;
    }

    try {
        $stmt = $pdo->prepare("
            SELECT *
            FROM telegram_bot_card_profiles
            WHERE id = :id
              AND user_id = :user_id
              AND card_type = 'Physical Card'
            LIMIT 1
        ");
        $stmt->execute([
            ':id' => $cardId,
            ':user_id' => $userId
        ]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    } catch (Throwable $e) {
        return null;
    }
}

function cardServicesStatusLabel($status): string
{
    $status = trim((string)$status);
    if ($status === '') {
        return 'Pending for Approval';
    }
    return $status;
}

function cardServicesMaskDigits($last4): string
{
    $last4 = preg_replace('/\D+/', '', (string)$last4);
    if ($last4 === '') {
        return '••••  ••••  ••••  ••••';
    }
    return '••••  ••••  ••••  ' . $last4;
}

function cardServicesVisaUi(array $card): string
{
    $holder = strtoupper(trim((string)($card['card_holder_name'] ?? 'FINOVIAPAY CUSTOMER')));
    if ($holder === '') {
        $holder = 'FINOVIAPAY CUSTOMER';
    }

    $plan = strtoupper(trim((string)($card['card_plan'] ?? 'PHYSICAL CARD')));
    $digits = cardServicesMaskDigits($card['card_last4'] ?? '');
    $status = strtoupper(cardServicesStatusLabel($card['card_status'] ?? 'Pending for Approval'));
    $ref = trim((string)($card['reference_code'] ?? 'REFERENCE PENDING'));

    return "<pre>┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n"
        . "┃  FINOVIAPAY DIGITAL BANKING   ┃\n"
        . "┃  VISA SIGNATURE               ┃\n"
        . "┃                                ┃\n"
        . "┃  " . str_pad(substr($digits, 0, 26), 26) . "  ┃\n"
        . "┃                                ┃\n"
        . "┃  CARD HOLDER                   ┃\n"
        . "┃  " . str_pad(substr($holder, 0, 28), 28) . "┃\n"
        . "┃                                ┃\n"
        . "┃  PLAN   " . str_pad(substr($plan, 0, 20), 20) . "┃\n"
        . "┃  STATUS " . str_pad(substr($status, 0, 20), 20) . "┃\n"
        . "┃                                ┃\n"
        . "┃  REF " . str_pad(substr($ref, 0, 25), 25) . "┃\n"
        . "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛</pre>";
}

function cardServicesShortCardMenu($chat_id, array $cards): void
{
    $primary = $cards[0];

    $holder = trim((string)($primary['card_holder_name'] ?? 'Customer'));
    $plan = trim((string)($primary['card_plan'] ?? 'Physical Card'));
    $status = cardServicesStatusLabel($primary['card_status'] ?? 'Pending for Approval');
    $deliveryDate = trim((string)($primary['card_delivery_date'] ?? ''));
    $deliveryNote = trim((string)($primary['card_delivery_date_text'] ?? 'Not Available Yet'));
    $deliveryShow = $deliveryDate !== '' ? $deliveryDate : $deliveryNote;
    $shippedBy = trim((string)($primary['card_shipped_by'] ?? ''));
    if ($shippedBy == '') {
        $shippedBy = 'Not Available Yet';
    }

    $message  = "💳 <b>My Physical Card</b>\n\n";
    $message .= cardServicesVisaUi($primary) . "\n";
    $message .= "<b>Card Holder</b>\n" . htmlspecialchars($holder, ENT_QUOTES, 'UTF-8') . "\n\n";
    $message .= "<b>Card Plan</b>\n" . htmlspecialchars($plan, ENT_QUOTES, 'UTF-8') . "\n\n";
    $message .= "<b>Current Card Status</b>\n" . htmlspecialchars($status, ENT_QUOTES, 'UTF-8') . "\n\n";
    $message .= "<b>Delivery Date</b>\n" . htmlspecialchars($deliveryShow, ENT_QUOTES, 'UTF-8') . "\n\n";
    $message .= "<b>Card Shipped By</b>\n" . htmlspecialchars($shippedBy, ENT_QUOTES, 'UTF-8') . "\n\n";
    $message .= "Please select your card record below to review the complete banking details.";

    $buttons = [];
    foreach ($cards as $i => $card) {
        $label = '🔎 Open Card Record ' . ($i + 1);
        $buttons[] = [[
            'text' => $label,
            'callback_data' => 'physical_card_view_' . (int)$card['id']
        ]];
    }
    $buttons[] = [[
        'text' => '↩️ Back to Physical Card Menu',
        'callback_data' => 'ticket_card_type_physical'
    ]];

    sendInlineKeyboard($chat_id, $message, $buttons);
}

function cardServicesFullCardDetailsMessage(array $card): string
{
    $holder = trim((string)($card['card_holder_name'] ?? 'Customer'));
    $address = trim((string)($card['card_delivery_address_full'] ?? ''));
    if ($address === '') {
        $address = 'Not Available Yet';
    }

    $plan = trim((string)($card['card_plan'] ?? 'Physical Card'));
    $type = trim((string)($card['card_type'] ?? 'Physical Card'));
    $last4 = trim((string)($card['card_last4'] ?? ''));
    if ($last4 === '') {
        $last4 = 'Not Available Yet';
    }
    $status = cardServicesStatusLabel($card['card_status'] ?? 'Pending for Approval');
    $requiredInfo = trim((string)($card['required_information_details'] ?? ''));
    $deliveryDate = trim((string)($card['card_delivery_date'] ?? ''));
    $deliveryNote = trim((string)($card['card_delivery_date_text'] ?? 'Not Available Yet'));
    $deliveryShow = $deliveryDate !== '' ? $deliveryDate : $deliveryNote;
    $shippedBy = trim((string)($card['card_shipped_by'] ?? ''));
    if ($shippedBy === '') {
        $shippedBy = 'Not Available Yet';
    }
    $tracking = trim((string)($card['shipping_tracking_code'] ?? ''));
    if ($tracking === '') {
        $tracking = 'Not Available Yet';
    }
    $officerComments = trim((string)($card['officer_comments'] ?? ''));
    if ($officerComments === '') {
        $officerComments = 'No officer comments are currently available.';
    }
    $ref = trim((string)($card['reference_code'] ?? 'Not Available Yet'));

    $message  = "🏦 <b>FinoviaPay Physical Card Details</b>\n\n";
    $message .= cardServicesVisaUi($card) . "\n";
    $message .= "╭─ <b>Card Profile</b>\n";
    $message .= "├ <b>Card Holder:</b> " . htmlspecialchars($holder, ENT_QUOTES, 'UTF-8') . "\n";
    $message .= "├ <b>Card Plan:</b> " . htmlspecialchars($plan, ENT_QUOTES, 'UTF-8') . "\n";
    $message .= "├ <b>Card Type:</b> " . htmlspecialchars($type, ENT_QUOTES, 'UTF-8') . "\n";
    $message .= "├ <b>Last 4 Digits:</b> " . htmlspecialchars($last4, ENT_QUOTES, 'UTF-8') . "\n";
    $message .= "├ <b>Status:</b> " . htmlspecialchars($status, ENT_QUOTES, 'UTF-8') . "\n";
    $message .= "├ <b>Delivery Date:</b> " . htmlspecialchars($deliveryShow, ENT_QUOTES, 'UTF-8') . "\n";
    $message .= "├ <b>Shipped By:</b> " . htmlspecialchars($shippedBy, ENT_QUOTES, 'UTF-8') . "\n";
    $message .= "├ <b>Tracking Code:</b> " . htmlspecialchars($tracking, ENT_QUOTES, 'UTF-8') . "\n";
    $message .= "╰ <b>Reference Code:</b> " . htmlspecialchars($ref, ENT_QUOTES, 'UTF-8') . "\n\n";
    $message .= "╭─ <b>Delivery Address</b>\n";
    $message .= "╰ " . htmlspecialchars($address, ENT_QUOTES, 'UTF-8') . "\n\n";

    if (strcasecmp($status, 'Required Additional Information') === 0 && $requiredInfo !== '') {
        $message .= "╭─ <b>Required Additional Information</b>\n";
        $message .= "╰ " . htmlspecialchars($requiredInfo, ENT_QUOTES, 'UTF-8') . "\n\n";
    }

    $message .= "╭─ <b>Officer Comments</b>\n";
    $message .= "╰ " . htmlspecialchars($officerComments, ENT_QUOTES, 'UTF-8') . "\n\n";
    $message .= "💬 <b>Need Assistance?</b>\n";
    $message .= "If you have any questions regarding your FinoviaPay card status, delivery progress, or required information, please contact our customer support team for professional assistance.";

    return $message;
}
if ($callbackId) {
    answerCallbackQuery($callbackId);
}

/* Main Card Services landing */
if ($callbackData === 'card_order') {
    $states[$chat_id]['step'] = 'ticket_card_type';
    saveStates($states, $state_file);
    cardServicesMainMenu($chat_id);
    exit;
}

/* Physical Card submenu */
if ($callbackData === 'ticket_card_type_physical') {
    $states[$chat_id]['step'] = 'physical_card_menu';
    $states[$chat_id]['ticket_flow']['card_type'] = 'Physical Card';
    saveStates($states, $state_file);
    physicalCardMenu($chat_id);
    exit;
}

/* Physical Card submenu actions */
if ($callbackData === 'physical_card_my_card') {
    $userId = cardServicesGetUserId($states, $chat_id);
    $cards = cardServicesFetchPhysicalCards($pdo, $userId);

    if (empty($cards)) {
        sendInlineKeyboard(
            $chat_id,
            "💳 <b>My Physical Card</b>\n\nNo physical card order record is currently available for your verified FinoviaPay account.\n\nIf you would like to request a new card or need assistance, please select one of the service options below.",
            [
                [['text' => '📦 Order New Card', 'callback_data' => 'physical_card_order_new']],
                [['text' => '🛠️ Card Support', 'callback_data' => 'physical_card_support']],
                [['text' => '↩️ Back to Physical Card Menu', 'callback_data' => 'ticket_card_type_physical']]
            ]
        );
        exit;
    }

    cardServicesShortCardMenu($chat_id, $cards);
    exit;
}

if (strpos((string)$callbackData, 'physical_card_view_') === 0) {
    $userId = cardServicesGetUserId($states, $chat_id);
    $cardId = (int)str_replace('physical_card_view_', '', (string)$callbackData);
    $card = cardServicesFindCardById($pdo, $userId, $cardId);

    if (!$card) {
        sendInlineKeyboard(
            $chat_id,
            "We were unable to locate the selected physical card record for your account. Please return to your card list and try again.",
            [
                [['text' => '↩️ Back to My Card', 'callback_data' => 'physical_card_my_card']],
                [['text' => '↩️ Back to Physical Card Menu', 'callback_data' => 'ticket_card_type_physical']]
            ]
        );
        exit;
    }

    sendInlineKeyboard(
        $chat_id,
        cardServicesFullCardDetailsMessage($card),
        [
            [['text' => '💬 Contact Customer Support', 'callback_data' => 'physical_card_support']]
        ],
        [
            [['text' => '↩️ Back to My Card', 'callback_data' => 'physical_card_my_card']],
            [['text' => '↩️ Back to Physical Card Menu', 'callback_data' => 'ticket_card_type_physical']]
        ]
    );
    exit;
}

if ($callbackData === 'physical_card_order_new') {
    sendInlineKeyboard(
        $chat_id,
        physicalCardPlaceholderMessage('order_new'),
        [
            [['text' => '↩️ Back to Physical Card Menu', 'callback_data' => 'ticket_card_type_physical']],
            [['text' => '↩️ Back to Card Services', 'callback_data' => 'card_order']]
        ]
    );
    exit;
}

if ($callbackData === 'physical_card_support') {
    $states[$chat_id]['step'] = 'ticket_issue_type';
    $states[$chat_id]['ticket_flow']['card_type'] = 'Physical Card';
    saveStates($states, $state_file);
    cardServicesIssueMenu($chat_id, 'Physical Card');
    exit;
}

/* Other card types */
if ($callbackData === 'ticket_card_type_virtual' || $callbackData === 'ticket_card_type_onetime') {
    $cardTypeMap = [
        'ticket_card_type_virtual' => 'Virtual Card',
        'ticket_card_type_onetime' => 'One-Time Card'
    ];
    $selectedCardType = $cardTypeMap[$callbackData] ?? 'Card';

    $states[$chat_id]['step'] = 'ticket_issue_type';
    $states[$chat_id]['ticket_flow']['card_type'] = $selectedCardType;
    saveStates($states, $state_file);

    cardServicesIssueMenu($chat_id, $selectedCardType);
    exit;
}

/* Issue selection */
if (strpos((string)$callbackData, 'ticket_issue_') === 0) {
    $issueMap = [
        'ticket_issue_declined' => 'Card Declined',
        'ticket_issue_online_failed' => 'Online Payment Failed',
        'ticket_issue_not_activated' => 'Card Not Activated',
        'ticket_issue_blocked' => 'Card Blocked',
        'ticket_issue_other' => 'Other Issue'
    ];
    $selectedIssue = $issueMap[$callbackData] ?? 'Other Issue';

    $states[$chat_id]['step'] = 'ticket_description';
    $states[$chat_id]['ticket_flow']['card_type'] = $states[$chat_id]['ticket_flow']['card_type'] ?? 'Card';
    $states[$chat_id]['ticket_flow']['issue_type'] = $selectedIssue;
    saveStates($states, $state_file);

    $cardType = $states[$chat_id]['ticket_flow']['card_type'] ?? 'Card';
    sendMessage(
        $chat_id,
        "💳 <b>FinoviaPay Card Services</b>\n\nSelected Card Type: <b>" . htmlspecialchars((string)$cardType, ENT_QUOTES, 'UTF-8') . "</b>\nSelected Issue: <b>" . htmlspecialchars((string)$selectedIssue, ENT_QUOTES, 'UTF-8') . "</b>\n\nPlease briefly describe the issue you are experiencing. Your message will be attached to a secure card services support ticket for review by our Card Operations Department."
    );
    exit;
}

/* Restore card menus if state returns without callback */
if (($states[$chat_id]['step'] ?? '') === 'physical_card_menu' && empty($callbackData) && empty($text)) {
    physicalCardMenu($chat_id);
    exit;
}

if (($states[$chat_id]['step'] ?? '') === 'ticket_card_type' && empty($callbackData) && empty($text)) {
    cardServicesMainMenu($chat_id);
    exit;
}

if (($states[$chat_id]['step'] ?? '') === 'ticket_issue_type' && empty($callbackData) && empty($text)) {
    $cardType = $states[$chat_id]['ticket_flow']['card_type'] ?? 'Card';
    cardServicesIssueMenu($chat_id, $cardType);
    exit;
}

?>