<?php

function smarty_function_get_terminal_transactions($params, &$smarty)
{
    $hide = getVal('terminal_hide', null, '');
    if (!$params['order'] || $hide == '1') {
        return;
    }

    $transactions = [];
    foreach ($params['order']->getPaymentsArray() as $payment) {
        if ($payment['status'] != Payment::STATUS_FINISHED) {
            continue;
        }

        $data = json_decode($payment['payment_data'] ?? '', true);
        if ($data['terminal'] ?? false) {
            $lines = explode("\n", trim($data['terminal'] ?? ''));
            $transactions[] = [
                'result_id' => $lines[0] ?? '',                    // 1.Result ID
                'uid' => $lines[1] ?? '',                          // 2.UID
                'result' => $lines[2] ?? '',                       // 3.Result
                'card_mask_pan' => $lines[3] ?? '',                // 4.CardMaskPAN
                'aid' => $lines[4] ?? '',                          // 5.AID
                'card_type' => $lines[5] ?? '',                    // 6.Cardtype
                'terminal_id' => $lines[6] ?? '',                  // 7.TerminalID
                'auth_code' => $lines[7] ?? '',                    // 8.AuthCode
                'seq_number' => $lines[8] ?? '',                   // 9.SeqNumber
                'variable_symbol' => $lines[9] ?? '',              // 10.VariableSymbol
                'datetime' => $lines[10] ?? '',                    // 11.date-time
                'pin_used' => $lines[11] ?? '',                    // 12.PIN
                'signature_check' => $lines[12] ?? '',             // 13.SignatureCheck
                'message' => $lines[13] ?? '',                     // 14.Message/ReasonNotAccepted
                'message2' => $lines[14] ?? '',                    // 15.Message2
                'user_field1' => $lines[15] ?? '',                 // 16.Uživatelské pole
                'undocumented_field' => $lines[16] ?? '',          // 17.Nedokumentované pole
                'user_field2' => $lines[17] ?? '',                 // 18.Uživatelské pole
                'user_field3' => $lines[18] ?? '',                 // 19.Uživatelské pole
                'provider_tid' => $lines[19] ?? '',                // 20.TID poskytovateľa
                'spdh_id' => $lines[20] ?? '',                     // 21.SPDH ID
                'price' => $payment['price'] ?? 0,                 // Uhrazená částka
            ];
        }
    }

    if (!empty($params['assign'])) {
        $smarty->assign($params['assign'], $transactions);
    } else {
        if ($transactions) {
            $params['transactions'] = $transactions;
            echo $smarty->_subTemplateRender('print/terminalTransactions.tpl', $smarty->cache_id, $smarty->compile_id, 0, null, $params, 0, false);
        }
    }
}
