<?php

defined('ABSPATH') || exit;

function primer_display_watermark(): void {
    $receipt_id     = get_the_ID();
    $order_id       = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $check_api_type = get_post_meta($receipt_id, 'send_to_api_type', true);

    $watermark_wrapper = (empty($check_api_type) || $check_api_type !== 'production')
        ? '<div class="watermark_message">' . __((empty($check_api_type) || wc_get_order($order_id)->get_billing_country() === 'GR') ? 'ΑΚΥΡΟ' : 'INVALID', 'primer') . '</div>' : '';

    $allowed_html = array(
        'div' => array('class' => array())
    );

    echo wp_kses($watermark_wrapper, $allowed_html);
}

function primer_display_issuer_container(): void {
    $receipt_id          = get_the_ID();
    $primer_license_data = get_option('primer_licenses');
    $order_id            = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $branchID            = get_post_meta($receipt_id, 'branchID', true);
    $order               = wc_get_order($order_id);
    $is_greece           = $order->get_billing_country() == 'GR' ? true : false;
    $is_central          = true;

    $branchID = ($branchID == null) ? "0" : $branchID;
    if (isset($branchID) && $branchID != "0") {
        $found_subsidiary = null;
        $is_central       = false;
        foreach ($primer_license_data['subsidiaries'] as $subsidiary) {
            if ($subsidiary['branchId'] == $branchID) {
                $found_subsidiary = $subsidiary;
                break;
            }
        }
        $subsidiary_city   = $found_subsidiary['city'] ?? '';
        $subsidiary_street = $found_subsidiary['street'] ?? '';
        $subsidiary_tk     = $found_subsidiary['tk'] ?? '';
        $subsidiary_doy    = $found_subsidiary['doy'] ?? '';
        $subsidiary_number = $found_subsidiary['number'] ?? '';
        $subsidiary_phone  = $found_subsidiary['phoneNumber'] ?? '';
    }

    $issuer_container = '';
    if (!empty($primer_license_data)) {
        if ($is_central) {
            $issuer_container .= !empty($primer_license_data['companyName'])
                ? '<span class="issuer_name skin">' . (!$is_greece && !empty($primer_license_data['translated_company_name'])
                    ? $primer_license_data['translated_company_name'] : $primer_license_data['companyName']) . '</span>'
                : '<span class="issuer_name skin">' . __('ISSUER\'S COMPANY NAME', 'primer') . '</span>';
            $issuer_container .= !empty($primer_license_data['companySmallName'])
                ? '<p><span class="issuer_name skin">' . (!$is_greece && !empty($primer_license_data['translated_company_small_name'])
                    ? $primer_license_data['translated_company_small_name'] : $primer_license_data['companySmallName']) . '</span></p>' : '';
            $issuer_container .= !empty($primer_license_data['companyActivity'])
                ? '<p> <span class="issuer_subjectField skin company_activity">' . (!$is_greece && !empty($primer_license_data['translated_company_activity']) ? $primer_license_data['translated_company_activity'] : $primer_license_data['companyActivity']) . '</span></p>'
                : '<p> <span class="issuer_subjectField skin">' . __('COMPANY ACTIVITY', 'primer') . '</span></p>';

            $issuer_container .= !empty($primer_license_data['companyAddress'] && $primer_license_data['companyCity'] && $primer_license_data['companyTk'] && $primer_license_data['companyPhoneNumber'] && $primer_license_data['companyDoy'])
                ? (!$is_greece && !empty($primer_license_data['translated_company_address']) && !empty($primer_license_data['translated_company_city'])
                    ? '<p><span class="issuer_subjectField skin">' . $primer_license_data['translated_company_address'] . ', ' . $primer_license_data['translated_company_city'] . ', ' . $primer_license_data['companyTk'] . ', <span>PHONE. </span>' . $primer_license_data['companyPhoneNumber'] . ', <span>DΟΥ: </span>' . $primer_license_data['translated_company_doy'] . '</span></p>'
                    : '<p><span class="issuer_subjectField skin">' . $primer_license_data['companyAddress'] . ', ' . $primer_license_data['companyCity'] . ', ' . $primer_license_data['companyTk'] . ', <span>ΤΗΛ. </span>' . $primer_license_data['companyPhoneNumber'] . ', <span>ΔΟΥ: </span>' . $primer_license_data['companyDoy'] . '</span></p>')
                : '<p><span class="issuer_subjectField skin">' . __('ISSUER\'S COMPANY ADDRESS', 'primer') . ', ' . __('ISSUER\'S COMPANY CITY', 'primer') . ', ' . __('ISSUER\'S COMPANY TK', 'primer') . ', ' . __('ISSUER\'S COMPANY PHONE', 'primer') . ', ' . __('ISSUER\'S COMPANY DOY', 'primer') . '</span></p>';

            $issuer_container .= !empty($primer_license_data['companyVatNumber'])
                ? '<p><span class="issuer_address skin">' . ($is_greece ? __('ΑΦΜ: ', 'primer') : __('VAT: ', 'primer')) . 'EL' . $primer_license_data['companyVatNumber'] . ', ' . ($is_greece ? __('ΓΕΜΗ: ', 'primer') . ($primer_license_data['gemh'] ?? '') : __('GEMH: ', 'primer')) . '</span></p>'
                : '<p><span class="issuer_address skin">ΑΦΜ: </span></p>';
        } else {
            $issuer_container .= !empty($primer_license_data['companyName'])
                ? '<span class="issuer_name skin">' . (!$is_greece && !empty($primer_license_data['translated_company_name'])
                    ? $primer_license_data['translated_company_name'] : $primer_license_data['companyName']) . '</span>'
                : '<span class="issuer_name skin">' . __('ISSUER\'S COMPANY NAME', 'primer') . '</span>';
            $issuer_container .= !empty($primer_license_data['companySmallName'])
                ? '<p><span class="issuer_name skin">' . (!$is_greece && !empty($primer_license_data['translated_company_small_name'])
                    ? $primer_license_data['translated_company_small_name'] : $primer_license_data['companySmallName']) . '</span></p>' : '';
            $issuer_container .= !empty($primer_license_data['companyActivity'])
                ? '<p> <span class="issuer_subjectField skin company_activity">' . (!$is_greece && !empty($primer_license_data['translated_company_activity']) ? $primer_license_data['translated_company_activity'] : $primer_license_data['companyActivity']) . '</span></p>'
                : '<p> <span class="issuer_subjectField skin">' . __('COMPANY ACTIVITY', 'primer') . '</span></p>';

            $issuer_container .= !empty($primer_license_data['companyVatNumber'])
                ? '<p><span class="issuer_address skin">' . ($is_greece ? __('ΑΦΜ: ', 'primer') : __('VAT: ', 'primer')) . ' ' . $primer_license_data['companyVatNumber'] . '</span></p>'
                : '<p><span class="issuer_address skin">ΑΦΜ: </span></p>';

            if ($branchID != null && $branchID != "0") {
                $issuer_container .= '<p><span class="issuer_address skin">' . ($is_greece ? __('Υποκατάστημα: ', 'primer') : __('Branch: ', 'primer')) . $subsidiary_street . ' ' . $subsidiary_number . '</span></p>';
                $issuer_container .= !empty($subsidiary_street)
                    ? '<p><span class="issuer_subjectField skin">' . $subsidiary_city . ', ' . $subsidiary_tk . '</span>' : '';
                $issuer_container .= !empty($subsidiary_doy)
                    ? '<p><span class="issuer_address skin">' . ($is_greece ? __('Δ.Ο.Υ: ', 'primer') : __('DOY: ', 'primer')) . ' ' . $subsidiary_doy . '</span></p>' : '';
                $issuer_container .= !empty($subsidiary_phone)
                    ? '<p><span class="issuer_address skin">' . ($is_greece ? __('ΤΗΛΕΦΩΝΟ: ', 'primer') : __('PHONE: ', 'primer')) . ' ' . $subsidiary_phone . '</span></p>' : '';
                $issuer_container .= !empty($primer_license_data['gemh']) && $primer_license_data['gemh'] != 'empty'
                    ? '<p><span class="issuer_address skin">' . ($is_greece ? __('ΓΕΜΗ: ', 'primer') : __('GEMH: ', 'primer')) . ' ' . $primer_license_data['gemh'] . '</span></p>' : '';
            }
        }
    }

    $allowed_html = array(
        'p'    => array('class' => array()),
        'span' => array('class' => array())
    );

    echo wp_kses($issuer_container, $allowed_html);
}

function primer_main_info_table_head(): void {
    $receipt_id = get_the_ID();
    $order_id   = get_post_meta($receipt_id, 'order_id_to_receipt', true);

    $labes = wc_get_order($order_id)->get_billing_country() == 'GR'
        ? ['ΕΙΔΟΣ ΠΑΡΑΣΤΑΤΙΚΟΥ', 'ΣΕΙΡΑ', 'ΑΡΙΘΜΟΣ', 'ΗΜΕΡ/ΝΙΑ', 'ΩΡΑ']
        : ['INVOICE TYPE', 'SERIES', 'INVOICE NUMBER', 'DATE', 'TIME'];

    $issuer_main_info_table_head = '<tr class="heading"><td><p>' . implode('</p></td><td><p>', $labes) . '</p></td></tr>';

    $allowed_html = array(
        'tr'   => array('class' => array()),
        'td'   => array(),
        'p'    => array('class' => array()),
        'span' => array('class' => array())
    );

    echo wp_kses($issuer_main_info_table_head, $allowed_html);
}

function primer_display_issuer_product_head(): void {
    $receipt_id             = get_the_ID();
    $order_id               = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $order                  = wc_get_order($order_id);
    $is_greece              = ($order->get_billing_country() == 'GR') ? true : false;

    $issuer_product_head  = '<tr class="heading ">';

    $issuer_product_head .= '<td class="code_head_td"><p>' . ($is_greece ? 'ΚΩΔΙΚΟΣ' : 'PRODUCT ID') . '</p></td>';
    $issuer_product_head .= '<td class="description_head_td"><p>' . ($is_greece ? 'ΠΕΡΙΓΡΑΦΗ' : 'DESCRIPTION') . '</p></td>';
    $issuer_product_head .= '<td class="quantity_head_td"><p>' . ($is_greece ? 'ΠΟΣΟΤΗΤΑ' : 'PIECES') . '</p></td>';
    $issuer_product_head .= '<td class="mu_head_td"><p>' . ($is_greece ? 'Μ.Μ' : 'UNIT') . '</p></td>';
    $issuer_product_head .= '<td class="up_head_td"><p>' . ($is_greece ? 'ΤΙΜΗ ΜΟΝΑΔΑΣ' : 'PRICE PER UNIT') . '</p></td>';
    $issuer_product_head .= '<td class="vat_head_td"><p>' . ($is_greece ? 'ΦΠΑ %' : 'VAT %') . '</p></td>';
    $issuer_product_head .= '<td class="pricenovat_head_td"><p>' . ($is_greece ? 'ΤΙΜΗ ΠΡΟ ΦΠΑ' : 'PRICE BEFORE TAXES') . '</p></td>';
    $issuer_product_head .= '<td class="pricenovat_head_td"><p>' . ($is_greece ? 'ΑΞΙΑ ΦΠΑ' : 'VAT PRICE') . '</p></td>';
    $issuer_product_head .= '<td class="price_head_td"><p>' . ($is_greece ? 'ΤΕΛΙΚΗ ΑΞΙΑ' : 'TOTAL AMOUNT') . '</p></td>';

    $issuer_product_head .= '</tr>';

    $allowed_html = array(
        'tr'   => array('class' => array(),),
        'td'   => array('class' => array(),),
        'p'    => array('class' => array()),
        'span' => array('class' => array())
    );
    echo wp_kses($issuer_product_head, $allowed_html);
}

function primer_display_issuer_product($i, $last_page): void {
    $receipt_id           = get_the_ID();
    $general_settings     = get_option('primer_generals');
    $order_id             = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $is_greece            = wc_get_order($order_id)->get_billing_country() == "GR" ? true : false;
    $tax_classes          = WC_Tax::get_tax_classes();
    $create_json_instance = new Create_json();
    $Vat_categories       = $create_json_instance->getVatCategories();

    in_array('', $tax_classes, true) || array_unshift($tax_classes, '');

    $per_page_product = 5;
    if (isset($general_settings['products_per_page_receipt']) && $general_settings['products_per_page_receipt'] != null && $general_settings['products_per_page_receipt'] != '') {
        $per_page_product = $general_settings['products_per_page_receipt'] + 1;
    }

    $product_count      = $i * $per_page_product;
    $product_count_html = 0;
    $product_per_page   = $product_count - $per_page_product;
    $is_credit_receipt  = get_post_meta($receipt_id, 'credit_receipt', true);
    $log_for_order      = get_post_meta($receipt_id, $is_credit_receipt ? 'credit_log_id_for_order' : 'log_id_for_order', true);
    $json_send_to_api   = get_post_meta($log_for_order, 'json_send_to_api', true);
    $json_send_to_api   = json_decode($json_send_to_api, true);
    $json_send_to_api   = decodeUnicodeSequences($json_send_to_api);

    $issuer_product = '';
    foreach ($json_send_to_api['invoice'][0]['invoiceDetails'] as $product) {
        $product_count_html++;
        if (($product_count_html <= $product_count) && ($product_count_html > $product_per_page)) {
            if (!isset($product['quantity'])) {
                $product['quantity'] = 1;
            }
            $measurement_unit = $is_greece ? 'ΥΠΗΡΕΣΙΑ' : 'SERVICES';
            if ($product['incomeClassification'][0]['classificationCategory'] == 'category1_1' || $product['incomeClassification'][0]['classificationCategory'] == 'category1_2') {
                $measurement_unit = $is_greece ? 'ΤΕΜΑΧΙΑ' : 'PIECES';
            }

            $issuer_product .= '<tr class="products table_borders">';

            $issuer_product .= '<td class="table_borders"><span class="item_code">' . $product['code'] . '</span></td>';
            $issuer_product .= '<td class="table_borders"><span class="item_name">' . $product['name'] . '</span></td>';
            $issuer_product .= '<td class="table_borders"><span class="item_quantity">' . $product['quantity'] . '</span></td>';
            $issuer_product .= '<td class="table_borders"><span class="item_mu">' . $measurement_unit . '</span></td>';
            $issuer_product .= '<td class="table_borders"><span class="item_unit_price">' . number_format((float) ($product['netValue'] / $product['quantity']), 2, '.', '') . '</span></td>';
            $issuer_product .= '<td class="table_borders"><span class="item_vat">' . $Vat_categories[$product['vatCategory']] . '</span></td>';
            $issuer_product .= '<td class="table_borders"><span class="item_price_novat">' . $product['netValue'] . '</span></td>';
            $issuer_product .= '<td class="table_borders"><span class="item_price_novat">' . $product['vatAmount'] . '</span></td>';
            $issuer_product .= '<td class="table_borders"><span class="item_price_novat">' . number_format((float) ($product['netValue'] + $product['vatAmount']), 2, '.', '') . '</span></td>';

            $issuer_product .= '</tr>';
        }
    }

    $allowed_html = array(
        'tr'   => array('class' => array(),),
        'td'   => array('class' => array(),),
        'p'    => array('class' => array()),
        'span' => array('class' => array())
    );

    echo wp_kses($issuer_product, $allowed_html);
}

function primer_display_issuer_tax_total(): void {
    $receipt_id        = get_the_ID();
    $order_id          = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $is_credit_receipt = get_post_meta($receipt_id, 'credit_receipt', true);
    $log_for_order     = get_post_meta($receipt_id, $is_credit_receipt ? 'credit_log_id_for_order' : 'log_id_for_order', true);
    $json_send_to_api  = get_post_meta($log_for_order, 'json_send_to_api', true);
    $json_send_to_api  = json_decode($json_send_to_api, true);
    $totals            = $vat_values = $net_values = $vat_category = [];

    foreach ($json_send_to_api['invoice'][0]['invoiceDetails'] as $product) {
        $net_values[]   = $product['netValue'];
        $vat_values[]   = $product['vatAmount'];
        $vat_category[] = $product['vatCategory'];
    }

    $vat_categories = $net_categories = $total_categories = array_fill(1, 7, 0);
    $tax_rate       = [1 => '24%', 2 => '13%', 3 => '6%', 4 => '17%', 5 => '9%', 6 => '4%', 7 => '0%'];

    for ($i = 0; $i < count($vat_category); $i++) {
        $category = $vat_category[$i];
        if (isset($vat_categories[$category])) {
            $vat_categories[$category]   += floatval($vat_values[$i]);
            $net_categories[$category]   += floatval($net_values[$i]);
            $total_categories[$category]  = $vat_categories[$category] + $net_categories[$category];
            $totals[$category]            = $vat_categories[$category] + $net_categories[$category];
        }
    }

    $is_greece = wc_get_order($order_id)->get_billing_country() == 'GR' ? true : false;

    $issuer_product_tax_total  = '<tr>';
    $issuer_product_tax_total .= $is_greece ? '<td class="bold table_tax" style="width: 50%"><span>Συντελεστής ΦΠΑ</span></td>' : '<td class="bold table_tax" style="width: 50%"><span>VAT Rate</span></td>';
    foreach ($tax_rate as $category => $rate) {
        if (isset($totals[$category]) && $totals[$category] > 0) {
            $issuer_product_tax_total .= '<td class="table_tax"><span class="table_tax">' . $rate . '</span></td>';
        }
    }
    $issuer_product_tax_total .= '</tr>';

    $issuer_product_tax_total .= '<tr>';
    $issuer_product_tax_total .= $is_greece ? '<td class="skin bold table_tax" style="width: 50%"><span>Καθαρή Αξία</span></td>' : '<td class="skin bold table_tax" style="width: 50%"><span>Net Value</span></td>';
    foreach ($net_categories as $category => $net_value) {
        if (isset($totals[$category]) && $totals[$category] > 0) {
            $issuer_product_tax_total .= '<td class="table_tax"><span class="table_tax">' . number_format($net_value, 2, '.', '') . '</span></td>';
        }
    }
    $issuer_product_tax_total .= '</tr>';

    $issuer_product_tax_total .= '<tr>';
    $issuer_product_tax_total .= $is_greece ? '<td class="skin bold table_tax" style="width: 50%"><span>Αξία ΦΠΑ</span></td>' : '<td class="skin bold table_tax" style="width: 50%"><span>VAT Value</span></td>';
    foreach ($vat_categories as $category => $vat_value) {
        if (isset($totals[$category]) && $totals[$category] > 0) {
            $issuer_product_tax_total .= '<td class="table_tax"><span class="table_tax">' . number_format($vat_value, 2, '.', '') . '</span></td>';
        }
    }
    $issuer_product_tax_total .= '</tr>';

    $issuer_product_tax_total .= '<tr>';
    $issuer_product_tax_total .= $is_greece ? '<td class="skin bold table_tax" style="width: 50%"><span>Τελική Αξία</span></td>' : '<td class="skin bold table_tax" style="width: 50%"><span>Total Value</span></td>';
    foreach ($total_categories as $category => $total) {
        if (isset($totals[$category]) && $totals[$category] > 0) {
            $issuer_product_tax_total .= '<td class="table_tax"><span class="table_tax">' . number_format($total, 2, '.', '') . '</span></td>';
        }
    }
    $issuer_product_tax_total .= '</tr>';

    $allowed_html = array(
        'tr'   => array(),
        'td'   => array('class' => array(), 'style' => array(),),
        'span' => array('class' => array(),)
    );

    echo wp_kses($issuer_product_tax_total, $allowed_html);
}

function primer_display_issuer_comments():void {
    $receipt_id     = get_the_ID();
    $mydata_options = get_option('primer_mydata');
    $order_id       = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $order          = wc_get_order($order_id);
    $log_id         = $order->get_meta('log_id_for_order');
    $is_greece      = $order->get_billing_country() == 'GR' ? true : false;
    $order_comment  = $order->get_customer_note();
    $json           = get_post_meta($log_id, 'json_send_to_api', true);
    $data           = json_decode($json, true);

    if(array_key_exists('mydata_invoice_notes', $mydata_options)) {
        $primer_invoice_notes = $mydata_options['mydata_invoice_notes'] != null ? $mydata_options['mydata_invoice_notes'] : '';
    } else {
        $primer_invoice_notes = '';
    }

    $length_notes = strlen( (string)$primer_invoice_notes );
    if($length_notes > 1300) {
        $primer_invoice_notes = substr($primer_invoice_notes, 0, 1300);
    }

    $varExemptionCategory = array();
    if (isset($data['invoice'][0]['invoiceDetails']) && is_array($data['invoice'][0]['invoiceDetails'])) {
        foreach ($data['invoice'][0]['invoiceDetails'] as $invoiceDetails) {
            if (isset($invoiceDetails['vatExemptionCategory']) && $invoiceDetails['vatExemptionCategory'] != null) {
                $varExemptionCategory[] = $invoiceDetails['vatExemptionCategory'];
            }
        }
    }
    $varExemptionCategory        = array_unique($varExemptionCategory);
    $varExemptionCategory        = array_values($varExemptionCategory);
    $count                       = count($varExemptionCategory);
    $create_json_instance        = new Create_json();
    $Vat_exemption_categories    = $create_json_instance->getVatExemptionCategories();
    $Vat_exemption_categories_en = $create_json_instance->getVatExemptionCategoriesEn();

    $issuer_comment = $exception_vat = '';
    if ($count > 0) {
        $categories = $is_greece ? $Vat_exemption_categories : $Vat_exemption_categories_en;
        $exception_vat = '<div><span class="skin bold">' . ($is_greece ? 'ΑΠΑΛΛΑΓΗ ΑΠΟ ΤΟ Φ.Π.Α :' : 'EXEMPTION FROM VAT :') . '</span></div>';
        for ($i = 0; $i < $count; $i++) {
            $exception_vat .= '<div>' . $categories[$varExemptionCategory[$i]] . '</div>';
        }
    }
    $issuer_comment .= '<div class="cont_notation">' . $exception_vat . '<span class="skin bold">' . ($is_greece ? 'ΠΑΡΑΤΗΡΗΣΕΙΣ:' : 'COMMENTS:') . '</span>
                            <div class="cont_notation_inner">
                                <span class="notes">' . $order_comment . '&nbsp;' . $primer_invoice_notes . '</span>
                            </div>
                        </div>';

    $allowed_html = array(
        'div'  => array('class' => array(),),
        'span' => array('class' => array(),)
    );

	echo wp_kses($issuer_comment, $allowed_html);
}

function primer_sum_unit_title(): void {
    $receipt_id     = get_the_ID();
    $order_id       = get_post_meta($receipt_id, 'order_id_to_receipt', true);

    echo esc_html__(wc_get_order($order_id)->get_billing_country() == 'GR' ? 'ΣΥΝΟΛΟ ΤΕΜΑΧΙΩΝ: ' : 'SUM OF UNITS: ', 'primer');
}

function primer_sum_unit_count(): void {
    $receipt_id        = get_the_ID();
    $is_credit_receipt = get_post_meta($receipt_id, 'credit_receipt', true);
    $log_for_order     = get_post_meta($receipt_id, $is_credit_receipt ? 'credit_log_id_for_order' : 'log_id_for_order', true);
    $json_send_to_api  = json_decode(get_post_meta($log_for_order, 'json_send_to_api', true), true);

    $quantity = [];
    foreach ($json_send_to_api['invoice'][0]['invoiceDetails'] as $product) {
        if ($product['incomeClassification'][0]['classificationCategory'] === 'category1_3') {
            continue;
        }
        $quantity[] = $product['quantity'];
    }

    $sum_unit_count = array_sum($quantity);

    echo esc_html__($sum_unit_count, 'primer');
}

function primer_display_issuer_order_total_price($i, $last_page): void {
    $receipt_id       = get_the_ID();
    $order_id         = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $log_for_order    = get_post_meta($receipt_id, get_post_meta($receipt_id, 'credit_receipt', true) ? 'credit_log_id_for_order' : 'log_id_for_order', true);
    $order            = wc_get_order($order_id);
    $discount_total   = $order->get_discount_total();
    $zero_order_total = $order->get_total();
    $is_greece        = $order->get_billing_country() == 'GR' ? true : false;
    $currency_symbol  = get_woocommerce_currency_symbol($order->get_currency());

    $json_receipt       = json_decode(get_post_meta($log_for_order, 'json_send_to_api', true), true);
    $total_net_value    = number_format($json_receipt['invoice'][0]['invoiceSummary']['totalNetValue'], 2, '.', '');
    $total_vat_amount   = number_format($json_receipt['invoice'][0]['invoiceSummary']['totalVatAmount'], 2, '.', '');
    $total_gross_value  = number_format($json_receipt['invoice'][0]['invoiceSummary']['totalGrossValue'], 2, '.', '');

    $new_discount_total = 0;
    if ($zero_order_total > 0) {
        foreach ($order->get_items('fee') as $item_fee) {
            if ($item_fee->get_total() < 0) {
                $new_discount_total += abs($item_fee->get_total()) + abs($item_fee->get_total_tax());
            }
        }
        $total_before_discount   = $order->get_total() - $order->get_shipping_total() - $order->get_shipping_tax() + $new_discount_total;
        $new_discount_percentage = 100 - (bcdiv($total_before_discount - $new_discount_total, $total_before_discount, 1000) * 100) ?: 0;
        if ($new_discount_percentage > 0) {
            $discount_total += $new_discount_total;
        }
    }
    if ($zero_order_total == 0) {
        $total_gross_value = 0.02;
        $discount_total    = 0;
    }

    $issuer_total  = '<div class="totals">';
    $issuer_total .= '<table class="totals_table">';

    $issuer_total .= '<tr>';
    $issuer_total .= $is_greece ? '<td class="text-left"><p>ΑΞΙΑ ΠΡΟ ΕΚΠΤΩΣΗΣ</p></td>' : '<td class="text-left"><p>TOTAL NO DISCOUNT</p></td>';
    if ($i == $last_page) {
        $issuer_total .= '<td class="text-right">';
        $issuer_total .= '<p><span class="total_nodiscount">' . number_format((float) $total_gross_value + $discount_total, 2, '.', '') . ' ' . $currency_symbol . '</span> </p>';
        $issuer_total .= '</td>';
    }
    $issuer_total .= '</tr>';

    $issuer_total .= '<tr>';
    $issuer_total .= $is_greece ? '<td class="text-left"><p>ΣΥΝΟΛΟ ΕΚΠΤΩΣΗΣ</p></td>' : '<td class="text-left"><p>TOTAL DISCOUNT</p></td>';
    if ($i == $last_page) {
        $issuer_total .= '<td class="text-right">';
        $issuer_total .= '<p><span class="total_discount">' . number_format((float) $discount_total, 2, '.', '') . ' ' . $currency_symbol . '</span></p>';
        $issuer_total .= '</td>';
        $issuer_total .= '</tr>';
    }
    $issuer_total .= '<tr>';

    $issuer_total .= $is_greece ? '<td class="text-left"><p>ΣΥΝΟΛΟ ΧΩΡΙΣ ΦΠΑ</p></td>' : '<td class="text-left"><p>TOTAL WITHOUT VAT</p></td>';
    if ($i == $last_page) {
        $issuer_total .= '<td class="text-right">';
        $issuer_total .= '<p><span class="total_withoutvat">' . $total_net_value . ' ' . $currency_symbol . '</span> </p>';
        $issuer_total .= '</td>';
        $issuer_total .= '</tr>';
    }
    $issuer_total .= '<tr>';

    $issuer_total .= $is_greece ? '<td class="text-left"><p>Φ.Π.Α</p></td>' : '<td class="text-left"><p>TAXES</p></td>';
    if ($i == $last_page) {
        $issuer_total .= '<td class="text-right">';
        $issuer_total .= '<p><span class="amounttotal">' . $total_vat_amount . ' ' . $currency_symbol . '</span> </p>';
        $issuer_total .= '</td>';
        $issuer_total .= '</tr>';
    }
    $issuer_total .= '<tr>';

    $issuer_total .= $is_greece ? '<td class="text-left"><p>ΤΕΛΙΚΟ ΣΥΝΟΛΟ</p></td>' : '<td class="text-left"><p>TOTAL SUM</p></td>';
    if ($i == $last_page) {
        $issuer_total .= '<td class="text-right">';
        $issuer_total .= '<p><span class="amounttotal">' . $total_gross_value . ' ' . $currency_symbol . '</span> </p>';
        $issuer_total .= '</td>';
        $issuer_total .= '</tr>';
    }
    $issuer_total .= '<tr class="blank_row bordered"><td class="text-left">&nbsp;</td></tr>';
    $issuer_total .= '<tr>';

    $issuer_total .= $is_greece ? '<td class="text-left finalprice"><p>ΠΛΗΡΩΤΕΟ ΠΟΣΟ</p></td>' : '<td class="text-left finalprice"><p>TOTAL PAYMENT</p></td>';
    if ($i == $last_page) {
        $issuer_total .= '<td class="text-right">';
        $issuer_total .= '<p><span class="totalpayment">' . $total_gross_value . ' ' . $currency_symbol . '</span> </p>';
        $issuer_total .= '</td>';
        $issuer_total .= '</tr>';
    }

    $issuer_total .= '</table>';
    $issuer_total .= '<div class="total_funny_box"></div>';
    $issuer_total .= '</div>';

    $allowed_html = array(
        'table' => array('class' => array(),),
        'tr'    => array('class' => array(),),
        'td'    => array('class' => array(), 'style' => array(),),
        'div'   => array('class' => array(),),
        'span'  => array('class' => array(),),
        'p'     => array('class' => array())
    );

    echo wp_kses($issuer_total, $allowed_html);
}

function primer_display_issuer_logo(): void {
	$check_use_logo = primer_get_mydata_use_logo();
	if (!empty(primer_get_mydata_logo()) && $check_use_logo == 'on') {
		$mydata_options = get_option('primer_mydata');
		$photo_id_arg   = explode(':', $mydata_options['image_api_id']);

        if (count($photo_id_arg) > 1) {
			$response_value = $photo_id_arg[1];
			$response_value = str_replace('"', '', $response_value);
			$photo_id       = ltrim($response_value);
			if (isset($_GET['type_logo'])) {
				echo esc_attr($photo_id);
			}
		}
        if (!isset($_GET['type_logo'])) {
            echo primer_get_mydata_logo() ? '<img class="logo_img" src="' . wp_get_attachment_image_url(primer_get_mydata_logo(), 'full') . '">' : '';
        }
    } else {
        echo '';
    }
}

function primer_get_mydata_logo() {
    $mydata = PrimerSettings::get_mydata_details();
    return apply_filters('primer_get_mydata_logo', $mydata['logo'], $mydata);
}

function primer_get_mydata_use_logo() {
    $mydata = PrimerSettings::get_mydata_use_details();
    return apply_filters('primer_get_mydata_use_logo', $mydata['use_logo'], $mydata);
}

function primer_display_invoice_information(): void {
    $receipt_id             = get_the_ID();
    $order_id               = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $receipt_invoice_series = get_post_meta($receipt_id, '_primer_receipt_series', true);
    $receipt_invoice_number = get_post_meta($receipt_id, '_primer_receipt_number', true) ?: $receipt_id;
    $log_for_order          = get_post_meta($receipt_id, 'log_id_for_order', true);
    $log_for_order          = get_post_meta($receipt_id, 'credit_receipt', true) ? get_post_meta($receipt_id, 'credit_log_id_for_order', true) : $log_for_order;
    $json_send_to_api       = get_post_meta($log_for_order, 'json_send_to_api', true);

    $invoice_type     = json_decode(preg_match('/"invoiceType":\s*("[^"]+"|\d+(?:\.\d+)?)/', $json_send_to_api, $type) ? $type[1] : '', true);
    $issue_date       = json_decode(preg_match('/"issueDate":\s*("[^"]+"|\d+(\.\d+)?)/', $json_send_to_api, $date) ? $date[1] : '', true);
    $issue_time       = json_decode(preg_match('/"time":\s*("[^"]+"|\d+(\.\d+)?)/', $json_send_to_api, $time) ? $time[1] : '', true);
    $is_delivery_note = json_decode(preg_match('/"isDeliveryNote":\s*(true|false)/i', $json_send_to_api, $delivery) ? $delivery[1] : '', true);

    $is_greece = wc_get_order($order_id)->get_billing_country() == 'GR' ? true : false;

    $invoice_texts = [
        'GR'     => [
            '11.1' => 'Απόδειξη Λιανικής',
            '11.2' => 'Απόδειξη Παροχής Υπηρεσιών',
            '11.4' => 'Πιστωτικό Στοιχείο Λιανικής',
            '1.1'  => 'Τιμολόγιο Πώλησης',
            '1.2'  => 'Τιμολόγιο Ενδοκοινοτικών Παραδόσεων',
            '1.3'  => 'Τιμολόγιο Παραδόσεων Τρίτων Χωρών',
            '2.1'  => 'Τιμολόγιο Παροχής Υπηρεσιών',
            '2.2'  => 'Τιμολόγιο Παροχής - Ενδοκοινοτική Παροχή Υπηρεσιών',
            '2.3'  => 'Τιμολόγιο Παροχής - Παροχή Υπηρεσιών σε λήπτη Τρίτης Χώρας',
            '5.1'  => 'Πιστωτικό Τιμολόγιο Συσχετιζόμενο'
        ],
        'NOT_GR' => [
            '11.1' => 'Retail Receipt',
            '11.2' => 'Service Provision Receipt',
            '11.4' => 'Retail Credit Note',
            '1.1'  => 'Sales Invoice',
            '1.2'  => 'EU-Community Supply Invoice',
            '1.3'  => 'Third Country Supply Invoice',
            '2.1'  => 'Service Provision Invoice',
            '2.2'  => 'Service Provision - EU-Community Service Supply Invoice',
            '2.3'  => 'Service Provision - Service Supply to Third Country Recipient Invoice',
            '5.1'  => 'Related Credit Invoice'
        ]
    ];

    $invoice_type_text = ($invoice_texts[$is_greece ? 'GR' : 'NOT_GR'][$invoice_type] ?? '') . ($is_delivery_note ? ($is_greece ? ' - ΔΕΛΤΙΟ ΑΠΟΣΤΟΛΗΣ' : ' - DELIVERY NOTE') : '');

    $invoice_information_container  = '<tr>';

    $invoice_information_container .= '<td><span class="invoice_type">'   . $invoice_type_text . '</span></td>';
    $invoice_information_container .= '<td><span class="invoice_series">' . ($receipt_invoice_series != 'EMPTY' ? $receipt_invoice_series : '') . '</span></td>';
    $invoice_information_container .= '<td><span class="invoice_number">' . $receipt_invoice_number . '</span></td>';
    $invoice_information_container .= '<td><span class="invoice_date"> '  . date('d/m/Y', strtotime($issue_date)) ?: get_the_date('d/m/Y', $receipt_id) . '</span></td>';
    $invoice_information_container .= '<td><span class="invoice_time"> '  . date('H:i', strtotime($issue_time)) ?: get_the_date('H:i', $receipt_id) . '</span></td>';

    $invoice_information_container .= '</tr>';

    $allowed_html = array(
        'tr'   => array('class' => array(),),
        'td'   => array('class' => array(), 'style' => array(),),
        'span' => array('class' => array(),),
    );

    echo wp_kses($invoice_information_container, $allowed_html);
}

function primer_display_left_customer_info(): void {
    $receipt_id       = get_the_ID();
    $invoice_type     = get_the_terms($receipt_id, 'receipt_status');
    $order_id         = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $order            = wc_get_order($order_id);
    $issuer_client_id = get_post_meta($receipt_id, 'receipt_client_id', true);

    $invoice_type_slug = $invoice_type[0]->slug;
    if ($invoice_type_slug == 'credit-invoice') {
        $find_invoice_in_slug = 'invoice';
    } elseif ($invoice_type_slug == 'credit-receipt') {
        $find_invoice_in_slug = 'receipt';
    } else {
        $invoice_type_name    = explode('_', $invoice_type_slug);
        $find_invoice_in_slug = $invoice_type_name[1];
    }

    $is_greece          = $order->get_billing_country() ? true : false;
    $customer_full_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
    $company_bil        = $order->get_meta('_billing_company');
    $profession         = $find_invoice_in_slug == 'invoice' ? $order->get_meta('_billing_store') : '';
    $vat_number         = $find_invoice_in_slug == 'invoice' ? $order->get_meta('_billing_vat') : '';
    $doy_value          = $find_invoice_in_slug == 'invoice' ? (primer_return_doy_args()[$order->get_meta('_billing_doy')] ?? $order->get_meta('_billing_doy')) : '';

    $left_customer_info  = '<table>';

    $left_customer_info .= '<tr>';
    $left_customer_info .= $is_greece ? '<p class="table_titles">ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗ</p>' : '<p class="table_titles">CUSTOMER INFORMATION</p>';
    $left_customer_info .= $is_greece ? '<td class="skin bold"><span>ΚΩΔΙΚΟΣ</span></td>' : '<td class="skin bold"><span>CUSTOMER ID</span></td>';
    $left_customer_info .= '<td class="info_value"><span>: </span><span class="counterparty_code">' . $issuer_client_id . '</span></td>';
    $left_customer_info .= '</tr>';

    $left_customer_info .= '<tr>';
    $left_customer_info .= $is_greece ? '<td class="skin bold"><span>ΑΦΜ</span></td>' : '<td class="skin bold"><span>VAT NUMBER</span></td>';
    $left_customer_info .= '<td class="info_value"><span>: </span><span class="counterparty_vat">' . $vat_number . '</span></td>';
    $left_customer_info .= '</tr>';

    $left_customer_info .= '<tr>';
    $left_customer_info .= $is_greece ? '<td class="skin bold"><span>ΕΠΩΝΥΜΙΑ</span></td>' : '<td class="skin bold"><span>NAME</span></td>';
    $left_customer_info .= '<td class="info_value"><span>: </span><span class="counterparty_name">' . ($find_invoice_in_slug == 'invoice' ? $company_bil : $customer_full_name) . '</span></td>';
    $left_customer_info .= '</tr>';

    $left_customer_info .= '<tr>';
    $left_customer_info .= $is_greece ? '<td class="skin bold"><span>ΕΠΑΓΓΕΛΜΑ</span></td>' : '<td class="skin bold"><span>ACTIVITY</span></td>';
    $left_customer_info .= '<td class="info_value"><span>: </span><span class="counterparty_activity">' . $profession . '</span></td>';
    $left_customer_info .= '</tr>';

    $left_customer_info .= '<tr>';
    if ($is_greece) {
        $left_customer_info .= '<td class="skin bold"><span>ΔΟΥ</span></td>';
        $left_customer_info .= '<td class="info_value"><span>:</span><span class="counterparty_doy">' . $doy_value . '</span></td>';
        $left_customer_info .= '</tr>';
    }

    $left_customer_info .= '</table>';

    $allowed_html = array(
        'table' => array('class' => array(),),
        'tr'    => array('class' => array(),),
        'td'    => array('class' => array(), 'style' => array(),),
        'div'   => array('class' => array(),),
        'span'  => array('class' => array(),),
        'p'     => array('class' => array())
    );

    echo wp_kses($left_customer_info, $allowed_html);
}

function primer_display_right_customer_info(): void {
    $receipt_id       = get_the_ID();
    $order_id         = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $order            = wc_get_order($order_id);
    $log_for_order    = get_post_meta($receipt_id, 'log_id_for_order', true);
    $log_for_order    = get_post_meta($receipt_id, 'credit_receipt', true) ? get_post_meta($receipt_id, 'credit_log_id_for_order', true) : $log_for_order;
    $json_send_to_api = get_post_meta($log_for_order, 'json_send_to_api', true);

    $is_delivery_note = json_decode(preg_match('/"isDeliveryNote":\s*(true|false)/i', $json_send_to_api, $delivery) ? $delivery[1] : '',true);
    $move_purpose     = json_decode(preg_match('/"movePurpose":\s*("[^"]+"|\d+(\.\d+)?)/', $json_send_to_api, $move) ? $move[1] : '', true);

    $is_greece = $order->get_billing_country() == "GR" ? true : false;

    $purpose_text = [
        'GR'     => [
            '1'  => 'Πώληση',
            '2'  => 'Πώληση για Λογαριασμό Τρίτων',
            '3'  => 'Δειγματισμός',
            '4'  => 'Έκθεση',
            '5'  => 'Επιστροφή',
            '7'  => 'Επεξεργασία-Συναρμολόγηση-Αποσυναρμολόγηση',
            '8'  => 'Ενδοδιακίνηση',
            '9'  => 'Αγορά',
            '10' => 'Εφοδιασμός πλοίων και αεροσκαφών',
            '11' => 'Δωρεάν διάθεση',
            '12' => 'Εγγύηση',
            '13' => 'Χρησιδανεισμός',
            '14' => 'Αποθήκευση σε Τρίτους',
            '20' => 'Μεταφορές - Ταχυμεταφορές'
        ],
        'NOT_GR' => [
            '1'  => 'Sale',
            '2'  => 'Sale on behalf of Third Parties',
            '3'  => 'Sampling',
            '4'  => 'Exhibition',
            '5'  => 'Return',
            '7'  => 'Assembly',
            '8'  => 'Between Entity Installations',
            '9'  => 'Purchase',
            '10' => 'Ship and Aircraft Supply',
            '11' => 'Free Disposal',
            '12' => 'Guarantee',
            '13' => 'Lending',
            '14' => 'Storage for Third Parties',
            '20' => 'Transport - Courier Services'
        ]
    ];
    $purpose_text = $purpose_text[$is_greece ? 'GR' : 'NOT_GR'][$move_purpose] ?? '';

    $customer_city        = $order->get_billing_city();
    $order_payment_method = $order->get_payment_method_title();
    $shipping_address_1   = $order->get_shipping_address_1();
    $billing_address      = $order->get_billing_address_1() . ' ' . $order->get_billing_address_2();
    $shipping_address     = !empty($shipping_address_1) ? $shipping_address_1 . ' ' . $order->get_shipping_address_2() : $billing_address;
    $order_shipping_name  = !empty($shipping_address_1) ? $order->get_formatted_shipping_full_name() : '';

    $address_labels = [
        'info'         => $is_greece ? 'ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ' : 'OTHER INFORMATION',
        'city'         => $is_greece ? 'ΠΟΛΗ' : 'CITY',
        'address'      => $is_greece ? 'ΔΙΕΥΘΥΝΣΗ' : 'ADDRESS',
        'shipping'     => $is_greece ? 'ΔΙΕΥΘΥΝΣΗ ΑΠΟΣΤΟΛΗΣ' : 'SHIPPING ADDRESS',
        'recipient'    => $is_greece ? 'ΠΑΡΑΛΗΠΤΗΣ' : 'RECIPIENT',
        'payment'      => $is_greece ? 'ΤΡΟΠΟΣ ΠΛΗΡΩΜΗΣ' : 'PAYMENT METHOD',
        'move_purpose' => $is_greece ? 'ΣΚΟΠΟΣ ΔΙΑΚΙΝΗΣΗΣ' : 'PURPOSE OF MOVEMENT'
    ];

    $right_customer_info  = '<table>';
    $right_customer_info .= '<tr>';

    $right_customer_info .= '<p class="table_titles">' . $address_labels['info'] . '</p>';
    $right_customer_info .= sprintf('<tr><td class="skin bold"><span>%s</span></td><td class="info_value"><span>: </span><span class="counterparty_city">%s</span></td></tr>', $address_labels['city'], $customer_city);
    $right_customer_info .= sprintf('<tr><td class="skin bold"><span>%s</span></td><td class="info_value"><span>: </span><span class="counterparty_address">%s</span></td></tr>', $address_labels['address'], $billing_address);

    if (!empty($shipping_address_1)) {
        $right_customer_info .= sprintf('<tr><td class="skin bold"><span>%s</span></td><td class="info_value"><span>: </span><span class="send_place">%s</span></td></tr>', $address_labels['shipping'], $shipping_address);
        $right_customer_info .= sprintf('<tr><td class="skin bold"><span>%s</span></td><td class="info_value"><span>: </span><span class="send_place">%s</span></td></tr>', $address_labels['recipient'], $order_shipping_name);
    }

    $right_customer_info .= sprintf('<tr><td class="skin bold"><span>%s</span></td><td class="info_value"><span>: </span><span class="send_place">%s</span></td></tr>', $address_labels['payment'], $order_payment_method);
    $right_customer_info .= $is_delivery_note
        ? sprintf('<tr><td class="skin bold"><span>%s</span></td><td class="info_value"><span>: </span><span class="send_place">%s</span></td>', $address_labels['move_purpose'], $purpose_text)
        : '';

    $right_customer_info .= '</tr>';
    $right_customer_info .= '</table>';

    $allowed_html = array(
        'table' => array('class' => array(),),
        'tr'    => array('class' => array(),),
        'td'    => array('class' => array(), 'style' => array(),),
        'div'   => array('class' => array(),),
        'span'  => array('class' => array(),),
        'p'     => array('class' => array()),
    );

    echo wp_kses($right_customer_info, $allowed_html);
}

function primer_invoice_uid(): void {
    $receipt_id  = get_the_ID();
    $invoice_uid = get_post_meta($receipt_id, 'response_invoice_uid', true);

    echo esc_html($invoice_uid);
}

function primer_invoice_mark(): void {
	$receipt_id   = get_the_ID();
	$invoice_mark = get_post_meta($receipt_id, 'response_invoice_mark', true);

	echo esc_html($invoice_mark);
}

function primer_invoice_authcode(): void {
	$receipt_id       = get_the_ID();
	$invoice_authcode = get_post_meta($receipt_id, 'response_invoice_authcode', true);

	echo esc_html($invoice_authcode);
}

function primer_generate_qr($receipt_id, $generated_uid): void {
    $upload_dir = wp_upload_dir()['basedir'];

    if (!file_exists($upload_dir . '/primer_qrs')) {
        mkdir($upload_dir . '/primer_qrs');
    }

    $is_qr_code_exist = get_post_meta($receipt_id, '_is_qr_code_exist', true);
    $primer = new Primer();
    if (empty($is_qr_code_exist) && !empty($generated_uid)) {
        $receipt_link  = "https://primer.gr/mydatasearch/" . $generated_uid;
        $image_name    = time() . '_' . $receipt_id . '.png';
        $image_name    = sanitize_text_field($image_name);
        $qr_size       = 4;
        $qr_frame_size = 2;
        $primer->QRcode->png($receipt_link, PRIMER_QR_IMAGE_DIR . $image_name, QR_ECLEVEL_M, $qr_size, $qr_frame_size);
        update_post_meta($receipt_id, '_is_qr_code_exist', 1);
        update_post_meta($receipt_id, '_product_qr_code', $image_name);
    }
}

function primer_get_generated_qr(): void {
    $receipt_id      = get_the_ID();
    $receipt_qr_code = get_post_meta($receipt_id, '_product_qr_code', true);

    $qr_code = '';
    if (!empty($receipt_qr_code) && file_exists(PRIMER_QR_IMAGE_DIR . $receipt_qr_code)) {
        $path     = PRIMER_QR_IMAGE_DIR . $receipt_qr_code;
        $type     = pathinfo($path, PATHINFO_EXTENSION);
        $data     = file_get_contents($path);
        $base64   = 'data:image/' . $type . ';base64,' . base64_encode($data);
        $qr_code .= '<img class="product-qr-code-img" src="' . $base64 . '" alt="QR Code" /img>';
    }

    echo wp_kses_normalize_entities($qr_code, [
        'img' => [
            'src'    => true,
            'sizes'  => true,
            'class'  => true,
            'id'     => true,
            'width'  => true,
            'height' => true,
            'alt'    => true,
            'align'  => true,
        ],
    ]);
}

function times_html() {
    $receipt_id       = get_the_ID();
    $order_id         = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $order            = wc_get_order($order_id);
    $general_settings = get_option('primer_generals');

    $per_page_product = 5;
    if (isset($general_settings['products_per_page_receipt']) && $general_settings['products_per_page_receipt'] != null && $general_settings['products_per_page_receipt'] != '') {
        $per_page_product = $general_settings['products_per_page_receipt'] + 1;
    }

    $count_product = 0;
    foreach ($order->get_items() as $item_id => $item) {
        $count_product++;
    }

    if ($order->get_shipping_total()) {
        $count_product++;
    }

    if ($order->get_total() != 0) {
        foreach ($order->get_items('fee') as $item_id => $item_fee) {
            $fee_total = $item_fee->get_total();
            if ($fee_total > 0) {
                $count_product++;
            }
        }
    }

    $html_time = 1;
    if ($count_product > $per_page_product) {
        $html_time = (int) ($count_product / $per_page_product) + 1;
        if (($count_product % $per_page_product) == 0) {
            $html_time = $html_time - 1;
        }
    }

    return $html_time;
}

function get_customer_country() {
    $receipt_id = get_the_ID();
    $order_id   = get_post_meta($receipt_id, 'order_id_to_receipt', true);
    $order      = wc_get_order($order_id);

    return $order->get_billing_country();
}

function get_failure_message(): void {
    $receipt_id = get_the_ID();
    $message    = get_post_meta($receipt_id, 'connection_fail_message', true);

    echo esc_html($message);
}

function decodeUnicodeSequences($data) {
    if (is_string($data)) {
        return preg_replace_callback('/u([0-9A-Fa-f]{4})/', function($matches) {
            $code = hexdec($matches[1]);
            return mb_convert_encoding("&#$code;", 'UTF-8', 'HTML-ENTITIES');
        }, $data);
    } elseif (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = decodeUnicodeSequences($value);
        }
    } elseif (is_object($data)) {
        foreach ($data as $key => $value) {
            $data->$key = decodeUnicodeSequences($value);
        }
    }

    return $data;
}