<?php

defined('ABSPATH') || exit;

require_once(ABSPATH . 'wp-load.php');
require_once PRIMER_PATH . 'includes/vendor/dompdf/autoload.inc.php';

use PrimerDompdf\Dompdf;

class Create_json {

    public function create_invoice(&$user_id, &$order_id, &$total_vat_number, $mydata_options, &$primer_license_data, &$total, &$series, &$serie, &$number,
                                   &$currency, &$currency_symbol, &$user_data, &$insert_taxonomy, &$classificationCategory, &$classificationCategory_en,
                                   &$response_data, &$receipt_log_value, &$receipt_log_value_array, &$receipt_log_id, &$invoice_term, $gr_time,$invoice_time,
                                   &$order_total_price, &$order_invoice_type, &$order_vatNumber, &$user_order_email, &$order_country, &$user_full_name, &$primer_smtp,
                                   &$log_ids, $callingFunction, &$invoiceType, &$classificationType, $is_credit = false, $receipt_id = '') {

        $primer_smtp             = PrimerSMTP::get_instance();
        $licenses                = get_option('primer_licenses');
        $invoice_data            = array("invoice" => array());
        $order                   = wc_get_order($order_id);
        $id_of_order             = $order->get_id();
        $order_country           = $order->get_billing_country() ?: 'GR';
        $order_total_price       = $order->get_total();
        $user_id                 = $order->get_user_id();
        $vies                    = $order->get_meta('is_vat_exempt');
        $order_invoice_type      = $order->get_meta('_billing_invoice_type');
        $order_id_from_receipt   = $order->get_meta('order_id_from_receipt');
        $user_order_email        = $order->get_meta('_billing_email');
        $currency                = $order->get_currency();
        $order_status            = $order->get_status();
        $total_refund            = $order->get_total_refunded() ?: 0;
        $user_full_name          = $order->get_billing_first_name() ? $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() : ($order->get_billing_company() ?: 'RETAIL CLIENT');
        $order_paid_date         = date('F j, Y', ($order->get_date_paid() ?: $order->get_date_created())->getTimestamp());
        $invoice_time            = $invoice_time ?: (new DateTime("now", new DateTimeZone("Europe/Athens")))->format('H:i');
        $currency_symbol         = get_woocommerce_currency_symbol($currency);
        $country_out_of_eu       = !check_zone_country($order_country);
        $user_data               = $user_full_name ?: 'Customer';
        $insert_taxonomy         = 'receipt_status';
        $invoice_term            = $outside_vat = $inside_tax_rate = $order_vat_exemption_category = '';
        $total_net_value         = $total_vat_value = $item_count = $discount_total = $discount_percentage = $outside_vat_total = 0;
        $invoice_products_types  = [];
        $exist_goods_or_products = $exist_services = false;

        $branchID = "0";
        $branchIDfromReceipt = get_post_meta($order_id_from_receipt, 'branchID', true);
        if ($callingFunction === 'convert_select_orders' || $callingFunction === 'convert_order_to_invoice') {
            if (isset($licenses['currentBranchID']) && $licenses['currentBranchID'] !== "0") {
                $branchID = $licenses['currentBranchID'];
            }
        } elseif (in_array($callingFunction, ['primer_cancel_invoice', 'convert_order_to_invoice_failed', 'primer_cancel_invoice_cron'])) {
            if ($branchIDfromReceipt !== null) {
                $branchID = $branchIDfromReceipt;
            }
        }

        $invoice_data['invoice'][0]['issuer']['vatNumber'] = "$total_vat_number";
        $invoice_data['invoice'][0]['issuer']['country']   = 'GR';
        $invoice_data['invoice'][0]['issuer']['branch']    = $branchID;

        $number         = $number ?: 0;
        $series_array   = ['EMPTY' => __('EMPTY', 'primer'), 'Α' => 'A', 'Β' => 'B', 'Γ' => 'C', 'Δ' => 'D', 'Ε' => 'E', 'Ζ' => 'Z', 'Η' => 'H', 'Θ' => 'Q', 'Ι' => 'I', 'Κ' => 'K', 'Λ' => 'L', 'Μ' => 'M', 'Ν' => 'N', 'Ξ' => 'J', 'Ο' => 'O', 'Π' => 'P', 'Ρ' => 'R', 'Σ' => 'S', 'Τ' => 'T', 'Υ' => 'Y', 'Φ' => 'F', 'Χ' => 'X', 'Ψ' => 'W', 'Ω' => 'V'];

        if ($order_total_price > 0) {
            foreach ($order->get_items('fee') as $item_fee) {
                if ($item_fee->get_total() < 0) {
                    $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() + $discount_total;
            $discount_percentage   = 100 - (bcdiv($total_before_discount - $discount_total, $total_before_discount, 1000) * 100) ?: 0;
        }

        $predefined_category = $mydata_options['predefined_category'] ?? 'Goods';
        $category_amounts    = array_fill_keys(['Goods', 'Products', 'Services'], 0);
        $categories_map      = array('Goods' => 'category1_1', 'Products' => 'category1_2', 'Services' => 'category1_3');

//        $refunds_before_issue_info = [];
//        foreach ($order->get_items() as $item_id => $items) {
//            if ($order->get_refunds() && !$is_credit) {
//                if ($order->get_refunds()) {
//                    foreach ($order->get_refunds() as $refund) {
//                        foreach ($refund->get_items() as $refund_item) {
//                            $original_item_id = $refund_item->get_meta('_refunded_item_id');
//                            if ($original_item_id) {
//                                $original_item = $order->get_item($original_item_id);
//                                if ($original_item) {
//                                    if ($refund_item->get_meta('_refunded_item_id') == $item_id) {
//
//                                        $original_net      = (float) $original_item->get_total();
//                                        $original_tax      = (float) $original_item->get_total_tax();
//                                        $original_quantity = $original_item->get_quantity();
//                                        $original_gross    = $original_net + $original_tax;
//                                        $original_price    = $original_net / $original_quantity;
//
//                                        $refunded_net_raw   = (float) $refund_item->get_total();
//                                        $refunded_tax_raw   = (float) $refund_item->get_total_tax();
//                                        $refunded_quantity  = $refund_item->get_quantity();
//                                        $refunded_gross_raw = abs($refunded_net_raw + $refunded_tax_raw);
//
//                                        $tax_multiplier = ($original_net > 0) ? ($original_gross / $original_net) : 1;
//
//                                        $refund_net = $refunded_quantity == 0 ? ($refunded_gross_raw / $tax_multiplier) : $refunded_net_raw;
//                                        $refund_tax = $refunded_quantity == 0 ? ($refunded_gross_raw - $refund_net) : $refunded_tax_raw;
//
//                                        $quantity_refunded = $refunded_quantity === 0 ? ceil($refund_net / $original_price) : $refunded_quantity;
//
//                                        $refunds_before_issue_info[$original_item_id]['quantity_refunded']  = abs($quantity_refunded);
//                                        $refunds_before_issue_info[$original_item_id]['total']              = abs($refund_net);
//                                        $refunds_before_issue_info[$original_item_id]['total_tax']          = abs($refund_tax);
//                                        $refunds_before_issue_info[$original_item_id]['refunded_total']     = $refunds_before_issue_info[$original_item_id]['total']  + $refunds_before_issue_info[$original_item_id]['total_tax'];
//
//                                    }
//                                }
//                                $refunds_before_issue_info['shipping_total']  = $refund->get_shipping_total() ?: 0;
//                                $refunds_before_issue_info['shipping_tax']    = $refund->get_shipping_tax() ?: 0;
//                                $refunds_before_issue_info['shipping_amount'] = $refunds_before_issue_info['shipping_total'] + $refunds_before_issue_info['shipping_tax'];
//
//                            }
//                        }
//                    }
//                }
//            }
//        }
//
//        $credit_refunds        = current($order->get_refunds());
//        $credit_refunds_info   = [];
//        if (!empty($credit_refunds && $is_credit)) {
//            foreach ($credit_refunds->get_items() as $item) {
//                $original_item_id = $item->get_meta('_refunded_item_id');
//                if ($original_item_id) {
//                    $original_item = $order->get_item($original_item_id);
//                    if ($original_item) {
//                        $original_net      = (float) $original_item->get_total();
//                        $original_tax      = (float) $original_item->get_total_tax();
//                        $original_quantity = $original_item->get_quantity();
//                        $original_gross    = $original_net + $original_tax;
//                        $original_price    = $original_net / $original_quantity;
//
//                        $refunded_net_raw   = (float) $item->get_total();
//                        $refunded_tax_raw   = (float) $item->get_total_tax();
//                        $refunded_quantity  = $item->get_quantity();
//                        $refunded_gross_raw = abs($refunded_net_raw + $refunded_tax_raw);
//
//                        $tax_multiplier = ($original_net > 0) ? ($original_gross / $original_net) : 1;
//
//                        $refund_net = $refunded_quantity == 0 ? ($refunded_gross_raw / $tax_multiplier) : $refunded_net_raw;
//                        $refund_tax = $refunded_quantity == 0 ? ($refunded_gross_raw - $refund_net) : $refunded_tax_raw;
//
//                        $quantity_refunded = $refunded_quantity === 0 ? ceil($refund_net / $original_price) : $refunded_quantity;
//
//                        $credit_refunds_info[$original_item_id]['quantity_refunded']  = $quantity_refunded;
//                        $credit_refunds_info[$original_item_id]['total']              = $refund_net;
//                        $credit_refunds_info[$original_item_id]['total_tax']          = $refund_tax;
//                        $credit_refunds_info[$original_item_id]['refunded_total']     = $credit_refunds_info[$original_item_id]['total']  + $credit_refunds_info[$original_item_id]['total_tax'];
//                    }
//                }
//            }
//            $credit_refunds_info['shipping_total']  = $credit_refunds->get_shipping_total() ?: 0;
//            $credit_refunds_info['shipping_tax']    = $credit_refunds->get_shipping_tax() ?: 0;
//            $credit_refunds_info['shipping_amount'] = $credit_refunds_info['shipping_total'] + $credit_refunds_info['shipping_tax'];
//        }

        $refunds_before_issue_info = [];
        $credit_refunds_info       = [];

        if ($order->get_refunds()) {
            foreach ($order->get_items() as $item_id => $items) {
                foreach ($order->get_refunds() as $refund) {
                    foreach ($refund->get_items() as $refund_item) {
                        if ($refund_item->get_meta('_refunded_item_id') == $item_id) {
                            $original_item = $order->get_item($item_id);
                            if ($original_item) {
                                $refund_data                         = $this->process_refund_item($refund_item, $original_item);
                                $refunds_before_issue_info[$item_id] = array_map('abs', $refund_data);
                            }
                        }
                    }
                    $refunds_before_issue_info['shipping_total']  = $refund->get_shipping_total() ?: 0;
                    $refunds_before_issue_info['shipping_tax']    = $refund->get_shipping_tax() ?: 0;
                    $refunds_before_issue_info['shipping_amount'] = $refunds_before_issue_info['shipping_total'] + $refunds_before_issue_info['shipping_tax'];
                }
            }
        }

        $credit_refunds = current($order->get_refunds());
        if (!empty($credit_refunds && $is_credit)) {
            foreach ($credit_refunds->get_items() as $item) {
                $original_item_id = $item->get_meta('_refunded_item_id');
                if ($original_item_id) {
                    $original_item = $order->get_item($original_item_id);
                    if ($original_item) {
                        $credit_refunds_info[$original_item_id] = $this->process_refund_item($item, $original_item);
                    }
                }
            }
            $credit_refunds_info['shipping_total']  = $credit_refunds->get_shipping_total() ?: 0;
            $credit_refunds_info['shipping_tax']    = $credit_refunds->get_shipping_tax() ?: 0;
            $credit_refunds_info['shipping_amount'] = $credit_refunds_info['shipping_total'] + $credit_refunds_info['shipping_tax'];
        }

        $credit_refunds = null;

//        foreach ($order->get_items() as $item_id => $items) {
//            $product = $items->get_product();
//
//            if ($product) {
//                $product_id    = $product->get_id();
//                $product_types = get_post_meta($product_id, 'product_types', true) ?: $predefined_category;
//
//                $invoice_products_types[$product_id] = $product_types;
//
//                if (in_array($product_types, [
//                    'Goods',
//                    'Products'
//                ])) {
//                    $exist_goods_or_products = true;
//                } elseif ($product_types === 'Services') {
//                    $exist_services = true;
//                }
//
//                if ($order_total_price > 0) {
//                    $item_total = $items->get_total();
//                    if (isset($category_amounts[$product_types])) {
//                        $category_amounts[$product_types] += number_format((float) $item_total, 2, '.', '');
//                        if ($discount_percentage > 0) {
//                            $category_amounts[$product_types] -= wc_round_discount($item_total * $discount_percentage / 100, 2);
//                        }
//                    }
//                    if ($total_refund > 0 && !$is_credit) {
//                        $category_amounts[$product_types] += $refunds_before_issue_info[$item_id]['total'] ?: 0;
//                    }
//                }
//
//                if ($is_credit && !empty($credit_refunds) && isset($credit_refunds_info[$item_id])) {
//                    $refund_amount                    = isset($credit_refunds_info[$item_id]['total']) ? abs($credit_refunds_info[$item_id]['total']) : 0;
//                    $category_amounts[$product_types] += (float) $refund_amount;
//                }
//            } else {
//                $product_types = $predefined_category;
//                $item_total    = $items->get_total();
//                if (isset($category_amounts[$product_types])) {
//                    $category_amounts[$product_types] += number_format((float) $item_total, 2, '.', '');
//                    if ($discount_percentage > 0) {
//                        $category_amounts[$product_types] -= wc_round_discount($item_total * $discount_percentage / 100, 2);
//                    }
//                }
//            }
//        }

        foreach ($category_amounts as $key => $value) {
            $category_amounts[$key] = 0;
        }

        foreach ($order->get_items() as $item_id => $item) {
            $product = $item->get_product();

            if ($product) {
                $product_id    = $product->get_id();
                $product_types = get_post_meta($product_id, 'product_types', true) ?: $predefined_category;
            } else {
                $product_id    = $item->get_id();
                $product_types = $predefined_category;
            }

            $invoice_products_types[$product_id] = $product_types;

            if ($is_credit && !empty($credit_refunds)) {
                if (isset($credit_refunds_info[$item_id])) {
                    $refund_amount = (float) abs($credit_refunds_info[$item_id]['total'] ?? 0);
                    if (isset($category_amounts[$product_types])) {
                        $category_amounts[$product_types] += $refund_amount;
                    }
                }
            } else {
                if ($order_total_price > 0) {
                    $item_total = (float) $item->get_total();
                    if (isset($category_amounts[$product_types])) {
                        $category_amounts[$product_types] += number_format(round($item_total, 2, PHP_ROUND_HALF_UP), 2, '.', '');
                        if ($discount_percentage > 0) {
                            $category_amounts[$product_types] -= wc_round_discount($item_total * $discount_percentage / 100, 2);
                        }
                        if ($total_refund > 0 && isset($refunds_before_issue_info[$item_id])) {
                            $category_amounts[$product_types] -= (float) ($refunds_before_issue_info[$item_id]['total'] ?? 0);
                        }
                    }
                }
            }

            if (in_array($product_types, ['Goods', 'Products'])) {
                $exist_goods_or_products = true;
            } elseif ($product_types === 'Services') {
                $exist_services = true;
            }
        }

        $services = $exist_services && !$exist_goods_or_products;
        $order->update_meta_data('invoice_products_types', $invoice_products_types);
        $order->save();

        $is_production = $mydata_options['mydata_api'] == 'production_api';
        $is_invoice    = in_array($order_invoice_type, ['primer_invoice', 'invoice']);
        $is_greece     = $order_country == 'GR';

        if ($is_credit) {
            $invoice_term       = $is_invoice ? 'credit-invoice' : 'credit-receipt';
            $invoiceType        = $is_invoice ? '5.1' : '11.4';
            $classificationType = $is_invoice ? ($is_greece ? 'E3_561_001' : (check_zone_country($order_country) ? 'E3_561_005' : 'E3_561_006')) : 'E3_561_003';
            if (empty($number)) {
                $apiSuffix = $is_production ? '' : '_test_api';
                $prefix    = $is_invoice ? 'credit_invoice' : 'credit_receipt';
                $seriesKey = $prefix . $apiSuffix . '_series';
                $series    = $mydata_options[$seriesKey];
                $serie     = array_search($series, $series_array);
                $numberKey = $prefix . '_' . $series . $apiSuffix;
                $number    = $mydata_options[$numberKey];
            }
        } else {
            $invoice_term       = $is_invoice ? ($is_greece ? 'greek_invoice' : 'english_invoice') : 'greek_receipt';
            $invoiceType        = $is_invoice ? ($is_greece ? ($services ? '2.1' : '1.1') : (check_zone_country($order_country) ? ($services ? '2.2' : '1.2') : ($services ? '2.3' : '1.3'))) : ($services ? '11.2' : '11.1');
            $classificationType = $is_invoice ? ($is_greece ? 'E3_561_001' : (check_zone_country($order_country) ? 'E3_561_005' : 'E3_561_006')) : 'E3_561_003';
            if (empty($number)) {
                $apiSuffix = $is_production ? '' : '_test_api';
                $prefix    = $is_invoice ? ($is_greece ? 'invoice_numbering_gi' : (check_zone_country($order_country) ? 'invoice_numbering_within' : 'invoice_numbering_outside')) : 'invoice_numbering_gr';
                $seriesKey = $prefix . $apiSuffix . '_series';
                $series    = $mydata_options[$seriesKey];
                $serie     = array_search($series, $series_array);
                $numberKey = $prefix . '_' . $series . $apiSuffix;
                $number    = $mydata_options[$numberKey];
            }
        }

        if (!empty($mydata_options['primer_rounding_calculation']) && array_key_exists('primer_rounding_calculation', $mydata_options) && $mydata_options['primer_rounding_calculation'] == 'on') {
            $order->update_status('pending', '<%Your message%>', TRUE);
            $order->calculate_totals();
            $order->update_status($order_status, '<%Your message%>', TRUE);
        }
        if ($callingFunction == "convert_order_to_invoice") {
            update_post_meta($receipt_log_id, 'receipt_log_automation_order_id', $id_of_order);
            if (!empty($receipt_log_id)) {
                $order->update_meta_data('log_id_for_order', $receipt_log_id);
                update_post_meta($receipt_log_id, 'receipt_log_automation_order_date', $order_paid_date);
            }
        } else {
            update_post_meta($receipt_log_id, 'receipt_log_order_id', $id_of_order);
            if (!empty($receipt_log_id)) {
                $order->update_meta_data('log_id_for_order', $receipt_log_id);
                update_post_meta($receipt_log_id, 'receipt_log_order_date', $order_paid_date);
            }
        }
        $order->save();

        $log_ids[]      = $receipt_log_id;
        $get_coupon     = $order->get_coupon_codes();

        if ($is_credit && !empty($credit_refunds)) {
            $shipping_total = $order->get_shipping_total() + abs($credit_refunds_info['shipping_total']) ?: 0;
            $shipping_tax   = $order->get_shipping_tax() + abs($credit_refunds_info['shipping_tax']) ?: 0;
        } elseif (!empty($refunds_before_issue_info)) {
            $shipping_total = $order->get_shipping_total() + $refunds_before_issue_info['shipping_total'];
            $shipping_tax   = $order->get_shipping_tax() + $refunds_before_issue_info['shipping_tax'];
        } else {
            $shipping_total = $order->get_shipping_total();
            $shipping_tax   = $order->get_shipping_tax();
        }

        $invoice_data['invoice'][0]['invoiceHeader']['series']      = $serie == 'EMPTY' ? '0' : $serie;
        $invoice_data['invoice'][0]['invoiceHeader']['aa']          = $number;
        $invoice_data['invoice'][0]['invoiceHeader']['invoiceType'] = $invoiceType;
        $invoice_data['invoice'][0]['invoiceHeader']['currency']    = $currency;
        $invoice_data['invoice'][0]['invoiceHeader']['issueDate']   = $gr_time;

        $activated_dispatch = isset($mydata_options['activation_dispatch_note']) && !$exist_services && $mydata_options['activation_dispatch_note'] === 'on';
        if ($activated_dispatch) {
            $move_purpose = $mydata_options['purpose_dispatch_note'];
            if (!metadata_exists('post', $id_of_order, 'isDeliveryNote') || !$order->meta_exists('isDeliveryNote')) {
                $order->update_meta_data('isDeliveryNote', true);
                $order->update_meta_data('movePurpose', $move_purpose);
                $order->save();
            }
        } elseif ($is_credit) {
            $activated_dispatch = $order->get_meta('isDeliveryNote');
            $move_purpose       = $order->get_meta('movePurpose');
        }
        if ($activated_dispatch) {
            $invoice_data['invoice'][0]['invoiceHeader']['movePurpose'] = $move_purpose;
            if (isset($licenses['currentBranchID']) && $licenses['currentBranchID'] != "0") {
                $selected_branch = null;
                foreach ($licenses['subsidiaries'] as $subsidiary) {
                    if (isset($subsidiary['branchId']) && $subsidiary['branchId'] == $licenses['currentBranchID']) {
                        $selected_branch = $subsidiary;
                        break;
                    }
                }
                $company_street  = $selected_branch['street'];
                $company_number  = $selected_branch['number'];
                $company_tk      = $selected_branch['tk'];
                $company_city    = $selected_branch['city'];
            } else {
                $company_address = $licenses['companyAddress'];
                $company_street  = trim(preg_replace('/[^a-zA-ZΑ-Ωα-ωΆ-Ώά-ώ\s]/u', '', $company_address));
                $company_number  = trim(preg_replace('/\D/', '', $company_address)) != "" ? trim(preg_replace('/\D/', '', $company_address)) : "0";
                $company_tk      = $licenses['companyTk'];
                $company_city    = $licenses['companyCity'];
            }
            $billing_address = $order->get_billing_address_1();
            $billing_vat     = $order->get_meta('_billing_vat') ?: '000000000';
            $billing_name    = $order->get_billing_company() ?: $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
            $address         = $order->get_shipping_address_1() ?? $order->get_billing_address_1();
            $billing_street  = trim(preg_replace('/[^a-zA-ZΑ-Ωα-ωΆ-Ώά-ώ\s]/u', '', $billing_address));

            if ($billing_street == '') {
                $billing_street = $order->get_billing_city();
            }

            $billing_number  = trim(preg_replace('/\D/', '', $billing_address)) != "" ? trim(preg_replace('/\D/', '', $billing_address)) : "0";
            $address_street  = trim(preg_replace('/[^a-zA-ZΑ-Ωα-ωΆ-Ώά-ώ\s]/u', '', $address));
            $address_number  = trim(preg_replace('/\D/', '', $address)) != "" ? trim(preg_replace('/\D/', '', $address)) : "0";

            $invoice_data['invoice'][0]['issuer']['name']                  = $licenses['companyName'];
            $invoice_data['invoice'][0]['issuer']['address']['street']     = $company_street;
            $invoice_data['invoice'][0]['issuer']['address']['number']     = $company_number;
            $invoice_data['invoice'][0]['issuer']['address']['postalCode'] = $company_tk;
            $invoice_data['invoice'][0]['issuer']['address']['city']       = $company_city;
            $invoice_data['invoice'][0]['counterpart']['vatNumber'] = $billing_vat;
            $invoice_data['invoice'][0]['counterpart']['country']   = $order_country;
            $invoice_data['invoice'][0]['counterpart']['branch']    = 0;
            $invoice_data['invoice'][0]['counterpart']['name']      = $billing_name;
            $invoice_data['invoice'][0]['counterpart']['address']['street']     = $billing_street;
            $invoice_data['invoice'][0]['counterpart']['address']['number']     = $billing_number;
            $invoice_data['invoice'][0]['counterpart']['address']['postalCode'] = $order->get_billing_postcode();
            $invoice_data['invoice'][0]['counterpart']['address']['city']       = $order->get_billing_city();
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['loadingAddress']['street']     = $company_street;
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['loadingAddress']['number']     = $company_number;
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['loadingAddress']['postalCode'] = $company_tk;
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['loadingAddress']['city']       = $company_city;
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['deliveryAddress']['street']     = $address_street;
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['deliveryAddress']['number']     = $address_number;
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['deliveryAddress']['postalCode'] = $order->get_shipping_postcode() ?? $order->get_billing_postcode();
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['deliveryAddress']['city']       = $order->get_shipping_city() ?? $order->get_billing_city();
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['startShippingBranch']           = $licenses['currentBranchID'];
            $invoice_data['invoice'][0]['invoiceHeader']['otherDeliveryNoteHeader']['completeShippingBranch']        = 0;
            $invoice_data['invoice'][0]['invoiceHeader']['isDeliveryNote'] = true;
        }
        $error_messages = [
            'no_euro_accepted'     => __('Only euro is accepted.', 'primer'),
            'no_zero_values'       => __('AADE does not accept zero value orders please enable "Accept zero total value orders" option in general settings if you want to issue this order.', 'primer'),
            'no_license_zero_vat'  => __('The order has 0% VAT included.The edition that you currently have does not support zero vat orders.Please choose another order to convert or go to www.primer.gr/shop and choose another edition.', 'primer'),
            'no_license_payment'   => __('order could not be converted because product value sum is not equal with total value. A payment fee was used and your edition does not support payment fees. Please create a new order without payment fee or go to www.primer.gr to select another MyData plugin version.', 'primer'),
            'no_zero_vat_enabled'  => __('The order has 0% VAT included.Please go to MyData settings and configure a vat exemption category for the specific tax class that the product is attached to it.', 'primer'),
            'error_popup_template' => '<div class="primer_popup popup_error"><div><h3>%s</h3><br><br><br><br><br></div><button class="popup_ok button button-primary">OK</button></div>'
        ];
        if ($currency != 'EUR' && in_array(18, $primer_license_data['wpModules'])) {
            $req_url = 'https://api.freecurrencyapi.com/v1/latest?apikey=fca_live_utrfbGSzAGB1NZw4aDkHhUWDDBQ83JBr7tLjaCWM&base_currency=EUR&currencies=' . $currency;
            $ch      = curl_init();
            curl_setopt($ch, CURLOPT_URL, $req_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $response_json = curl_exec($ch);
            $httpcode      = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            if ($httpcode >= 200 && $httpcode < 300) {
                $response = json_decode($response_json);
                if ($response !== null && isset($response->data->$currency)) {
                    $exchange_rate_formatted                                     = number_format((float) $response->data->$currency, 5, '.', '');
                    $invoice_data['invoice'][0]['invoiceHeader']['exchangeRate'] = $exchange_rate_formatted;
                }
            }
        } elseif ($currency != 'EUR' && !(in_array(18, $primer_license_data['wpModules']))) {
            $receipt_log_value         .= $error_messages['no_euro_accepted'];
            $receipt_log_value_array[]  = $error_messages['no_euro_accepted'];
            $response_data             .= sprintf($error_messages['error_popup_template'], $error_messages['no_euro_accepted']);
            update_post_meta($receipt_log_id, ($callingFunction === "convert_order_to_invoice") ? 'receipt_log_automation_error' : 'receipt_log_error', $receipt_log_value);

            return "break";
        }
        $transmission_failure = $order->get_meta( 'transmission_failure_check');
        if ($transmission_failure == 1 || $transmission_failure == 3) {
            $order_date_failed = $order->get_meta('order_date_failed');
            $invoice_data['invoice'][0]['transmissionFailure']        = ($transmission_failure == 1) ? '1' : '2';
            $invoice_data['invoice'][0]['invoiceHeader']['issueDate'] = "$order_date_failed";
        }
        if (($order_invoice_type == 'primer_invoice' || $order_invoice_type == 'invoice') && $is_credit){
            $correlated_mark = get_post_meta($receipt_id,'response_invoice_mark',true);
            $invoice_data['invoice'][0]['invoiceHeader']['correlatedInvoices'] = [$correlated_mark];
        }

        $general_settings = get_option('primer_generals');
        $zero_total_value = $order->get_total();

        if ($general_settings['accept_zero_value_orders'] == 'on' && $zero_total_value == 0) {
            $invoice_data['invoice'][0]['invoiceDetails'][0]['name']        = 'ΠΡΟΙΟΝ';
            $invoice_data['invoice'][0]['invoiceDetails'][0]['code']        = '1';
            $invoice_data['invoice'][0]['invoiceDetails'][0]['lineNumber']  = 1;
            $invoice_data['invoice'][0]['invoiceDetails'][0]['netValue']    = 0.01;
            $invoice_data['invoice'][0]['invoiceDetails'][0]['vatCategory'] = 1;
            $invoice_data['invoice'][0]['invoiceDetails'][0]['vatAmount']   = 0.01;
            if ($activated_dispatch) {
                $invoice_data['invoice'][0]['invoiceDetails'][0]['itemDescr']       = 'ΠΡΟΙΟΝ';
                $invoice_data['invoice'][0]['invoiceDetails'][0]['quantity']        = 1;
                $invoice_data['invoice'][0]['invoiceDetails'][0]['measurementUnit'] = 1;
            }
            $invoice_data['invoice'][0]['paymentMethods']['paymentMethodDetails'][0]['type']   = 1;
            $invoice_data['invoice'][0]['paymentMethods']['paymentMethodDetails'][0]['amount'] = 0.02;
            $invoice_data['invoice'][0]['invoiceSummary']['totalNetValue']         = 0.01;
            $invoice_data['invoice'][0]['invoiceSummary']['totalVatAmount']        = 0.01;
            $invoice_data['invoice'][0]['invoiceSummary']['totalWithheldAmount']   = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalFeesAmount']       = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalStampDutyAmount']  = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalDeductionsAmount'] = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalOtherTaxesAmount'] = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalGrossValue']       = 0.02;
            $invoice_data['templateId'] = '1';
            update_post_meta($receipt_log_id, 'receipt_log_automation_error', $receipt_log_value);
            update_post_meta($receipt_log_id, 'json_send_to_api', wp_slash(json_encode($invoice_data)));

            return ($invoice_data);
        } elseif ($general_settings['accept_zero_value_orders'] != 'on' && $zero_total_value == 0) {
            $receipt_log_value         .= $error_messages['no_zero_values'];
            $receipt_log_value_array[]  = $error_messages['no_zero_values'];
            $response_data             .= sprintf($error_messages['error_popup_template'], $error_messages['no_zero_values']);
            update_post_meta($receipt_log_id, ($callingFunction === "convert_order_to_invoice") ? 'receipt_log_automation_error' : 'receipt_log_error', $receipt_log_value);

            return "break";
        } else {
            foreach ($order->get_items() as $item_id => $item_data) {
                $quantity     = $item_data->get_quantity();
                $product_name = $item_data->get_name();
                if ($general_settings['display_attr_var'] == 'on') {
                    if ($item_data->get_all_formatted_meta_data()) {
                        $attribute_strings = array();
                        foreach ($item_data->get_all_formatted_meta_data() as $meta_key => $formatted_meta) {
                            $attribute_string    = $formatted_meta->key . ": " . $formatted_meta->value;
                            $attribute_strings[] = $attribute_string;
                        }
                        $attributes   = implode(', ', $attribute_strings);
                        $product_name = $item_data->get_name() . " - " . $attributes;
                    }
                }

                $product = $item_data->get_product();
                if ($product) {
                    $product_id             = $product->get_id();
                    $classificationCategory = $categories_map[$invoice_products_types[$product_id]];
                    $product_code           = $product->get_sku() ?: $product->get_id();
                } else {
                    $classificationCategory = $categories_map[$predefined_category];
                    $product_code           = $item_data->get_id();
                }

                if ($is_credit && !empty($credit_refunds)) {
                    $has_refund = false;
                    if (isset($credit_refunds_info[$item_id])) {
                        $subtotal_order_payment = (float) abs($credit_refunds_info[$item_id]['total'] ?? 0);
                        $subtotal_item_tax      = (float) abs($credit_refunds_info[$item_id]['total_tax'] ?? 0);
                        $quantity               = absint($credit_refunds_info[$item_id]['quantity_refunded'] ?? 0);
                        $has_refund             = true;
                    }
                    if (!$has_refund) {
                        continue;
                    }
                    if ($quantity <= 0) {
                        $quantity = 1;
                    }
                } else {
                    $subtotal_order_payment = $item_data->get_total();
                    if (!empty($get_coupon) || $order->get_total_discount() > 0 || $discount_percentage > 0) {
                        if ($discount_percentage > 0) {
                            $subtotal_order_payment -= wc_round_discount($subtotal_order_payment * ($discount_percentage / 100), 2);
                        }
                    }
                    $subtotal_item_tax = $item_data->get_total_tax();
                    if (!empty($get_coupon) || $order->get_total_discount() > 0 || $discount_percentage > 0) {
                        if ($discount_percentage > 0) {
                            $subtotal_item_tax -= wc_round_tax_total($subtotal_item_tax * ($discount_percentage / 100), 2);
                        }
                    }

                    if ($total_refund > 0) {
                        $subtotal_order_payment -= $refunds_before_issue_info[$item_id]['total'];
                        $subtotal_item_tax      -= $refunds_before_issue_info[$item_id]['total_tax'];
                        $quantity               -= $refunds_before_issue_info[$item_id]['quantity_refunded'];
                    }
                    if ($subtotal_order_payment == 0) {
                        continue;
                    }

                }

                $product_tax_class = $item_data->get_tax_class();
                $taxes             = $item_data->get_taxes();
                foreach ($taxes['total'] as $tax_rate_id => $tax_amount) {
                    if ($tax_amount > 0) {
                        $tax_rate        = WC_Tax::_get_tax_rate($tax_rate_id);
                        $inside_tax_rate = strval($tax_rate['tax_rate']);
                        break;
                    }
                }
                if (empty($inside_tax_rate) || $subtotal_item_tax == 0) {
                    $vatCategory = 7;
                    $outside_vat = '';
                } else {
                    switch ($inside_tax_rate) {
                        case "24":
                            $vatCategory = 1;
                            break;
                        case "17":
                            $vatCategory = 4;
                            break;
                        case "13":
                            $vatCategory = 2;
                            break;
                        case "9":
                            $vatCategory = 5;
                            break;
                        case "6":
                            $vatCategory = 3;
                            break;
                        case "4":
                            $vatCategory = 6;
                            break;
                        case "0":
                            $vatCategory = 7;
                            break;
                        default:
                            $vatCategory = 7;
                            $outside_vat = 'yes';
                    }
                }

                $tax_classes       = WC_Tax::get_tax_classes();
                $classes_names     = array();
                $classes_names[''] = __('Standard rate', 'woocommerce');
                if (!empty($tax_classes)) {
                    foreach ($tax_classes as $class) {
                        $classes_names[sanitize_title($class)] = esc_html($class);
                    }
                }
                $order_vat_exemption_category = '27';
                $order_vat_exemption_name     = $classes_names[$product_tax_class];
                $order_vat_exemption_name     = str_replace(' ', '_', $order_vat_exemption_name);

                if (($inside_tax_rate == "0" || empty($inside_tax_rate) || $subtotal_item_tax == 0) && !empty($mydata_options['' . $order_vat_exemption_name . '']) && in_array(16, $primer_license_data['wpModules'])) {
                    $order_vat_exemption_category = $mydata_options['' . $order_vat_exemption_name . ''];
                }

                if ($inside_tax_rate == "0" && !(in_array(16, $primer_license_data['wpModules'])) && ($is_greece || ($order_invoice_type == 'receipt' && $is_greece))) {
                    $receipt_log_value         .= $error_messages['no_license_zero_vat'];
                    $receipt_log_value_array[]  = $error_messages['no_license_zero_vat'];
                    $response_data             .= sprintf($error_messages['error_popup_template'], $error_messages['no_license_zero_vat']);
                    update_post_meta($receipt_log_id, ($callingFunction === "convert_order_to_invoice") ? 'receipt_log_automation_error' : 'receipt_log_error', $receipt_log_value);

                    return "break";
                }
                if ($inside_tax_rate == "0" && ($is_greece || ($order_invoice_type == 'receipt' && $is_greece)) && (empty($mydata_options['' . $order_vat_exemption_name . '']) || $mydata_options['' . $order_vat_exemption_name . ''] == 0) && in_array(16, $primer_license_data['wpModules'])) {
                    $receipt_log_value         .= $error_messages['no_zero_vat_enabled'];
                    $receipt_log_value_array[]  = $error_messages['no_zero_vat_enabled'];
                    $response_data             .= sprintf($error_messages['error_popup_template'], $error_messages['no_zero_vat_enabled']);
                    update_post_meta($receipt_log_id, ($callingFunction === "convert_order_to_invoice") ? 'receipt_log_automation_error' : 'receipt_log_error', $receipt_log_value);

                    return "break";
                }
                if (!$is_greece && ($order_vat_exemption_category == '' || empty($order_vat_exemption_category) || $order_vat_exemption_category == 0)) {
                    $order_vat_exemption_category = 27;
                }

                $subtotal_order_payment = number_format(round($subtotal_order_payment, 2, PHP_ROUND_HALF_UP), 2, '.', '');
                $subtotal_item_tax      = number_format(round($subtotal_item_tax, 2, PHP_ROUND_HALF_UP), 2, '.', '');

                if ($outside_vat != 'yes' && $vies != 'yes') {
                    $total_net_value  += $subtotal_order_payment;
                    $total_vat_value  += $subtotal_item_tax;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['name']        = $product_name;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['code']        = $product_code;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['lineNumber']  = $item_count + 1;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['netValue']    = $subtotal_order_payment;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatCategory'] = (int) $vatCategory;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatAmount']   = $subtotal_item_tax;
                    if ($activated_dispatch) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['itemDescr'] = $product_name;
                    }
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationCategory'] = $classificationCategory;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationType']     = $classificationType;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['amount']                 = $subtotal_order_payment;
                    if (!$services) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = (int) $quantity;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                    }
                    if ($subtotal_item_tax == "0.00") {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = $order_vat_exemption_category;
                    }
                } else {
                    $total_net_value += $subtotal_order_payment;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['name']        = $product_name;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['code']        = $product_code;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['lineNumber']  = $item_count + 1;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['netValue']    = $subtotal_order_payment;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatCategory'] = 7;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatAmount']   = "0.00";
                    if ($activated_dispatch) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['itemDescr'] = $product_name;
                    }
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationCategory'] = $classificationCategory;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationType']     = $classificationType;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['amount'] = $subtotal_order_payment;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory']              = 27;
                    if (!$services) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = (int) $quantity;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                    }
                    if ($subtotal_item_tax > 0) {
                        $total_net_value   += $subtotal_item_tax;
                        $total_vat_value   += $subtotal_item_tax;
                        $outside_vat_total += number_format((float) $subtotal_item_tax, 2, '.', '');
                        $item_count++;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['name']        = "ΦΠΑ $inside_tax_rate %";
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['code']        = 'ΦΠΑ' . ($item_count);
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['lineNumber']  = $item_count + 1;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['netValue']    = $subtotal_item_tax;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatCategory'] = 7;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatAmount']   = "0.00";
                        if ($activated_dispatch) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['itemDescr'] = "ΦΠΑ $inside_tax_rate %";
                        }
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationCategory'] = $classificationCategory_en;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['amount'] = $subtotal_item_tax;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 27;
                        if (!$services) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = 1;
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                        }
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 27;
                    } else {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 27;
                    }
                    if ($vies == 'yes') {
                        if ($classificationCategory !== 'category1_3') {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 14;
                        } else {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                        }
                    } elseif ($country_out_of_eu) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                    }
                }
                $item_count++;
            }
            if ($shipping_total > 0) {
                $shipping_tax_rate = '';
                foreach ($order->get_items('tax') as $item_id => $item_tax) {
                    $tax_data = $item_tax->get_data();
                    if (count($order->get_items('tax')) > 1) {
                        if ($tax_data['shipping_tax_total'] == 0) {
                            continue;
                        }
                    }
                    $shipping_tax_rate = $tax_data['rate_percent'];
                }
                switch ($shipping_tax_rate) {
                    case "24":
                        $vatCategory_shipping = 1;
                        break;
                    case "17":
                        $vatCategory_shipping = 4;
                        break;
                    case "13":
                        $vatCategory_shipping = 2;
                        break;
                    case "9":
                        $vatCategory_shipping = 5;
                        break;
                    case "6":
                        $vatCategory_shipping = 3;
                        break;
                    case "4":
                        $vatCategory_shipping = 6;
                        break;
                    case "0":
                        $vatCategory_shipping = 7;
                        break;
                    default:
                        $vatCategory_shipping = 7;
                        $outside_vat          = 'yes';
                }
                $shipping_total = number_format((float) $shipping_total, 2, '.', '');
                $shipping_tax   = number_format((float) $shipping_tax, 2, '.', '');
                if ($outside_vat == 'yes' || $vies == 'yes') {
                    $total_net_value      += $shipping_total;
                    $vatCategory_shipping = 7;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['name']        = "ΜΕΤΑΦΟΡΙΚΑ";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['code']        = "EA";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['lineNumber']  = $item_count + 1;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['netValue']    = $shipping_total;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatCategory'] = $vatCategory_shipping;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatAmount']   = "0.00";
                    if ($activated_dispatch) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = 1;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['itemDescr']       = 'ΜΕΤΑΦΟΡΙΚΑ';
                    }
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationCategory'] = "category1_5";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationType']     = "E3_562";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['amount'] = $shipping_total;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory']              = 27;
                    if ($vies == 'yes') {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                    } elseif ($country_out_of_eu) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                    }
                    if (!$services) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = 1;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                    }
                    if ($shipping_tax > 0) {
                        $total_net_value   += $shipping_tax;
                        $total_vat_value   += $shipping_tax;
                        $outside_vat_total += number_format((float) $shipping_tax, 2, '.', '');
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['name']        = "ΜΕΤΑΦΟΡΙΚΑ ΦΠΑ";
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['code']        = "ΦΠΑ" . ($item_count + 1);
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['lineNumber']  = $item_count + 2;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['netValue']    = $shipping_tax;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['vatCategory'] = $vatCategory_shipping;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['vatAmount']   = "00";
                        if ($activated_dispatch) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['itemDescr']       = 'ΜΕΤΑΦΟΡΙΚΑ ΦΠΑ';
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['quantity']        = 1;
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['measurementUnit'] = 1;
                        }
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['incomeClassification'][0]['classificationCategory'] = "category1_95";
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['incomeClassification'][0]['amount']                 = $shipping_tax;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['vatExemptionCategory'] = 27;
                        if (!$services) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['quantity']        = 1;
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['measurementUnit'] = 1;
                        }
                    } else {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = $order_vat_exemption_category;
                        if ($vies == 'yes') {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                        } elseif ($country_out_of_eu) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                        }
                    }
                    if ($shipping_tax == 0 && in_array(16, $primer_license_data['wpModules']) && $order_vat_exemption_category == '') {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 27;
                        if ($vies == 'yes') {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                        } elseif ($country_out_of_eu) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                        }
                    }
                } else {
                    $total_net_value += $shipping_total;
                    $total_vat_value += $shipping_tax;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['name']        = "ΜΕΤΑΦΟΡΙΚΑ";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['code']        = "EA";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['lineNumber']  = $item_count + 1;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['netValue']    = $shipping_total;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatCategory'] = $vatCategory_shipping;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatAmount']   = "$shipping_tax";
                    if ($activated_dispatch) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['itemDescr']       = "ΜΕΤΑΦΟΡΙΚΑ";
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = 1;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                    }
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationCategory'] = "category1_5";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationType']     = "E3_562";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['amount'] = $shipping_total;
                    if ($vatCategory_shipping == 7) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = $order_vat_exemption_category;
                    }
                    if ($shipping_tax == 0 && in_array(16, $primer_license_data['wpModules']) && $order_vat_exemption_category == '') {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 27;
                    }
                    if ($vies == 'yes') {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                    } elseif ($country_out_of_eu && $outside_vat == 'yes') {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                    }
                }
            }
            $fee_total = $fee_total_tax = $fee_tax_rate = $vatCategory_fee = $fee_net_value = 0;
            if (!empty($primer_license_data['wpModules'])) {
                if (in_array(14, $primer_license_data['wpModules'])) {
                    foreach ($order->get_items('fee') as $item_id => $item_fee) {
                        $fee_total     += $item_fee->get_total();
                        $fee_total_tax += $item_fee->get_total_tax();
                        $fee_net_value = $fee_total;
                        $taxes         = $item_fee->get_taxes();
                        foreach ($taxes['total'] as $tax_rate_id => $tax_amount) {
                            if ($tax_amount > 0) {
                                $tax_rate     = WC_Tax::_get_tax_rate($tax_rate_id);
                                $fee_tax_rate = $tax_rate['tax_rate'];
                                break;
                            }
                        }
                        switch ($fee_tax_rate) {
                            case "24":
                                $vatCategory_fee = 1;
                                break;
                            case "17":
                                $vatCategory_fee = 4;
                                break;
                            case "13":
                                $vatCategory_fee = 2;
                                break;
                            case "9":
                                $vatCategory_fee = 5;
                                break;
                            case "6":
                                $vatCategory_fee = 3;
                                break;
                            case "4":
                                $vatCategory_fee = 6;
                                break;
                            case "0":
                                $vatCategory_fee = 7;
                                break;
                            default:
                                $vatCategory_fee = 7;
                                $outside_vat     = 'yes';
                        }
                    }
                } else {
                    foreach ($order->get_items('fee') as $item_id => $item_fee) {
                        $check_fee = $item_fee->get_total();
                    }
                    if ($check_fee > 0) {
                        $receipt_log_value         .= $error_messages['no_license_payment'];
                        $receipt_log_value_array[]  = $error_messages['no_license_payment'];
                        $response_data             .= sprintf($error_messages['error_popup_template'], $error_messages['no_license_payment']);
                        update_post_meta($receipt_log_id, ($callingFunction === "convert_order_to_invoice") ? 'receipt_log_automation_error' : 'receipt_log_error', $receipt_log_value);

                        return "break";
                    }
                }
            }
            if ($fee_total > 0) {
                if ($shipping_total > 0) {
                    $item_count++;
                }
                $fee_total     = number_format((float)$fee_total, 2, '.', '');
                $fee_total_tax = number_format((float)$fee_total_tax, 2, '.', '');
                $fee_net_value = number_format((float)$fee_net_value, 2, '.', '');
                if ($outside_vat != 'yes' && $vies != 'yes') {
                    $total_net_value += $fee_total;
                    $total_vat_value += $fee_total_tax;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['name']        = "ΔΙΑΦΟΡΑ ΕΞΟΔΑ";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['code']        = "ΔΕ";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['lineNumber']  = $item_count + 1;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['netValue']    = $fee_total;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatCategory'] = $vatCategory_fee;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatAmount']   = "$fee_total_tax";
                    if ($activated_dispatch) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['itemDescr']       = "ΔΙΑΦΟΡΑ ΕΞΟΔΑ";
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = 1;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                    }
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationCategory'] = "category1_5";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationType']     = "E3_562";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['amount'] = $fee_total;
                    if ($vatCategory_fee == 7) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = $order_vat_exemption_category;
                    }
                    if ($fee_total_tax == 0 && in_array(16, $primer_license_data['wpModules']) && $order_vat_exemption_category == '') {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 27;
                    }
                } else {
                    $total_net_value += $fee_total;
                    $vatCategory_fee = 7;
                    if ($shipping_tax > 0 && $outside_vat == 'yes') {
                        $item_count++;
                    }
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['name']        = "ΔΙΑΦΟΡΑ ΕΞΟΔΑ";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['code']        = "ΔΕ";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['lineNumber']  = $item_count + 1;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['netValue']    = $fee_total;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatCategory'] = $vatCategory_fee;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatAmount']   = "0.00";
                    if ($activated_dispatch) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['itemDescr']       = "ΔΙΑΦΟΡΑ ΕΞΟΔΑ";
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = 1;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                    }
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationCategory'] = "category1_5";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['classificationType']     = "E3_562";
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['incomeClassification'][0]['amount'] = $fee_net_value;
                    $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory']              = 27;
                    if ($vies == 'yes') {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                    } elseif ($country_out_of_eu) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                    }
                    if (!$services) {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['quantity']        = 1;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['measurementUnit'] = 1;
                    }
                    if ($fee_total_tax > 0) {
                        $total_net_value   += $fee_total_tax;
                        $total_vat_value   += $fee_total_tax;
                        $outside_vat_total += number_format((float) $fee_total_tax, 2, '.', '');
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['name']        = "ΔΙΑΦΟΡΑ ΕΞΟΔΑ";
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['code']        = "ΦΠΑ" . ($item_count - 1);
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['lineNumber']  = $item_count + 2;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['netValue']    = $fee_total_tax;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['vatCategory'] = $vatCategory_fee;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['vatAmount']   = "00";
                        if ($activated_dispatch) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['itemDescr']       = "ΔΙΑΦΟΡΑ ΕΞΟΔΑ";
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['quantity']        = 1;
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['measurementUnit'] = 1;
                        }
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['incomeClassification'][0]['classificationCategory'] = "category1_95";
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['incomeClassification'][0]['amount'] = $fee_total_tax;
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['vatExemptionCategory'] = 27;
                        if ($vies == 'yes') {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                        } elseif ($country_out_of_eu) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                        }
                        if (!$services) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['quantity']        = 1;
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count + 1]['measurementUnit'] = 1;
                        }
                    } else {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = $order_vat_exemption_category;
                        if ($vies == 'yes') {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                        } elseif ($country_out_of_eu) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                        }
                    }
                    if ($fee_total_tax == 0 && in_array(16, $primer_license_data['wpModules']) && $order_vat_exemption_category == '') {
                        $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 27;
                        if ($vies == 'yes') {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 4;
                        } elseif ($country_out_of_eu) {
                            $invoice_data['invoice'][0]['invoiceDetails'][$item_count]['vatExemptionCategory'] = 8;
                        }
                    }
                }
            }
            $total = $total_net_value + $total_vat_value;
            $total = number_format($total, 2, '.', '');
            $invoice_data['invoice'][0]['paymentMethods']['paymentMethodDetails'][0]['type']   = 1;

//          $invoice_data['invoice'][0]['paymentMethods']['paymentMethodDetails'][0]['amount'] = number_format($order->get_total() - $total_refund, 2, '.', '');
            $payment_amount = ($is_credit & !empty($credit_refunds)) ? number_format((float) $total, 2, '.', '')
                : number_format($order->get_total() - $total_refund, 2, '.', '');

            $invoice_data['invoice'][0]['paymentMethods']['paymentMethodDetails'][0]['amount'] = $payment_amount;

            $order_total_price  = number_format((float)$order_total_price, 2, '.', '');
            $shipping_total     = number_format((float)$shipping_total, 2, '.', '');
            $total_vat_value    = number_format(wc_round_discount($total_vat_value, 2), 2, '.', '');
            $total_net_value    = number_format(wc_round_discount($total_net_value, 2), 2, '.', '');
            if ($outside_vat != 'yes' && $vies != 'yes') {
                $invoice_data['invoice'][0]['invoiceSummary']['totalNetValue']   = "$total_net_value";
                $invoice_data['invoice'][0]['invoiceSummary']['totalVatAmount']  = "$total_vat_value";
                $invoice_data['invoice'][0]['invoiceSummary']['totalGrossValue'] = "$total";
            } else {
                $invoice_data['invoice'][0]['invoiceSummary']['totalNetValue']   = "$total_net_value";
                $invoice_data['invoice'][0]['invoiceSummary']['totalVatAmount']  = "0.00";
                $invoice_data['invoice'][0]['invoiceSummary']['totalGrossValue'] = "$total_net_value";
            }
            $invoice_data['invoice'][0]['invoiceSummary']['totalWithheldAmount']   = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalFeesAmount']       = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalStampDutyAmount']  = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalDeductionsAmount'] = 0;
            $invoice_data['invoice'][0]['invoiceSummary']['totalOtherTaxesAmount'] = 0;

            $category_totals = [
                'Goods'           => ['amount' => $category_amounts['Goods'],    'category_type' => $classificationType, 'category_code' => 'category1_1'],
                'Products'        => ['amount' => $category_amounts['Products'], 'category_type' => $classificationType, 'category_code' => 'category1_2'],
                'Services'        => ['amount' => $category_amounts['Services'], 'category_type' => $classificationType, 'category_code' => 'category1_3'],
                'ShippingAndFees' => ['amount' => max(0, $fee_total) + max(0, $shipping_total), 'category_type' => 'E3_562', 'category_code' => 'category1_5'],
                'OutsideVAT'      => ['amount' => $outside_vat_total, 'category_type' => null, 'category_code' => 'category1_95']
            ];

            foreach ($category_totals as $category_data) {
                $amount = number_format((float) $category_data['amount'], 2, '.', '');
                if ($amount > 0) {
                    $classification = [
                        'classificationCategory' => $category_data['category_code'],
                        'amount' => $amount
                    ];
                    if ($category_data['category_type']) {
                        $classification['classificationType'] = $category_data['category_type'];
                    }
                    $invoice_data['invoice'][0]['invoiceSummary']['incomeClassification'][] = $classification;
                }
            }
        }

        $order_city         = $order->get_billing_city();
        $order_postcode     = $order->get_billing_postcode();
        $order_address      = $order->get_billing_address_1();
        $order_phone        = $order->get_billing_phone();
        $order_vatNumber    = $order->get_meta( '_billing_vat');
        $shipping_address   = $order->get_shipping_address_1();
        $shipping_city      = $order->get_meta('_shipping_city');
        $shipping_zip_code  = $order->get_meta( '_shipping_postcode');
        $order_comment      = $order->get_customer_note();
        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 > 1750) {
            $primer_invoice_notes = substr($primer_invoice_notes, 0, 1750);
        }
        $customer_name     = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
        $customer_activity = $order->get_meta('_billing_store');
        $customer_doy      = $order->get_meta('_billing_doy');
        if ($is_greece && ($order_invoice_type == 'primer_invoice' || $order_invoice_type == 'invoice')) {
            $order_vatNumber = trim($order_vatNumber);
            $invoice_data['invoice'][0]['counterpart']['vatNumber'] = $order_vatNumber;
            $invoice_data['invoice'][0]['counterpart']['country']   = $order_country;
        }
        if (!$is_greece && ($order_invoice_type == 'primer_invoice' || $order_invoice_type == 'invoice')) {
            $order_billing_company_name = $order->get_meta('_billing_company');
            $invoice_data['invoice'][0]['counterpart']['vatNumber']             = $order_vatNumber;
            $invoice_data['invoice'][0]['counterpart']['country']               = $order_country;
            $invoice_data['invoice'][0]['counterpart']['address']['city']       = $order_city;
            $invoice_data['invoice'][0]['counterpart']['address']['postalCode'] = $order_postcode;
            $invoice_data['invoice'][0]['counterpart']['address']['number']     = 0;
            $invoice_data['invoice'][0]['counterpart']['address']['street']     = $order_address;
            $invoice_data['invoice'][0]['counterpart']['name']                  = $order_billing_company_name;
            $customer_name = $order_billing_company_name;
        }
        $invoice_data['invoice'][0]['extra']['showOptionalFields'] = false;
        $invoice_data['invoice'][0]['extra']['time'] = $invoice_time;
        $invoice_data['templateId'] = '1';
        $invoice_data['invoice'][0]['extra']['sendEmail'] = false;
        if ($mydata_options['primer_use_api_smtp'] == 'on') {
            $invoice_data['invoice'][0]['extra']['sendEmail'] = true;
            $invoice_data['invoice'][0]['extra']['email']     = $user_order_email;
        }
        $use_upload_logo = isset($mydata_options['primer_use_logo']) ? $mydata_options['primer_use_logo'] : '';
        if (!empty($mydata_options['image_api_id']) && !empty($use_upload_logo)) {
            $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);
                $invoice_data['photoId'] = $photo_id;
            }
        }
        $invoice_data['invoice'][0]['extra']['notes']   = $order_comment . $primer_invoice_notes;
        $invoice_data['invoice'][0]['extra']['address'] = $order_address;
        $invoice_data['invoice'][0]['extra']['phone']   = $order_phone;
        $invoice_data['invoice'][0]['extra']['tk']      = $order_postcode;
        $invoice_data['invoice'][0]['extra']['city']    = $order_city;
        $invoice_data['invoice'][0]['extra']['customerCode']    = $user_id;
        $invoice_data['invoice'][0]['extra']['customerName']    = $customer_name;
        $invoice_data['invoice'][0]['extra']['locationName']    = "ΕΔΡΑ ΠΕΛΑΤΗ";
        $invoice_data['invoice'][0]['extra']['locationAddress'] = $shipping_address;
        $invoice_data['invoice'][0]['extra']['locationCity']    = $shipping_city;
        $invoice_data['invoice'][0]['extra']['locationZipCode'] = $shipping_zip_code;
        $invoice_data['invoice'][0]['extra']['isFromPlugin']    = "true";
        if ($order_invoice_type == 'primer_invoice' || $order_invoice_type == 'invoice') {
            $invoice_data['invoice'][0]['extra']['customerActivity'] = $customer_activity;
            if ($is_greece) {
                $doy_value = primer_return_doy_args()[$customer_doy];
                if (empty($doy_value)) {
                    $doy_value = $customer_doy;
                }
                $invoice_data['invoice'][0]['extra']['customerDoy'] = $doy_value;
            }
            $invoice_data['invoice'][0]['extra']['customerVat'] = $order_vatNumber;
        }
        if ($callingFunction == "convert_order_to_invoice") {
            update_post_meta($receipt_log_id, 'receipt_log_automation_error', $receipt_log_value);
            update_post_meta($receipt_log_id, 'json_send_to_api', wp_slash(json_encode($invoice_data)));
        } elseif ($callingFunction == "convert_order_to_invoice_failed") {
            update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value);
            update_post_meta($receipt_log_id, 'json_send_to_api', wp_slash(json_encode($invoice_data)));
        } else {
            update_post_meta($receipt_log_id, 'json_send_to_api', wp_slash(json_encode($invoice_data)));
            update_post_meta($receipt_log_id, 'receipt_log_order_id', $id_of_order);
            update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value);
        }

        return ($invoice_data);
    }

    public function numbering($order_invoice_type, $order_country, &$mydata_options, &$series, $is_credit = false): void {
        if($is_credit){
            if ($order_invoice_type == 'receipt' || empty($order_invoice_type)) {
                if($mydata_options['mydata_api'] == 'production_api'){
                    $mydata_options['credit_receipt_'.$series.''] = $mydata_options['credit_receipt_'.$series.''] + 1;
                }else{
                    $mydata_options['credit_receipt_'.$series.'_test_api'] = $mydata_options['credit_receipt_'.$series.'_test_api'] + 1;
                }
            }
            if ($order_invoice_type == 'primer_invoice' || $order_invoice_type == 'invoice') {
                if($mydata_options['mydata_api'] == 'production_api'){
                    $mydata_options['credit_invoice_'.$series.''] = $mydata_options['credit_invoice_'.$series.''] + 1;
                }else{
                    $mydata_options['credit_invoice_'.$series.'_test_api'] = $mydata_options['credit_invoice_'.$series.'_test_api'] + 1;
                }
            }
        } else {
             if (($order_invoice_type == 'primer_invoice' || $order_invoice_type == 'invoice') && $order_country == 'GR') {
                if ($mydata_options['mydata_api'] == 'production_api') {
                    $mydata_options['invoice_numbering_gi_' . $series . ''] = $mydata_options['invoice_numbering_gi_' . $series . ''] + 1;
                } else {
                    $mydata_options['invoice_numbering_gi_' . $series . '_test_api'] = $mydata_options['invoice_numbering_gi_' . $series . '_test_api'] + 1;
                }
            } else if (($order_invoice_type == 'primer_invoice' || $order_invoice_type == 'invoice') && $order_country !== 'GR' && check_zone_country($order_country) == true) {
                if ($mydata_options['mydata_api'] == 'production_api') {
                    $mydata_options['invoice_numbering_within_' . $series . ''] = $mydata_options['invoice_numbering_within_' . $series . ''] + 1;
                } else {
                    $mydata_options['invoice_numbering_within_' . $series . '_test_api'] = $mydata_options['invoice_numbering_within_' . $series . '_test_api'] + 1;
                }
            } else if (($order_invoice_type == 'primer_invoice' || $order_invoice_type == 'invoice') && check_zone_country($order_country) == false) {
                if ($mydata_options['mydata_api'] == 'production_api') {
                    $mydata_options['invoice_numbering_outside_' . $series . ''] = $mydata_options['invoice_numbering_outside_' . $series . ''] + 1;
                } else {
                    $mydata_options['invoice_numbering_outside_' . $series . '_test_api'] = $mydata_options['invoice_numbering_outside_' . $series . '_test_api'] + 1;
                }
            } else {
                 if ($mydata_options['mydata_api'] == 'production_api') {
                     $mydata_options['invoice_numbering_gr_' . $series . ''] = $mydata_options['invoice_numbering_gr_' . $series . ''] + 1;
                 } else {
                     $mydata_options['invoice_numbering_gr_' . $series . '_test_api'] = $mydata_options['invoice_numbering_gr_' . $series . '_test_api'] + 1;
                 }
             }
        }
    }

    public function get_invoice_status(&$api_type, &$id_of_order, &$gr_time, &$serie, &$number, &$invoiceType, &$order_invoice_type, &$order_vatNumber, &$user_vat,
                                       &$total, $auth, &$invoice_term, &$insert_taxonomy, &$order, &$user_data, &$user_id, &$order_total_price, &$currency_symbol,
                                       &$order_country, &$mydata_options, &$series, &$total_vat_number, &$receipt_log_value, &$receipt_log_value_array, &$user_order_email,
                                       &$response_data, &$receipt_log_id, $url_slug, &$callingFunction, &$generated_uid, $post_id_failed,$connectionFailedMessage): string {
        $primer_smtp         = PrimerSMTP::get_instance();
        $primer_smtp_options = get_option('primer_emails');
        $primer_license_data = get_option('primer_licenses');
        $credit              = false;
        $url_slug            = ($api_type == 'test') ? 'https://test-mydataapi.primer.gr' : $url_slug;
        $invoice_status_url  = $url_slug . '/v2/invoices/getInvoiceFromUID';
        $time_for_call       = $order->get_meta('order_date_failed_timeout') ?? $gr_time;
        $branch = '';
        $calling_function_convert_orders   = ['convert_select_orders', 'convert_order_to_invoice'];
        $calling_function_cancel_or_failed = ['primer_cancel_invoice', 'convert_order_to_invoice_failed', 'primer_cancel_invoice_cron'];
        if (in_array($callingFunction, $calling_function_convert_orders)) {
            $branch = (isset($primer_license_data['currentBranchID']) && $primer_license_data['currentBranchID'] != "0")
                        ? $primer_license_data['currentBranchID'] : "0";
        } elseif (in_array($callingFunction, $calling_function_cancel_or_failed)) {
            $order_id_from_receipt = $order->get_meta('order_id_from_receipt');
            $branchIDfromReceipt   = get_post_meta($order_id_from_receipt, 'branchID', true);
            $branch                = $branchIDfromReceipt ?? "0";
        }
        $serie         = ($series == 'EMPTY') ? '0' : $serie;
        $generated_uid = strtoupper(sha1(iconv("UTF-8", "ISO-8859-7",strval($user_vat).'-'.strval($time_for_call).'-'.strval($branch).'-'.strval($invoiceType).'-'.strval($serie).'-'.strval($number))));
        $curl_args = array(
            'timeout'     => 15,
            'redirection' => 10,
            'method'      => 'POST',
            'httpversion' => '1.1',
            'headers'     => array(
                'Authorization' => 'Basic ' . $auth,
                'Content-Type'  => 'application/json'
            ),
            'sslverify'   => false
        );
        $curl_args['body'] = '{
				"uid": "' . $generated_uid . '"
			}';
        $last_response_request = wp_remote_post($invoice_status_url, $curl_args);
        $last_response         = wp_remote_retrieve_body($last_response_request);
        $last_info             = wp_remote_retrieve_response_code($last_response_request);
        $serie = ($series == '0') ? 'EMPTY' : $serie;
        $popup_messages = [
            'allow_url_fopen'      => __('Php option allow_url_fopen is disabled! Please communicate with your hosting provider in order to activate it.', 'primer'),
            'bcmath'               => __('Php module "bcmath" is disabled! Please communicate with your hosting provider in order to activate it.', 'primer'),
            'orders_converted'     => __('Orders converted', 'primer'),
            'something_went_wrong' => __('Something went wrong. Please try again!', 'primer'),
            'error_popup_template' => '<div class="primer_popup popup_error"><div><h3>%s</h3><br><br><br><br><br></div><button class="popup_ok button button-primary">OK</button></div>'
        ];
        $primer_cancel_calling        = in_array($callingFunction, ['primer_cancel_invoice', 'primer_cancel_invoice_cron']) ? true : false;
        $primer_cancel_calling_prefix = $primer_cancel_calling ? 'credit_' : '';
        if (!empty($last_info)) {
            if ($last_info == '200' || $last_info > 500) {
                $last_response_to_array = json_decode($last_response);
                $responseUid            = $last_response_to_array[0]->uid;
                $responseMark           = $last_response_to_array[0]->mark;
                $responseAuthCode       = $last_response_to_array[0]->authenticationCode;
                if (!ini_get('allow_url_fopen')) {
                    $response_data     .= sprintf($popup_messages['error_popup_template'], $popup_messages['allow_url_fopen']);
                    $receipt_log_value .= $popup_messages['allow_url_fopen'];
                    return "break";
                }
                if (!extension_loaded('bcmath')) {
                    $response_data     .= sprintf($popup_messages['error_popup_template'], $popup_messages['bcmath']);
                    $receipt_log_value .= $popup_messages['bcmath'];
                    return "break";
                }
                $post_titles = [
                    'primer_cancel_invoice'           => "Credit Receipt for order #{$id_of_order}",
                    'convert_order_to_invoice_failed' => "Receipt for order #{$id_of_order}-failed",
                    'primer_cancel_invoice_cron'      => "Credit Receipt for order #{$id_of_order}-failed"
                ];
                $post_id = wp_insert_post([
                    'post_type'      => 'primer_receipt',
                    'post_title'     => $post_titles[$callingFunction] ?? "Receipt for order #{$id_of_order}",
                    'comment_status' => 'closed',
                    'ping_status'    => 'closed',
                    'post_status'    => 'publish'
                ]);
                wp_set_object_terms($post_id, $invoice_term, $insert_taxonomy, false);
                if ($post_id) {
                    $issue_date   = new DateTime("now", new DateTimeZone("Europe/Athens"));
                    $invoice_date = $issue_date->format('d/m/Y');
                    $invoice_time = $issue_date->format('H:i');
                    update_post_meta($post_id, "{$primer_cancel_calling_prefix}success_mydata_date", $invoice_date);
                    update_post_meta($post_id, "{$primer_cancel_calling_prefix}success_mydata_time", $invoice_time);
                    update_post_meta($post_id, 'receipt_type', $invoice_term);
                    update_post_meta($post_id, 'send_to_api_type', $api_type);
                    update_post_meta($post_id, 'order_id_to_receipt', $id_of_order);
                    $order->update_meta_data("order_id_from_{$primer_cancel_calling_prefix}receipt", $post_id);
                    $order->save();
                    add_post_meta($post_id, 'receipt_client', $user_data);
                    add_post_meta($post_id, 'receipt_client_id', $user_id);
                    add_post_meta($post_id, 'receipt_price', $order_total_price . ' ' . $currency_symbol);
                    update_post_meta($post_id, '_primer_receipt_number', $number);
                    update_post_meta($post_id, '_primer_receipt_series', $serie);
                    if ($last_info == 512) {
                        update_post_meta($post_id, 'connection_fail_message', 'ΑΔΥΝΑΜΙΑ ΔΙΑΣΥΝΔΕΣΗΣ ΠΑΡΟΧΟΥ - ΑΑΔΕ');
                    } elseif ($last_info > 500) {
                        update_post_meta($post_id, 'connection_fail_message', 'ΑΔΥΝΑΜΙΑ ΔΙΑΣΥΝΔΕΣΗΣ ΟΝΤΟΤΗΤΑΣ - ΠΑΡΟΧΟΥ');
                    }
                    $identifier = (($serie === "EMPTY") ? "0" : $serie) . "_" . $number . "_" . $invoice_term . "_" . $branch;
                    update_post_meta($post_id, 'numbering_identifier', $identifier);
                    if ($primer_cancel_calling) {
                        update_post_meta($post_id, 'credit_receipt', 'yes');
                        $credit = true;
                    }
                    $this->numbering($order_invoice_type, $order_country, $mydata_options, $series, $credit);
                    update_option('primer_mydata', $mydata_options);
                    if (!empty($responseMark))     update_post_meta($post_id, 'response_invoice_uid', $responseMark);
                    if (!empty($responseUid))      update_post_meta($post_id, 'response_invoice_mark', $responseUid);
                    if (!empty($responseAuthCode)) update_post_meta($post_id, 'response_invoice_authcode', $responseAuthCode);
                    update_post_meta($post_id, 'branchID', $branch);
                    update_post_meta($post_id, 'connection_fail_message', '');
                    if ($callingFunction == 'convert_order_to_invoice_failed' || $callingFunction == 'primer_cancel_invoice_cron') {
                        update_post_meta($post_id, 'connection_fail_message', $connectionFailedMessage);
                    }
                }
                primer_generate_qr($post_id, $generated_uid);
                update_post_meta($post_id, 'response_invoice_mark', $responseMark);
                update_post_meta($post_id, 'response_invoice_uid', $responseUid);
                update_post_meta($post_id, 'response_invoice_authcode', $responseAuthCode);
                $primer_options = new Primer_Options();
                $post_ids_str   = (!empty($post_id)) ? $total_vat_number . $responseMark : '';
                $post_arr_id            = explode(" ", $post_id);
                $use_url_params         = '?type_logo=id';
                $generate_html_response = $primer_options->export_receipt_as_static_html_by_page_id($post_arr_id, $use_url_params);
                $upload_dir             = wp_upload_dir()['basedir'];
                if ($generate_html_response) {
                    $all_files     = $upload_dir . '/exported_html_files/tmp_files';
                    $files         = $primer_options->get_all_files_as_array($all_files);
                    $zip_file_name = $upload_dir . '/exported_html_files/' . $post_ids_str . '_html.zip';
                    ob_start();
                    echo esc_url($primer_options->create_zip($files, $zip_file_name, $all_files . '/'));
                    $create_zip = ob_get_clean();
                    if ($create_zip == 'created') {
                        $primer_options->rmdir_recursive($upload_dir . '/exported_html_files/tmp_files');
                    }
                }
                if (!empty($post_id)) {
                    $primer_license_data = get_option('primer_licenses');
                    $post_url            = get_the_permalink($post_id);
                    $post_url            = $post_url . '?receipt=view&username=' . $primer_license_data['username'];
                    $arrContextOptions   = array(
                        "ssl"  => array(
                            "verify_peer"      => false,
                            "verify_peer_name" => false,
                        ),
                        "http" => array(
                            "header" => [
                                "User-Agent: Mozilla/5.0",
                                "Content-type: text/html; charset=utf-8\r\n"
                            ],
                        ),
                    );
                    $context              = stream_context_create($arrContextOptions);
                    $homepage             = file_get_contents($post_url, false, $context);
                    $modified_homepage    = $homepage;
                    $log_id               = $order->get_meta('log_id_for_order');
                    $json                 = get_post_meta($log_id, 'json_send_to_api', true);
                    $data                 = json_decode($json, true);
                    $varExemptionCategory = array_unique(array_filter(array_column($data['invoice'][0]['invoiceDetails'] ?? [], 'vatExemptionCategory')));
                    $is_greece            = $order->get_meta('_billing_country') === 'GR';
                    $is_receipt           = $order->get_meta('_billing_invoice_type') === 'receipt';
                    $is_delivery_note     = $data['invoice'][0]['invoiceHeader']['isDeliveryNote'] ?? false;
                    $vat_exemption_categories = $is_greece ? $this->getVatExemptionCategories() : $this->getVatExemptionCategoriesEn();
                    if (!empty($varExemptionCategory)) {
                        $exception_vat     = '<div><span class="skin bold">' . ($is_greece ? 'ΑΠΑΛΛΑΓΗ ΑΠΟ ΤΟ Φ.Π.Α :' : 'EXEMPTION FROM VAT :') . '</span></div>' . implode('', array_map(fn($cat) => '<div>' . ($vat_exemption_categories[$cat] ?? '') . '</div>', $varExemptionCategory));
                        $search            = $is_greece ? '<div class="cont_notation"><span class="skin bold">ΠΑΡΑΤΗΡΗΣΕΙΣ:</span>' : '<div class="cont_notation"><span class="skin bold">COMMENTS:</span>';
                        $modified_homepage = str_replace($search, '<div class="cont_notation">' . $exception_vat . $search, $modified_homepage);
                    }

                    $delivery_note_styles = $is_receipt ? ($is_delivery_note ? '140px' : '120px') : ($is_delivery_note ? '180px' : '160px');
                    $modified_homepage    = preg_replace('/(<div class="information (left|right)")([^>]*)>/', '$1 style="height: ' . $delivery_note_styles . '"$3>', $modified_homepage);

                    $replacements = $is_greece ? ['ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗXX' => 'ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗXX', 'ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ' => 'ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ']
                        : ['CUSTOMER INFORMATION' => 'CUSTOMER INFORMATION', 'OTHER INFORMATION' => 'OTHER INFORMATION'];

                    foreach ($replacements as $search => $replace) {
                        $modified_homepage = str_replace("<tr><p class=\"table_titles\">{$search}</p>", '<tr><td colspan="2" style="text-align: center;"><p class="table_titles"' . (str_contains($search, 'CUSTOMER') ? ' style="white-space: nowrap; text-align: center;"' : '') . ">{$replace}</p></td></tr><tr>", $modified_homepage);
                    }

                    $dompdf  = new Dompdf();
                    $options = $dompdf->getOptions();
                    $options->setIsHtml5ParserEnabled(true);
                    $options->setIsRemoteEnabled(true);
                    $dompdf->setOptions($options);
                    $dompdf->loadHtml($modified_homepage);
                    $dompdf->render();
                    $upload_dir = wp_upload_dir()['basedir'];
                    if (!file_exists($upload_dir . '/email-invoices')) {
                        mkdir($upload_dir . '/email-invoices');
                    }
                    $post_name = get_the_title($post_id);
                    $post_name = str_replace(' ', '_', $post_name);
                    $post_name = str_replace('#', '', $post_name);
                    $post_name = strtolower($post_name);
                    $post_name = sanitize_text_field($post_name);
                    $output    = $dompdf->output();
                    $upload_dir_file = $upload_dir . '/email-invoices/' . $post_name . '.pdf';
                    if (!empty(realpath($upload_dir . '/email-invoices/'))) {
                        file_put_contents($upload_dir_file, $output);
                    }
                    $attachments = $upload_dir . '/email-invoices/' . $post_name . '.pdf';
                    $post_issued = 'issued';
                    update_post_meta($post_id, 'receipt_status', $post_issued);
                    $order->update_meta_data('receipt_status', $post_issued);
                    $order->save();
                    add_post_meta($post_id, 'receipt_client', $user_data);
                    add_post_meta($post_id, 'receipt_client_id', $user_id);
                    add_post_meta($post_id, 'receipt_price', $order_total_price . ' ' . $currency_symbol);
                    $headers = 'From: ' . $primer_smtp_options['from_email_field'] ? $primer_smtp_options['from_email_field'] : 'Primer ' . get_bloginfo('admin_email');
                    if (!empty($primer_smtp_options['email_subject'])) {
                        $primer_smtp_subject = $primer_smtp_options['email_subject'];
                    } else {
                        $primer_smtp_subject = __('Test email subject', 'primer');
                    }
                    if (!empty($primer_smtp_options['email_from_name'])) {
                        $from_name_email = $primer_smtp_options['email_from_name'];
                    } else {
                        $from_name_email = '';
                    }
                    if (!empty($primer_smtp_options['quote_available_content'])) {
                        $primer_smtp_message = $primer_smtp_options['quote_available_content'];
                        $client_first_name   = $order->get_meta('_billing_first_name');
                        $client_last_name    = $order->get_meta('_billing_last_name');
                        $client_email        = $order->get_meta('_billing_email');
                        $streetAddress       = $order->get_meta('_billing_address_1');
                        $townCity            = $order->get_meta('_billing_city');
                        $phone               = $order->get_meta('_billing_phone');
                        $primer_smtp_message = str_replace('{ClientFirstName}', $client_first_name, $primer_smtp_message);
                        $primer_smtp_message = str_replace('{ClientLastName}', $client_last_name, $primer_smtp_message);
                        $primer_smtp_message = str_replace('{ClientEmail}', $client_email, $primer_smtp_message);
                        $primer_smtp_message = str_replace('{StreetAddress}', $streetAddress, $primer_smtp_message);
                        $primer_smtp_message = str_replace('{TownCity}', $townCity, $primer_smtp_message);
                        $primer_smtp_message = str_replace('{Phone}', $phone, $primer_smtp_message);
                    } else {
                        $primer_smtp_message = __('Test email message', 'primer');
                    }
                    $primer_automatically_send_file = $primer_smtp_options['automatically_send_on_conversation'];
                    $primer_smtp_type               = $primer_smtp_options['smtp_type'];
                    if (empty($primer_automatically_send_file)) {
                        $primer_automatically_send_file = 'yes';
                    }
                    $order->get_meta("{$primer_cancel_calling_prefix}log_id_for_order");
                    if (!empty($order_log_id)) {
                        update_post_meta($post_id, "{$primer_cancel_calling_prefix}log_id_for_order", $order_log_id);
                        $invoice_date = get_the_date('F j, Y', $post_id);
                        update_post_meta($order_log_id, 'receipt_log_invoice_id', $post_id);
                        update_post_meta($order_log_id, 'receipt_log_invoice_date', $invoice_date);
                        update_post_meta($order_log_id, 'receipt_log_client', $user_data);
                        $get_issue_status = get_post_meta($post_id, 'receipt_status', true);
                        $get_issue_status = $get_issue_status ?: 'issued';
                        update_post_meta($order_log_id, 'receipt_log_status', $get_issue_status);
                        update_post_meta($order_log_id, 'receipt_log_error', $receipt_log_value);
                        if ($receipt_log_value != null) {
                            update_post_meta($order_log_id, 'receipt_log_total_status', 'only_errors');
                        }
                    }
                    $email_logs = '';
                    if (!empty($primer_automatically_send_file) && $primer_automatically_send_file === 'yes' && $user_order_email != '' && $user_order_email != null) {
                        $mailResult = false;
                        if ($primer_smtp_type == 'wordpress_default') {
                            $headers        = array('Content-Type: text/html; charset=UTF-8');
                            $mailResultSMTP = wp_mail($user_order_email, $primer_smtp_subject, $primer_smtp_message, $headers, $attachments);
                        } else {
                            $mailResultSMTP = $primer_smtp->primer_mail_sender($user_order_email, $from_name_email, $primer_smtp_subject, $primer_smtp_message, $attachments);
                        }
                        if (!$primer_smtp->credentials_configured()) {
                            $email_logs .= __('Configure your SMTP credentials', 'primer') . "\n";
                        }
                        if (!empty($mailResultSMTP['error']) && !$primer_smtp->credentials_configured()) {
                            $response_data .= sprintf($popup_messages['error_popup_template'], $GLOBALS['phpmailer']->ErrorInfo);
                            update_post_meta($order_log_id, 'receipt_log_email', 'not_sent');
                            $email_logs .= $GLOBALS['phpmailer']->ErrorInfo . "\n";
                            update_post_meta($order_log_id, 'receipt_log_email_error', $email_logs);
                            update_post_meta($order_log_id, 'receipt_log_total_status', 'only_errors');
                        } else {
                            update_post_meta($order_log_id, 'receipt_log_email', 'sent');
                            update_post_meta($order_log_id, 'receipt_log_total_status', 'only_issued');
                        }
                        update_post_meta($post_id, 'exist_error_log', 'exist_log');
                    } else {
                        if (!$primer_smtp->credentials_configured()) {
                            $email_logs .= __('Configure your SMTP credentials', 'primer') . "\n";
                        }
                        $email_logs .= __('Send email automatically on order conversion disabled', 'primer') . "\n";
                        update_post_meta($order_log_id, 'receipt_log_email', 'not_sent');
                        update_post_meta($order_log_id, 'receipt_log_email_error', $email_logs);
                        update_post_meta($order_log_id, 'receipt_log_total_status', 'only_issued');
                    }
                }
                $order->update_meta_data('transmission_failure_check', 2);
                if ($primer_cancel_calling) {
                    $order->update_meta_data('cancelled', 'yes');
                    update_post_meta($post_id, 'cancelled', 'yes');
                }
                $order->save();
                $response_data .= sprintf($popup_messages['error_popup_template'], $popup_messages['orders_converted']);

                return "break";
            } else {
                $receipt_log_value_array[] = $popup_messages['something_went_wrong'];
                $response_data             .= sprintf($popup_messages['error_popup_template'], $popup_messages['something_went_wrong']);
                update_post_meta($receipt_log_id, $callingFunction === "convert_order_to_invoice" ? 'receipt_log_automation_error' : 'receipt_log_error', $popup_messages['something_went_wrong']);

                return "break";
            }
        } else {
            $receipt_log_value_array[] = $popup_messages['something_went_wrong'];
            $response_data             .= sprintf($popup_messages['error_popup_template'], $popup_messages['something_went_wrong']);
            update_post_meta($receipt_log_id, $callingFunction === "convert_order_to_invoice" ? 'receipt_log_automation_error' : 'receipt_log_error', (string) $popup_messages['something_went_wrong']);

            return "break";
        }
    }

    public function getVatExemptionCategories(): array {
        $Vat_exemption_categories = array();
        $Vat_exemption_categories[0]  = 'Please select a tax exemption category';
        $Vat_exemption_categories[1]  = 'Χωρίς ΦΠΑ - άρθρο 2 και 3 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[2]  = 'Χωρίς ΦΠΑ - άρθρο 5 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[3]  = 'Χωρίς ΦΠΑ - άρθρο 17 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[4]  = 'Χωρίς ΦΠΑ - άρθρο 18 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[5]  = 'Χωρίς ΦΠΑ - άρθρο 21 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[6]  = 'Χωρίς ΦΠΑ - άρθρο 24 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[7]  = 'Χωρίς ΦΠΑ - άρθρο 27 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[8]  = 'Χωρίς ΦΠΑ - άρθρο 29 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[9]  = 'Χωρίς ΦΠΑ - άρθρο 30 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[10] = 'Χωρίς ΦΠΑ - άρθρο 31 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[11] = 'Χωρίς ΦΠΑ - άρθρο 32 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[12] = 'Χωρίς ΦΠΑ - άρθρο 32 του Κώδικα ΦΠΑ - Πλοία Ανοικτής Θαλάσσης του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[13] = 'Χωρίς ΦΠΑ - άρθρο 32 .1.γ. του Κώδικα ΦΠΑ - Πλοία Ανοικτής Θαλάσσης του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[14] = 'Χωρίς ΦΠΑ - άρθρο 33 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[15] = 'Χωρίς ΦΠΑ - άρθρο 44 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[16] = 'Χωρίς ΦΠΑ - άρθρο 45 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[17] = 'Χωρίς ΦΠΑ - άρθρο 47 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[18] = 'Χωρίς ΦΠΑ - άρθρο 48 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[19] = 'Χωρίς ΦΠΑ - άρθρο 54 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[20] = 'ΦΠΑ εμπεριεχόμενος - άρθρο 50 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[21] = 'ΦΠΑ εμπεριεχόμενος - άρθρο 51 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[22] = 'ΦΠΑ εμπεριεχόμενος - άρθρο 52 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[23] = 'ΦΠΑ εμπεριεχόμενος - άρθρο 53 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[24] = 'Χωρίς ΦΠΑ - άρθρο 8 του Κώδικα ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[25] = 'Χωρίς ΦΠΑ - ΠΟΛ.1029/1995 (ν. 5144/2024)';
        $Vat_exemption_categories[26] = 'Χωρίς ΦΠΑ - ΠΟΛ.1167/2015 (ν. 5144/2024)';
        $Vat_exemption_categories[27] = 'Λοιπές Εξαιρέσεις ΦΠΑ (ν. 5144/2024)';
        $Vat_exemption_categories[28] = 'Χωρίς ΦΠΑ – άρθρο 29 περ. β’ παρ.1 του Κώδικα ΦΠΑ, (Tax Free) (ν. 5144/2024)';
        $Vat_exemption_categories[29] = 'Χωρίς ΦΠΑ – άρθρο 56 του Κώδικα ΦΠΑ (OSS_μη ενωσιακό καθεστώς) (ν. 5144/2024)';
        $Vat_exemption_categories[30] = 'Χωρίς ΦΠΑ – άρθρο 57 του Κώδικα ΦΠΑ (OSS_ενωσιακό καθεστώς) (ν. 5144/2024)';
        $Vat_exemption_categories[31] = 'Χωρίς ΦΠΑ – άρθρο 58 του Κώδικα ΦΠΑ (IOSS) (ν. 5144/2024)';

        return $Vat_exemption_categories;
    }

    public function getVatCategories(): array {
        $Vat_categories = array();
        $Vat_categories[1] = '24%';
        $Vat_categories[2] = '13%';
        $Vat_categories[3] = '6%';
        $Vat_categories[4] = '17%';
        $Vat_categories[5] = '9%';
        $Vat_categories[6] = '4%';
        $Vat_categories[7] = '0%';

        return $Vat_categories;
    }

    public function getVatExemptionCategoriesEn(): array {
        $Vat_exemption_categories = array();
        $Vat_exemption_categories[0]  = 'Please select a tax exemption category';
        $Vat_exemption_categories[1]  = 'VAT exempt - Articles 2 and 3 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[2]  = 'VAT exempt - Article 5 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[3]  = 'VAT exempt - Article 17 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[4]  = 'VAT exempt - Article 18 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[5]  = 'VAT exempt - Article 21 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[6]  = 'VAT exempt - Article 24 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[7]  = 'VAT exempt - Article 27 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[8]  = 'VAT exempt - Article 29 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[9]  = 'VAT exempt - Article 30 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[10] = 'VAT exempt - Article 31 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[11] = 'VAT exempt - Article 32 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[12] = 'VAT exempt - Article 32 of the VAT Code - Ocean-going vessels (Law 5144/2024)';
        $Vat_exemption_categories[13] = 'VAT exempt - Article 32.1.c of the VAT Code - Ocean-going vessels (Law 5144/2024)';
        $Vat_exemption_categories[14] = 'VAT exempt - Article 33 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[15] = 'VAT exempt - Article 44 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[16] = 'VAT exempt - Article 45 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[17] = 'VAT exempt - Article 47 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[18] = 'VAT exempt - Article 48 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[19] = 'VAT exempt - Article 54 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[20] = 'VAT included - Article 50 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[21] = 'VAT included - Article 51 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[22] = 'VAT included - Article 52 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[23] = 'VAT included - Article 53 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[24] = 'VAT exempt - Article 8 of the VAT Code (Law 5144/2024)';
        $Vat_exemption_categories[25] = 'VAT exempt - POL.1029/1995 (Law 5144/2024)';
        $Vat_exemption_categories[26] = 'VAT exempt - POL.1167/2015 (Law 5144/2024)';
        $Vat_exemption_categories[27] = 'Other VAT Exemptions (Law 5144/2024)';
        $Vat_exemption_categories[28] = 'VAT exempt – Article 29(b)(1) of the VAT Code, (Tax Free) (Law 5144/2024)';
        $Vat_exemption_categories[29] = 'VAT exempt – Article 56 of the VAT Code (OSS non-Union scheme) (Law 5144/2024)';
        $Vat_exemption_categories[30] = 'VAT exempt – Article 57 of the VAT Code (OSS Union scheme) (Law 5144/2024)';
        $Vat_exemption_categories[31] = 'VAT exempt – Article 58 of the VAT Code (IOSS) (Law 5144/2024)';

        return $Vat_exemption_categories;
    }

    function process_refund_item($refund_item, $original_item, $original_price = null) {
        $original_net      = (float) $original_item->get_total();
        $original_tax      = (float) $original_item->get_total_tax();
        $original_quantity = $original_item->get_quantity();
        $original_gross    = $original_net + $original_tax;
        $original_price    = $original_price ?: $original_net / $original_quantity;

        $refunded_net_raw   = (float) $refund_item->get_total();
        $refunded_tax_raw   = (float) $refund_item->get_total_tax();
        $refunded_quantity  = $refund_item->get_quantity();
        $refunded_gross_raw = abs($refunded_net_raw + $refunded_tax_raw);

        $tax_multiplier = ($original_net > 0) ? ($original_gross / $original_net) : 1;

        $refund_net = $refunded_quantity == 0 ? ($refunded_gross_raw / $tax_multiplier) : $refunded_net_raw;
        $refund_tax = $refunded_quantity == 0 ? ($refunded_gross_raw - $refund_net) : $refunded_tax_raw;

        $quantity_refunded = $refunded_quantity === 0 ? ceil($refund_net / $original_price) : $refunded_quantity;

        return [
            'quantity_refunded' => $quantity_refunded,
            'total'             => $refund_net,
            'total_tax'         => $refund_tax,
            'refunded_total'    => $refund_net + $refund_tax
        ];
    }



}



?>
