<?php

defined('ABSPATH') || exit;

require_once PRIMER_PATH . 'includes/vendor/autoload.php';
require_once PRIMER_PATH . 'admin/includes/my_data_json.php';

use PrimerDompdf\Dompdf;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Cell\DataType;

class PrimerCron {

    public function __construct() {
        add_action('primer_cron_save_settings', array($this, 'primer_save_automation_data'));
        add_action('primer_cron_process', array($this, 'convert_order_to_invoice'), 1);
        add_action('primer_cron_process_failed', array($this, 'convert_order_to_invoice_failed'), 1);
        add_action('primer_cron_process_credit_failed', array($this, 'primer_cancel_invoice_cron'), 1);
        add_action('wp_ajax_primer_fire_cron', array($this, 'ajax_fire_cron'));
        add_action('primer_cron_save_settings', array($this, 'primer_save_export_data'));
        add_action('primer_cron_export_process', array($this, 'export_invoice_to_report'));
        add_action('wp_ajax_export_invoice_to_report', array($this, 'export_invoice_to_report'));
        add_action('wp_ajax_primer_get_woocommerce_tax_rates', array($this, 'primer_get_woocommerce_tax_rates'));
        add_action('primer_cron_primer_license_remaining', array(&$this, 'primer_cron_license_remaining'), 1);
    }

    public function primer_save_automation_data() {
        $next_timestamp        = wp_next_scheduled('primer_cron_process');
        $automation_options    = get_option('primer_automation');
        $activation_automation = $automation_options['activation_automation'];
        $automation_duration   = $automation_options['automation_duration'];
        $current_schedule      = wp_get_schedule('primer_cron_process');

        if ($current_schedule !== $automation_duration) {
            wp_clear_scheduled_hook('primer_cron_process');
            wp_schedule_event(time(), $automation_duration, 'primer_cron_process');
        } elseif (!$next_timestamp) {
            wp_schedule_event(time(), $automation_duration, 'primer_cron_process');
        }

        if (!empty($automation_options) && !empty($activation_automation)) {
            wp_clear_scheduled_hook('primer_cron_process');
            wp_schedule_event(time(), $automation_duration, 'primer_cron_process');
        } else {
            wp_clear_scheduled_hook('primer_cron_process');
        }

    }

    public function primer_save_export_data() {
        $next_timestamp               = wp_next_scheduled('primer_cron_process');
        $export_options               = get_option('primer_export');
        $activation_automation_export = $export_options['export_enable_schedule'];
        $automation_export_duration   = $export_options['export_time'];
        $current_schedule             = wp_get_schedule('primer_cron_export_process');

        if ($current_schedule !== $automation_export_duration) {
            wp_clear_scheduled_hook('primer_cron_export_process');
            wp_schedule_event(time(), $automation_export_duration, 'primer_cron_export_process');
        } elseif (!$next_timestamp) {
            wp_schedule_event(time(), $automation_export_duration, 'primer_cron_export_process');
        }

        if (!empty($export_options) && !empty($activation_automation_export)) {
            wp_clear_scheduled_hook('primer_cron_export_process');
            wp_schedule_event(time(), $automation_export_duration, 'primer_cron_export_process');
        } else {
            wp_clear_scheduled_hook('primer_cron_process');
        }

    }

    public function primer_cron_license_remaining() {
        $licenses      = get_option('primer_licenses');
        $username      = $licenses['username'];
        $password      = $licenses['password'];
        $licenseKey    = $licenses['serialNumber'];
        $api_url       = 'https://erp-mydataapi.primer.gr/v2/invoice/productActivation';
        $auth          = base64_encode("$username" . ':' . "$password");
        $serial_number = array("serialNumber" => "$licenseKey");

        $request_args = array(
            'timeout'     => 0,
            'method'      => 'POST',
            'httpversion' => '1.1',
            'headers'     => array(
                'Authorization' => 'Basic ' . $auth,
                'Content-Type'  => 'application/json'
            ),
            'sslverify'   => false,
            'body'        => json_encode($serial_number),
        );

        $response          = wp_remote_post($api_url, $request_args);
        $response_code     = wp_remote_retrieve_response_code($response);
        $response_answer   = wp_remote_retrieve_body($response);
        $response_to_array = json_decode($response_answer);

        if (!empty($response_to_array)) {
            if (!is_string($response_to_array) && is_object($response_to_array)) {
                $licenses['monthRemainingInvoices'] = $response_to_array->monthRemainingInvoices;
                $licenses['endDate'] = $response_to_array->endDate;
                $licenses['deliveryNote'] = $response_to_array->deliveryNote;
                if (!$response_to_array->deliveryNote) {
                    $mydata_options = get_option('primer_mydata');
                    $mydata_options['activation_dispatch_note'] = 'off';
                    update_option('primer_mydata', $mydata_options);
                }
                if ($response_to_array->monthRemainingInvoices > 0) {
                    $mydata_options = get_option('primer_mydata');
                    $mydata_options['check_0_remaining'] = 2;
                    update_option('primer_mydata', $mydata_options);
                }
            } else {
                $licenses['monthRemainingInvoices'] = '';
            }
        }

        update_option('primer_licenses', $licenses);
        wp_die();
    }

    public function convert_order_to_invoice() {
        global $wpdb, $woocommerce;

        $log_ids = array();

        if (!defined('MINUTE_IN_SECONDS')) {
            define('MINUTE_IN_SECONDS', 60);
        }
        if (get_transient('convert_order_to_invoice_lock')) {
            return;
        }
        set_transient('convert_order_to_invoice_lock', true, MINUTE_IN_SECONDS);

        $automation_options        = get_option('primer_automation');
        $mydata_options            = get_option('primer_mydata');
        $classificationType        = $classificationCategory = '';
        $classificationCategory_en = 'category1_95';
        $api_url                   = $mydata_options['mydata_api'];

        switch ($api_url) {
            case 'test_api':
                $url      = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type = 'test';
                break;
            case 'production_api':
                $url      = 'https://erp-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type = 'production';
                break;
            default:
                $url      = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type = 'test';
        }

        $primer_license_data     = get_option('primer_licenses');
        $username                = $primer_license_data['username'] ?: '';
        $password                = $primer_license_data['password'] ?: '';
        $user_vat                = $primer_license_data['companyVatNumber'];
        $callingFunction         = "convert_order_to_invoice";
        $send_api_invoice        = true;
        $auth                    = base64_encode("$username" . ':' . "$password");

        $curl_args = array(
            'timeout'     => 30,
            'redirection' => 10,
            'method'      => 'POST',
            'httpversion' => '1.1',
            'headers'     => array(
                'Authorization' => 'Basic ' . $auth,
                'Content-Type'  => 'application/json',
                'charset=UTF-8'
            ),
            'sslverify'   => false
        );

        $total_vat_number        = "$user_vat";
        $count_orders            = 0;
        $response_data           = $receipt_log_value = '';
        $activation_automation   = $automation_options['activation_automation'];
        $limit_automation_orders = $automation_options['automation_limit'];

        if (empty($limit_automation_orders)) {
            $limit_automation_orders = 50;
        } elseif ($limit_automation_orders == "unlimited") {
            $limit_automation_orders = -1;
        }

        $error_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'),
            'transmission_failure_aade'      => __('Could not connect to AADE. Please check your general settings if you want to enable transmission failure option or contact Primer Software if the problem persists.', 'primer'),
            'no_remaining'                   => __('You have no other monthly invoices left.Please go to MyData settings and press "Get Remaining" button if you are sure that the month is passed and you have remaining invoices.', 'primer'),
            'unable_connect_provider_aade'   => __('Unable to connect Provider and AADE.', 'primer'),
            'unable_connect_entity_provider' => __('Unable to connect Entity and provider.', 'primer'),
            'orders_converted'               => __('Orders converted', 'primer'),
            'api_not_sent'                   => __('API not sent.', '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>',
            'error_notice_template'          => '<div class="notice notice-error"><p>%s</p></div>',
            'success_notice_template'        => '<div class="notice notice-success"><p>%s</p></div>'
        ];

        if (!empty($automation_options) && !empty($activation_automation)) {
            $primer_conditions       = $automation_options['primer_conditions'];
            $primer_start_order_date = $automation_options['calendar_date_timestamp'];

            if (!empty($primer_conditions)) {
                foreach ($primer_conditions as $primer_condition) {
                    $condition_order_status = $primer_condition['receipt_order_states'];

                    $order_args = array(
                        'return'     => 'ids',
                        'limit'      => $limit_automation_orders,
                        'order'      => 'DESC',
//                        'min_total'  => 0.01,
                        'meta_query' => array(
                            array(
                                'key'     => 'receipt_status',
                                'value'   => 'issued',
                                'compare' => '!='
                            ),
                        ),
                    );

                    $order_args['status']   = $condition_order_status;

                    if (!empty($primer_start_order_date)) {
                        $order_args['date_created'] = '>=' . $primer_start_order_date;
                    }

                    $orders       = wc_get_orders($order_args);
                    $orders       = array_unique($orders);
                    $count_orders += count($orders);

                    $mydata_options['already_running_orders'] = count($orders) * 5;
                    update_option('primer_mydata', $mydata_options);
                    array_map('sanitize_text_field', $orders);

                    foreach ($orders as $order_id) {
                        $order          = new WC_Order($order_id);
                        $issue_date     = new DateTime("now", new DateTimeZone("Europe/Athens"));
                        $id_of_order    = $order->get_id();
                        $gr_time        = $issue_date->format('Y-m-d');

                        $receipt_log_id = wp_insert_post(array(
                            'post_type'      => 'pr_log_automation',
                            'post_title'     => 'Receipt automation report for #' . $id_of_order,
                            'comment_status' => 'closed',
                            'ping_status'    => 'closed',
                            'post_status'    => 'publish',
                        ));

                        if (!ini_get('allow_url_fopen')) {
                            $response_data             .= sprintf($error_messages['error_popup_template'], $error_messages['allow_url_fopen']);
                            $receipt_log_value_array[]  = $error_messages['allow_url_fopen'];
                            update_post_meta($receipt_log_id, 'receipt_log_automation_error', $error_messages['allow_url_fopen']);
                            break;
                        }
                        if (!extension_loaded('bcmath')) {
                            $response_data             .= sprintf($error_messages['error_popup_template'], $error_messages['bcmath']);
                            $receipt_log_value_array[]  = $error_messages['bcmath'];
                            update_post_meta($receipt_log_id, 'receipt_log_automation_error', $error_messages['bcmath']);
                            break;
                        }

                        if ($order->get_meta('receipt_status') == 'issued') {
                            continue;
                        }

                        $general_settings = get_option('primer_generals');

                        if ($general_settings['accept_zero_value_orders'] == 'on' && $order->get_total() == 0) {
                            continue;
                        }

                        $order_country = $order->get_billing_country();

                        if (empty($order_country)) {
                            $order_country = 'GR';
                        }

                        if (!empty($order->get_date_paid())) {
                            $order_paid_date = date('F j, Y', $order->get_date_paid()->getTimestamp());
                        } else {
                            $order_paid_date = date('F j, Y', $order->get_date_created()->getTimestamp());
                        }

                        if (!empty($receipt_log_id)) {
                            $order->update_meta_data('log_id_for_order', $receipt_log_id);
                            $order->save();
                            update_post_meta($receipt_log_id, 'receipt_log_automation_order_date', $order_paid_date);
                        }

                        $insert_taxonomy         = 'receipt_status';
                        $receipt_log_value_array = array();
                        $invoice_data            = $order_country = $order_invoice_type = $order_vatNumber = $user_order_email = $currency = $currency_symbol = $user_id = $order_total_price = $user_full_name = $user_data = $serie = $series = $number = $invoice_time = $invoice_term = $response_data = $invoiceType = $receipt_log_value = $total = '';
                        $response_to_array       = $response_code = $response_message = $response = null;

                        $create_json_instance        = new Create_json();
                        $Vat_exemption_categories    = $create_json_instance->getVatExemptionCategories();
                        $Vat_exemption_categories_en = $create_json_instance->getVatExemptionCategoriesEn();
                        $is_timeout                  = false;
                        $i                           = 1;

                        while ($i <= 1) {
                            $mydata_options    = get_option('primer_mydata');
                            $serie             = get_post_meta($order_id, '_primer_receipt_series', true) != null ? get_post_meta($order_id, '_primer_receipt_series', true) != null : '';
                            $series            = '';
                            $number            = get_post_meta($order_id, '_primer_receipt_number', true) != null ? get_post_meta($order_id, '_primer_receipt_number', true) : '';
                            $invoice_data      = $create_json_instance->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);
                            $curl_args['body'] = json_encode($invoice_data);
                            $response          = wp_remote_post($url, $curl_args);
                            $response_message  = wp_remote_retrieve_body($response);
                            $response_code     = wp_remote_retrieve_response_code($response);
                            if ($response_code == 400 && json_decode($response_message, true)['response'][0]['errors']['error'][0]['code'] == 228) {
                                $create_json_instance->numbering($order_invoice_type, $order_country, $mydata_options, $series);
                                update_option('primer_mydata', $mydata_options);
                                $i = 1;
                            } else {
                                $i++;
                            }
                        }

                        if ($invoice_data == "break") {
                            continue;
                        }

                        if ($send_api_invoice) {
                            if (is_wp_error($response)) {
                                $response_data             .= sprintf($error_messages['error_notice_template'], $response->get_error_message());
                                $receipt_log_value_array[] = $response->get_error_message();
                                $first_time                = '';
                                $string_timeout            = 'Operation timed out after';
                                $message_timeout           = $response->get_error_message();
                                $check_string_timeout      = strpos($message_timeout, $string_timeout);

                                if ($check_string_timeout) {
                                    $is_timeout = true;
                                    $first_time = $order->get_meta('order_date_failed_timeout');
                                    if ($first_time == null) {
                                        $order->update_meta_data('order_date_failed_timeout', $gr_time);
                                        $order->save();
                                        $first_time = $order->get_meta('order_date_failed_timeout');
                                    }
                                }

                            } else {
                                $response_to_array = wp_remote_retrieve_body($response);
                            }

                            $time_for_call_timeout_48 = $order->get_meta('order_datetime_failed');

                            if ($time_for_call_timeout_48 && ($response_code > 500 || $is_timeout)) {
                                $time_for_call_timeout_1 = date('Y-m-d H:i:s', strtotime($time_for_call_timeout_48 . ' + 2 days'));
                                if ($time_for_call_timeout_1 > $gr_time) {
                                    $mydata_options['timeout_check_48'] = 0;
                                } else {
                                    $mydata_options['timeout_check_48'] = 1;
                                    $order->update_meta_data('failed_48', 'yes');
                                    $order->save();
                                }
                                update_option('primer_mydata', $mydata_options);
                            }

                            $general_settings = get_option('primer_generals');

                            if ($general_settings['primer_cron_transmission_failure'] != 'on' && ($response_code == 502 || $response_code == 512)) {
                                $receipt_log_value         .= $error_messages['transmission_failure_aade'];
                                $response_data             .= sprintf($error_messages['error_notice_template'], $error_messages['transmission_failure_aade']);
                                $receipt_log_value_array[]  = $error_messages['transmission_failure_aade'];
                                continue;
                            }

                            $string_0_remaining     = 'You have no other Monthly Invoices remaining';
                            $check_string_remaining = strpos($response_message, $string_0_remaining);

                            if ($check_string_remaining !== false && $api_type == 'production') {
                                $mydata_options['check_0_remaining'] = 1;
                                update_option('primer_mydata', $mydata_options);
                            }

                            if ($mydata_options['check_0_remaining'] == 1 && $api_type == 'production') {
                                $receipt_log_value         .= $error_messages['no_remaining'];
                                $response_data             .= sprintf($error_messages['error_notice_template'], $error_messages['no_remaining']);
                                $receipt_log_value_array[] = $error_messages['no_remaining'];
                                break;
                            }

                            $generated_uid     = strtoupper(sha1(iconv("UTF-8", "ISO-8859-7", strval($invoice_data['invoice'][0]['issuer']['vatNumber']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['issueDate']) . '-' . strval($invoice_data['invoice'][0]['issuer']['branch']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['invoiceType']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['series']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['aa']))));
                            $response_to_array = json_decode($response_message);

                            if ($response_code == 400) {
                                $response_data             .= sprintf($error_messages['error_notice_template'], $response_message);
                                $receipt_log_value_array[] = $response_message;
                                update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                                continue;
                            }

                            if ($response_code == 403) {
                                $response_data             .= sprintf($error_messages['error_notice_template'], $response_message);
                                $receipt_log_value_array[] = $response_message;
                                update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                                continue;
                            }

                            if (!empty($response_to_array) || ($response_code > 500 || $is_timeout)) {
                                $response_from_array = $response_to_array->response;
                                if (!empty($response_from_array) || ($response_code > 500 || $is_timeout)) {
                                    if (($response_from_array[0]->statusCode == 'Success') || ($response_code > 500 || $is_timeout)) {
                                        $invoice_uid      = $response_from_array[0]->invoiceUid;
                                        $invoice_mark     = $response_from_array[0]->invoiceMark;
                                        $invoice_authcode = $response_from_array[0]->authenticationCode;

                                        $post_id = wp_insert_post(array(
                                            'post_type'      => 'primer_receipt',
                                            'post_title'     => '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, 'success_mydata_date', $invoice_date);
                                            update_post_meta($post_id, 'success_mydata_time', $invoice_time);
                                            update_post_meta($post_id, 'send_to_api_type', $api_type);
                                            update_post_meta($post_id, 'receipt_type', $invoice_term);
                                            update_post_meta($post_id, 'order_id_to_receipt', $id_of_order);
                                            $order->update_meta_data('order_id_from_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);
                                            $create_json_instance->numbering($order_invoice_type, $order_country, $mydata_options, $series);
                                            update_option('primer_mydata', $mydata_options);

                                            if (!empty($invoice_uid)) {
                                                update_post_meta($post_id, 'response_invoice_uid', $invoice_uid);
                                            }

                                            if (!empty($invoice_mark)) {
                                                update_post_meta($post_id, 'response_invoice_mark', $invoice_mark);
                                            }

                                            if (!empty($invoice_authcode)) {
                                                update_post_meta($post_id, 'response_invoice_authcode', $invoice_authcode);
                                            }

                                            if (!isset($primer_license_data['currentBranchID'])) {
                                                $currentBranchID = 0;
                                            } else {
                                                $currentBranchID = $primer_license_data['currentBranchID'];
                                            }

                                            update_post_meta($post_id, 'branchID', $currentBranchID);

                                            if ($response_code == 512) {
                                                update_post_meta($post_id, 'connection_fail_message', 'ΑΔΥΝΑΜΙΑ ΔΙΑΣΥΝΔΕΣΗΣ ΠΑΡΟΧΟΥ - ΑΑΔΕ');
                                            } elseif ($response_code > 500 || $is_timeout) {
                                                update_post_meta($post_id, 'connection_fail_message', 'ΑΔΥΝΑΜΙΑ ΔΙΑΣΥΝΔΕΣΗΣ ΟΝΤΟΤΗΤΑΣ - ΠΑΡΟΧΟΥ');
                                            } else {
                                                update_post_meta($post_id, 'connection_fail_message', '');
                                            }

                                            $order_log_id = $order->get_meta('log_id_for_order');

                                            if ($order_log_id) {
                                                update_post_meta($post_id, '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);
                                                update_post_meta($order_log_id, 'receipt_log_automation_status', 'issued');
                                                $get_issue_status = get_post_meta($post_id, 'receipt_status', true);
                                                if (empty($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);
                                            }
                                        }
                                        $post_issued = 'issued';
                                        update_post_meta($post_id, 'receipt_status', $post_issued);
                                        $order->update_meta_data('receipt_status', $post_issued);
                                        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);
                                        $order->update_meta_data('transmission_failure_check', 2);
                                        $order->update_meta_data('failed_48', 'no');
                                        $order->save();

                                        primer_generate_qr($post_id, $generated_uid);

                                        $primer_options = new Primer_Options();
                                        $post_ids_str   = $zip_response = '';

                                        if (!empty($post_id)) {
                                            $post_ids_str = $total_vat_number . $invoice_mark;
                                        }

                                        $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'];
                                        $upload_url = wp_upload_dir()['baseurl'] . '/exported_html_files';

                                        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 $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');
                                            }

                                        }

                                        $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();

                                        foreach ($data['invoice'][0]['invoiceDetails'] as $invoiceDetails) {
                                            if ($invoiceDetails['vatExemptionCategory'] != null) {
                                                $varExemptionCategory[] = $invoiceDetails['vatExemptionCategory'];
                                            }
                                        }

                                        $varExemptionCategory = array_unique($varExemptionCategory);
                                        $varExemptionCategory = array_values($varExemptionCategory);
                                        $count                = count($varExemptionCategory);
                                        $is_greece            = $order->get_meta('_billing_country') == 'GR' ? true : false;

                                        if ($is_greece) {
                                            if ($count > 0) {
                                                $exception_vat = '<div><span class="skin bold">ΑΠΑΛΛΑΓΗ ΑΠΟ ΤΟ Φ.Π.Α :</span></div>';
                                                for ($i = 0; $i < $count; $i++) {
                                                    $exception_vat .= '<div>' . $Vat_exemption_categories[$varExemptionCategory[$i]] . '</div>';
                                                }
                                            } else {
                                                $exception_vat = '';
                                            }
                                            $modified_homepage = str_replace('<div class="cont_notation"><span class="skin bold">ΠΑΡΑΤΗΡΗΣΕΙΣ:</span>', '<div class="cont_notation">' . $exception_vat . '<span class="skin bold">ΠΑΡΑΤΗΡΗΣΕΙΣ:</span>', $modified_homepage);
                                        } else {
                                            if ($count > 0) {
                                                $exception_vat = '<div><span class="skin bold">EXEMPTION FROM VAT :</span></div>';
                                                for ($i = 0; $i < $count; $i++) {
                                                    $exception_vat .= '<div>' . $Vat_exemption_categories_en[$varExemptionCategory[$i]] . '</div>';
                                                }
                                            } else {
                                                $exception_vat = '';
                                            }
                                            $modified_homepage = str_replace('<div class="cont_notation"><span class="skin bold">COMMENTS:</span>', '<div class="cont_notation">' . $exception_vat . '<span class="skin bold">COMMENTS:</span>', $modified_homepage);
                                        }

                                        $isDeliveryNote       = $data['invoice'][0]['invoiceHeader']['isDeliveryNote'];
                                        $deliveryStyle        = $isDeliveryNote ? 'height: 140px' : 'height: 120px';
                                        $deliveryStyleSecond  = $isDeliveryNote ? 'height: 180px' : 'height: 160px';
                                        $billing_invoice_type = $order->get_meta('_billing_invoice_type') == 'receipt' ? true : false;

                                        if ($billing_invoice_type && $is_greece) {
                                            $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                            $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                        } elseif ($billing_invoice_type && !$is_greece) {
                                            $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                            $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                        } elseif (!$billing_invoice_type && $is_greece) {
                                            $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                            $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                        } elseif (!$billing_invoice_type && !$is_greece) {
                                            $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                            $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                        }

                                        if (!$is_greece) {
                                            $modified_homepage = str_replace('<tr><p class="table_titles">CUSTOMER INFORMATION</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles" style="white-space: nowrap; text-align: center;">CUSTOMER INFORMATION</p></td></tr><tr>', $modified_homepage);
                                            $modified_homepage = str_replace('<tr><p class="table_titles">OTHER INFORMATION</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles">OTHER INFORMATION</p></td></tr><tr>', $modified_homepage);
                                        } else {
                                            $modified_homepage = str_replace('<tr><p class="table_titles">ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗ</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles" style="white-space: nowrap; text-align: center;">ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗ</p></td></tr><tr>', $modified_homepage);
                                            $modified_homepage = str_replace('<tr><p class="table_titles">ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles">ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ</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);
                                        $output    = $dompdf->output();
                                        file_put_contents($upload_dir . '/email-invoices/' . $post_name . '.pdf', $output);
                                        $attachments = $upload_dir . '/email-invoices/' . $post_name . '.pdf';
                                        $primer_smtp_options = get_option('primer_emails');

                                        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['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');
                                            $streetAdress        = $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}', $streetAdress, $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_condition['client_email_send'];
                                        $primer_smtp_type               = $primer_smtp_options['smtp_type'];
                                        $email_logs                     = '';

                                        if (!empty($primer_automatically_send_file) && $primer_automatically_send_file === 'on') {
                                            $primer_smtp = PrimerSMTP::get_instance();
                                            if (!empty($primer_smtp_options['email_from_name'])) {
                                                $from_name_email = $primer_smtp_options['email_from_name'];
                                            } else {
                                                $from_name_email = '';
                                            }
                                            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);
                                                if (!$mailResultSMTP) {
                                                    $email_logs = __('Email failed. Please check your email configuration', 'primer');
                                                    update_post_meta($order_log_id, 'receipt_log_automation_email_error', 'Email failed. Please check your email configuration');
                                                    update_post_meta($order_log_id, 'receipt_log_automation_email', 'not_sent');
                                                }
                                            } else {
                                                $mailResultSMTP = $primer_smtp->primer_mail_sender($user_order_email, $from_name_email, $primer_smtp_subject, $primer_smtp_message, $attachments);
                                                if (!$mailResultSMTP) {
                                                    $email_logs = __('Email failed. Please check your email configuration', 'primer');
                                                    update_post_meta($order_log_id, 'receipt_log_automation_email_error', 'Email failed. Please check your email configuration');
                                                    update_post_meta($order_log_id, 'receipt_log_automation_email', 'not_sent');
                                                }
                                            }
                                            if (!$primer_smtp->credentials_configured() && $primer_smtp_type != 'wordpress_default') {
                                                $email_logs .= __('Configure your SMTP credentials', 'primer') . "\n";

                                            }
                                            if (!empty($mailResultSMTP['error']) && (!$primer_smtp->credentials_configured() && $primer_smtp_type != 'wordpress_default')) {
                                                update_post_meta($order_log_id, 'receipt_log_automation_email', 'not_sent');
                                                $email_logs .= $GLOBALS['phpmailer']->ErrorInfo . "\n";
                                                update_post_meta($order_log_id, 'receipt_log_automation_email_error', $email_logs);
                                                update_post_meta($order_log_id, 'receipt_log_automation_total_status', 'only_errors');
                                            } else {
                                                update_post_meta($order_log_id, 'receipt_log_automation_email', 'sent');
                                                update_post_meta($order_log_id, 'receipt_log_automation_total_status', 'only_issued');
                                            }
                                            if (!filter_var($user_order_email, FILTER_VALIDATE_EMAIL)) {
                                                update_post_meta($order_log_id, 'receipt_log_automation_email', 'not_sent');
                                                update_post_meta($order_log_id, 'receipt_log_automation_email_error', 'Invalid email');
                                            }
                                            if ($email_logs != '') {
                                                update_post_meta($order_log_id, 'receipt_log_automation_email', 'not_sent');
                                                update_post_meta($order_log_id, 'receipt_log_automation_email_error', $email_logs);
                                            }
                                            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_automation_email', 'not_sent');
                                            update_post_meta($order_log_id, 'receipt_log_automation_email_error', $email_logs);
                                            update_post_meta($order_log_id, 'receipt_log_automation_total_status', 'only_issued');
                                        }
                                        $mydata_options['timeout_check_48'] = 0;

                                        if (($response_code > 500 || $is_timeout) && $general_settings['primer_cron_transmission_failure'] == 'on') {
                                            if ($response_code == 512) {
                                                $receipt_log_value         .= $error_messages['unable_connect_provider_aade'];
                                                $receipt_log_value_array[] = $error_messages['unable_connect_provider_aade'];
                                                $order->update_meta_data('transmission_failure_check', 3);
                                                $order->save();
                                                update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                                            } else {
                                                $receipt_log_value         .= $error_messages['unable_connect_entity_provider'];
                                                $receipt_log_value_array[] = $error_messages['unable_connect_entity_provider'];
                                                $order->update_meta_data('transmission_failure_check', 1);
                                                $order->save();
                                                update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                                            }

                                            $gr_timezone = new DateTimeZone("Europe/Athens");
                                            $gr_time     = new DateTime("now", $gr_timezone);
                                            $order->update_meta_data('order_date_failed', $gr_time->format('Y-m-d'));
                                            $order->update_meta_data('order_datetime_failed', $gr_time->format('Y-m-d H:i:s'));
                                            $order->save();
                                        }
                                        $response_data = sprintf($error_messages['success_notice_template'], $error_messages['orders_converted']);
                                    } else {
                                        update_option('primer_mydata', $mydata_options);
                                        $response_data             .= is_object($response_from_array[0]->errors) ? json_encode($response_from_array[0]->errors) : $response_from_array[0]->errors;
                                        $receipt_log_value_array[] = $response_data;
                                        continue;
                                    }
                                }
                            } else {
                                $receipt_log_value_array[] = $error_messages['api_not_sent'];
                                update_post_meta($receipt_log_id, 'receipt_log_automation_error', $receipt_log_value_array);
                            }

                            if (!empty($receipt_log_value_array)) {
                                update_post_meta($receipt_log_id, 'receipt_log_automation_error', $receipt_log_value_array);
                            }

                        } else {
                            break;
                        }
                    }
                }
            }

            if (!empty($log_ids)) {
                foreach ($log_ids as $log_id) {
                    $check_if_error = get_post_meta($log_id, 'receipt_log_automation_error', true);
                    if (!empty($check_if_error) && $check_if_error != '') {
                        update_post_meta($log_id, 'receipt_log_automation_total_status', 'only_errors');
                    }
                }
            }

            $primer_send_success_log = $primer_send_fail_log = '';

            if (!empty($automation_options['send_successful_log'])) {
                $primer_send_success_log = $automation_options['send_successful_log'];
            }

            if (!empty($automation_options['send_failed_log'])) {
                $primer_send_fail_log = $automation_options['send_failed_log'];
            }

            if ($count_orders > 0) {
                if ($automation_options['send_email_to_admin'] == 'on') {
                    $this->export_csv_log($log_ids, $primer_send_success_log, $primer_send_fail_log);
                }
            }
        }

        delete_transient('convert_order_to_invoice_lock');
        wp_die();
    }

    public function convert_order_to_invoice_failed() {
        global $wpdb, $woocommerce;

        $log_ids                   = $emails = $api_urls = $post_ids = $order_ids = $log_ids = $receipt_log_value_array = array();
        $mydata_options            = get_option('primer_mydata');
        $callingFunction           = "convert_order_to_invoice_failed";
        $classificationType        = $classificationCategory = $response_data = $receipt_log_value = '';
        $classificationCategory_en = 'category1_95';
        $api_url                   = $mydata_options['mydata_api'];

        switch ($api_url) {
            case 'test_api':
                $api_urls[] = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $url        = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type   = 'test';
                break;
            case 'production_api':
                $api_urls[] = 'https://erp-mydataapi.primer.gr/v2/invoices/sendData';
                $url        = 'https://erp-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type   = 'production';
                break;
            default:
                $api_urls[] = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $url        = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type   = 'test';
        }

        $primer_license_data = get_option('primer_licenses');
        $username            = $primer_license_data['username'] ?: '';
        $password            = $primer_license_data['password'] ?: '';
        $user_vat            = $primer_license_data['companyVatNumber'];
        $url_slug            = 'https://erp-mydataapi.primer.gr';
        $auth                = base64_encode("$username" . ':' . "$password");

        $curl_args = array(
            'timeout'     => 30,
            'redirection' => 10,
            'method'      => 'POST',
            'httpversion' => '1.1',
            'headers'     => array(
                'Authorization' => 'Basic ' . $auth,
                'Content-Type'  => 'application/json',
                'charset=UTF-8'
            ),
            'sslverify'   => false
        );

        $total_vat_number = "$user_vat";

        $order_args = array(
            'return' => 'ids',
            'limit'  => 499,
            'order'  => 'DESC'
        );

        $error_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'),
            'no_remaining_invoices'   => __('You have no other monthly invoices left.Please go to MyData settings and press "Get Remaining" button if you are sure that the month is passed and you have remaining invoices.', 'primer'),
            'orders_converted'        => __('Orders converted', '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>',
            'error_notice_template'   => '<div class="notice notice-error"><p>%S</p></div>',
            'success_notice_template' => '<div class="notice notice-success"><p>%s</p></div>'
        ];

        $orders = wc_get_orders($order_args);

        foreach ($orders as $order_id) {
            $invoice_data = array(
                "invoice" => array(),
            );

            $order = new WC_Order($order_id);

            if (is_a($order, 'WC_Order_Refund')) {
                $order = wc_get_order($order->get_parent_id());
            }

            $id_of_order                   = $order->get_id();
            $order_ids[]                   = $id_of_order;
            $check_timeout                 = $order->get_meta('failed_48');
            $check_transmission_failure_48 = $order->get_meta('transmission_failure_check');
            $issued_order                  = $order->get_meta('receipt_status');
            $transmission_failure          = $order->get_meta('transmission_failure_check');
            $post_id_failed                = $order->get_meta('order_id_from_receipt');
            $branchID                      = get_post_meta($post_id_failed, 'branchID', true);

            if ($branchID == null) {
                $branchID = 0;
            }

            $check_api_type = get_post_meta($post_id_failed, 'send_to_api_type', true);
            $already_issued = get_post_meta($post_id_failed, 'response_invoice_mark', true);

            if (($transmission_failure == 1 || $transmission_failure == 3) && $check_api_type == 'production' && empty($already_issued)) {
                $time_for_call_timeout_48 = $order->get_meta('order_datetime_failed');
                $time_for_call_timeout_1  = '';
                $issue_date               = new DateTime("now", new DateTimeZone("Europe/Athens"));
                $order_datetime_co        = $order->get_meta('order_datetime_failed');

                if ($order_datetime_co != '') {
                    $issue_date = new DateTime($order_datetime_co, new DateTimeZone("Europe/Athens"));
                }

                $gr_time      = $issue_date->format('Y-m-d');
                $invoice_time = $issue_date->format('H:i');
                if ($time_for_call_timeout_48) {
                    $time_for_call_timeout_1 = date('Y-m-d H:i:s', strtotime($time_for_call_timeout_48 . ' + 2 days'));
                    if ($time_for_call_timeout_1 > $gr_time) {
                        $mydata_options['timeout_check_48'] = 0;
                    } else {
                        $mydata_options['timeout_check_48'] = 1;
                        $order->update_meta_data('failed_48', 'yes');
                        $order->save();
                    }
                    update_option('primer_mydata', $mydata_options);
                }

                $receipt_log_id = wp_insert_post(array(
                    'post_type'      => 'primer_receipt_log',
                    'post_title'     => 'Receipt report for #' . $id_of_order,
                    'comment_status' => 'closed',
                    'ping_status'    => 'closed',
                    'post_status'    => 'publish',
                ));

                if (!ini_get('allow_url_fopen')) {
                    $response_data     .= sprintf($error_messages['error_popup_template'], $error_messages['allow_url_fopen']);
                    $receipt_log_value .= $error_messages['allow_url_fopen'];
                    break;
                }
                if (!extension_loaded('bcmath')) {
                    $response_data     .= sprintf($error_messages['error_popup_template'], $error_messages['bcmath']);
                    $receipt_log_value .= $error_messages['bcmath'];
                    break;
                }

                $order_country = $order_invoice_type = $order_vatNumber = $user_order_email = $currency = $currency_symbol = $user_id = $order_total_price = $user_full_name = $user_data = $invoice_term = $response_data = $invoiceType = $receipt_log_value = $total = $series = '';

                $receipt_log_value_array = array();

                $insert_taxonomy         = 'receipt_status';
                $serie                   = get_post_meta($post_id_failed, '_primer_receipt_series', true);
                $number                  = get_post_meta($post_id_failed, '_primer_receipt_number', true);
                $connectionFailedMessage = get_post_meta($post_id_failed, 'connection_fail_message', true);

                $create_json_instance        = new Create_json();
                $Vat_exemption_categories    = $create_json_instance->getVatExemptionCategories();
                $Vat_exemption_categories_en = $create_json_instance->getVatExemptionCategoriesEn();
                $invoice_data                = $create_json_instance->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);

                if ($invoice_data == "break") {
                    break;
                }

                $curl_args['body'] = json_encode($invoice_data);
                $response          = wp_remote_post($url, $curl_args);
                $response_message  = wp_remote_retrieve_body($response);
                $response_code     = wp_remote_retrieve_response_code($response);
                $response_to_array = null;

                if (is_wp_error($response)) {
                    $response_data             .= sprintf($error_messages['error_notice_template'], $response->get_error_message());
                    $receipt_log_value_array[] = $response->get_error_message();
                } else {
                    $response_to_array = wp_remote_retrieve_body($response);
                }

                if (!empty($response_to_array)) {
                    $response_to_array = json_decode($response_to_array);
                }

                $string_0_remaining     = 'You have no other Monthly Invoices remaining';
                $check_string_remaining = strpos($response_message, $string_0_remaining);

                if ($check_string_remaining !== false && $api_type == 'production') {
                    $mydata_options['check_0_remaining'] = 1;
                    update_option('primer_mydata', $mydata_options);
                }

                $generated_uid     = strtoupper(sha1(iconv("UTF-8", "ISO-8859-7", strval($invoice_data['invoice'][0]['issuer']['vatNumber']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['issueDate']) . '-' . strval($invoice_data['invoice'][0]['issuer']['branch']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['invoiceType']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['series']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['aa']))));
                $string_r          = 'It has already been sent for another invoice';
                $validate_response = strpos($response_message, $string_r);

                if ($validate_response !== false) {
                    $create_status_instance = new Create_json();
                    $status                 = $create_status_instance->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);
                    if ($status == "break") {
                        continue;
                    } else {
                        update_option('primer_mydata', $mydata_options);
                    }
                }

                if ($mydata_options['check_0_remaining'] == 1 && $api_type == 'production') {
                    $receipt_log_value         .= $error_messages['no_remaining_invoices'];
                    $response_data             .= sprintf($error_messages['error_notice_template'], $error_messages['no_remaining_invoices']);
                    $receipt_log_value_array[] = $error_messages['no_remaining_invoices'];
                    break;
                }

                // Αν υπάρχει mark για το invoice και έχει φτάσει εδώ, τότε σταματάει εδώ το cron γιατί το $response_code είναι 400.
                // Για την κατάσταση του τιμολογίου συνεχίζει γιατί το $last_info είναι 200.
                // Το $response εδώ είναι "It has already been sent for another invoice"
                if ($response_code == 400 || $response_code == 422) {
                    $response_data             .= sprintf($error_messages['error_notice_template'], $response_message);
                    $receipt_log_value_array[] = $response_message;
                    update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                    continue;
                }

                if ($response_code == 403) {
                    $response_data             .= sprintf($error_messages['error_notice_template'], $response_message);
                    $receipt_log_value_array[] = $response_message;
                    update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                    continue;
                }

                $response_from_array = $response_to_array->response;

                if (!empty($response_to_array)) {
                    if (!empty($response_from_array)) {
                        if ($response_from_array[0]->statusCode == 'Success') {
                            $invoice_uid      = $response_from_array[0]->invoiceUid;
                            $invoice_mark     = $response_from_array[0]->invoiceMark;
                            $invoice_authcode = $response_from_array[0]->authenticationCode;

                            $post_id = wp_insert_post(array(
                                'post_type'      => 'primer_receipt',
                                'post_title'     => 'Receipt for order #' . $id_of_order . '-failed',
                                'comment_status' => 'closed',
                                'ping_status'    => 'closed',
                                'post_status'    => 'publish',
                            ));

                            wp_set_object_terms($post_id, $invoice_term, $insert_taxonomy, false);

                            if ($post_id) {
                                $order_date_co     = $order->get_meta('order_date_failed');
                                $order_datetime_co = $order->get_meta('order_datetime_failed');
                                $issue_date        = new DateTime($order_datetime_co, new DateTimeZone("Europe/Athens"));
                                $invoice_date      = $issue_date->format('d/m/Y');
                                $invoice_time      = $issue_date->format('H:i');
                                update_post_meta($post_id, 'success_mydata_date', $invoice_date);
                                update_post_meta($post_id, '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_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);
                                update_option('primer_mydata', $mydata_options);

                                if (!empty($invoice_uid)) {
                                    update_post_meta($post_id, 'response_invoice_uid', $invoice_uid);
                                    $order->update_meta_data('transmission_failure_check', 2);
                                    $order->save();
                                }

                                if (!empty($invoice_mark)) {
                                    update_post_meta($post_id, 'response_invoice_mark', $invoice_mark);
                                }

                                if (!empty($invoice_authcode)) {
                                    update_post_meta($post_id, 'response_invoice_authcode', $invoice_authcode);
                                }

                                update_post_meta($post_id, 'branchID', $branchID);
                                update_post_meta($post_id, 'connection_fail_message', $connectionFailedMessage);
                                $order_log_id = $order->get_meta('log_id_for_order');

                                if ($order_log_id) {
                                    update_post_meta($post_id, '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);

                                    if (empty($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);
                                }
                            }

                            primer_generate_qr($post_id, $generated_uid);

                            $primer_options = new Primer_Options();
                            $post_ids_str   = '';

                            if (!empty($post_id)) {
                                $post_ids_str = $total_vat_number . $invoice_mark;
                            }

                            $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);
                            $zip_response           = '';
                            $upload_dir             = wp_upload_dir()['basedir'];
                            $upload_url             = wp_upload_dir()['baseurl'] . '/exported_html_files';

                            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 $primer_options->create_zip($files, $zip_file_name, $all_files . '/');
                                $create_zip = ob_get_clean();
                                if ($create_zip == 'created') {
                                    $primer_options->rmdir_recursive(WP_CONTENT_DIR . '/uploads/exported_html_files/tmp_files');
                                }
                                $zip_response = ($create_zip == 'created') ? $upload_url . '/' . $post_ids_str . '_html.zip' : false;
                            }

                            if ($zip_response !== false) {
                                $html_body_args['invoiceFile'] = curl_file_create($_SERVER["DOCUMENT_ROOT"] . '/wp-content/uploads/exported_html_files/' . $post_ids_str . '_html.zip', 'application/zip', $post_ids_str . '_html.zip');
                            }

                            $order->update_meta_data('transmission_failure_check', 2);
                            $order->save();

                            $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"
                                    ],
                                ),
                            );

                            $homepage          = file_get_contents($post_url, false, stream_context_create($arrContextOptions));
                            $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();
                            foreach ($data['invoice'][0]['invoiceDetails'] as $invoiceDetails) {
                                if ($invoiceDetails['vatExemptionCategory'] != null) {
                                    $varExemptionCategory[] = $invoiceDetails['vatExemptionCategory'];
                                }
                            }

                            $varExemptionCategory = array_unique($varExemptionCategory);
                            $varExemptionCategory = array_values($varExemptionCategory);
                            $count                = count($varExemptionCategory);
                            $is_greece            = $order->get_meta('_billing_country') == 'GR' ? true : false;

                            if ($is_greece) {
                                if ($count > 0) {
                                    $exception_vat = '<div><span class="skin bold">ΑΠΑΛΛΑΓΗ ΑΠΟ ΤΟ Φ.Π.Α :</span></div>';
                                    for ($i = 0; $i < $count; $i++) {
                                        $exception_vat .= '<div>' . $Vat_exemption_categories[$varExemptionCategory[$i]] . '</div>';
                                    }
                                } else {
                                    $exception_vat = '';
                                }
                                $modified_homepage = str_replace('<div class="cont_notation"><span class="skin bold">ΠΑΡΑΤΗΡΗΣΕΙΣ:</span>', '<div class="cont_notation">' . $exception_vat . '<span class="skin bold">ΠΑΡΑΤΗΡΗΣΕΙΣ:</span>', $modified_homepage);
                            } else {
                                if ($count > 0) {
                                    $exception_vat = '<div><span class="skin bold">EXEMPTION FROM VAT :</span></div>';
                                    for ($i = 0; $i < $count; $i++) {
                                        $exception_vat .= '<div>' . $Vat_exemption_categories_en[$varExemptionCategory[$i]] . '</div>';
                                    }
                                } else {
                                    $exception_vat = '';
                                }
                                $modified_homepage = str_replace('<div class="cont_notation"><span class="skin bold">COMMENTS:</span>', '<div class="cont_notation">' . $exception_vat . '<span class="skin bold">COMMENTS:</span>', $modified_homepage);
                            }

                            $isDeliveryNote       = $data['invoice'][0]['invoiceHeader']['isDeliveryNote'];
                            $deliveryStyle        = $isDeliveryNote ? 'height: 140px' : 'height: 120px';
                            $deliveryStyleSecond  = $isDeliveryNote ? 'height: 180px' : 'height: 160px';
                            $billing_invoice_type = $order->get_meta('_billing_invoice_type') == 'receipt' ? true : false;

                            if ($billing_invoice_type && $is_greece) {
                                $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                            } elseif ($billing_invoice_type && !$is_greece) {
                                $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                            } elseif (!$billing_invoice_type && $is_greece) {
                                $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                            } elseif (!$billing_invoice_type && !$is_greece) {
                                $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                            }
                            if (!$is_greece) {
                                $modified_homepage = str_replace('<tr><p class="table_titles">CUSTOMER INFORMATION</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles" style="white-space: nowrap; text-align: center;">CUSTOMER INFORMATION</p></td></tr><tr>', $modified_homepage);
                                $modified_homepage = str_replace('<tr><p class="table_titles">OTHER INFORMATION</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles">OTHER INFORMATION</p></td></tr><tr>', $modified_homepage);
                            } else {
                                $modified_homepage = str_replace('<tr><p class="table_titles">ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗ</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles" style="white-space: nowrap; text-align: center;">ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗ</p></td></tr><tr>', $modified_homepage);
                                $modified_homepage = str_replace('<tr><p class="table_titles">ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles">ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ</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);
                            $output    = $dompdf->output();
                            file_put_contents($upload_dir . '/email-invoices/' . $post_name . '.pdf', $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);
                            $primer_smtp_options = get_option('primer_emails');

                            $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['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';
                            }

                            $email_logs = '';

                            if (!empty($primer_automatically_send_file) && $primer_automatically_send_file === 'yes' && $user_order_email != '' && $user_order_email != null) {
                                $primer_smtp = PrimerSMTP::get_instance();
                                if (!empty($primer_smtp_options['email_from_name'])) {
                                    $from_name_email = $primer_smtp_options['email_from_name'];
                                } else {
                                    $from_name_email = '';
                                }
                                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() && $primer_smtp_type != 'wordpress_default') {
                                    $email_logs .= __('Configure your SMTP credentials', 'primer') . "\n";
                                }
                                if (!empty($mailResultSMTP['error']) && (!$primer_smtp->credentials_configured() && $primer_smtp_type != 'wordpress_default')) {
                                    $response_data .= sprintf($error_messages['error_notice_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);
                            $order->update_meta_data('failed_48', 'no');
                            $order->save();
                            $mydata_options['timeout_check_48'] = 0;

                            update_option('primer_mydata', $mydata_options);

                            $response_data = sprintf($error_messages['success_notice_template'], $error_messages['orders_converted']);
                        } else {
                            update_option('primer_mydata', $mydata_options);
                            $response_data             .= is_object($response_from_array[0]->errors) ? json_encode($response_from_array[0]->errors) : $response_from_array[0]->errors;
                            $receipt_log_value_array[] = $response_data;
                            continue;
                        }
                    }
                }

                if (!empty($receipt_log_value_array)) {
                    update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                }

            } else {
                continue;
            }

            if (!empty($log_ids)) {
                foreach ($log_ids as $log_id) {
                    update_post_meta($log_id, 'receipt_log_error', $receipt_log_value_array);
                    if (!empty($receipt_log_value_array)) {
                        update_post_meta($log_id, 'receipt_log_total_status', 'only_errors');
                    }
                }
            }
        }

        wp_die();

    }

    public function primer_cancel_invoice_cron() {
        $mydata_options            = get_option('primer_mydata');
        $send_characterizations    = $mydata_options['send_characterizations'];
        $classificationType        = $classificationCategory = $api_type = $url = $url_slug = $invoiceType = $response_data = $receipt_log_value = $receipt_status_text = '';
        $classificationCategory_en = 'category1_95';
        $api_url                   = $mydata_options['mydata_api'];
        $api_urls                  = $post_ids = $order_ids = $log_ids = $receipt_ids = $receipt_log_value_array = $orders = array();

        switch ($api_url) {
            case 'test_api':
                $api_urls[] = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $url        = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type   = 'test';
                break;
            case 'production_api':
                $api_urls[] = 'https://erp-mydataapi.primer.gr/v2/invoices/sendData';
                $url        = 'https://erp-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type   = 'production';
                break;
            default:
                $api_urls[] = 'https://test-mydataapi.primer.gr/v2/invoices/sendData';
                $url        = 'https://erp-mydataapi.primer.gr/v2/invoices/sendData';
                $api_type   = 'test';
        }

        $primer_license_data = get_option('primer_licenses');
        $username            = $primer_license_data['username'] ?: '';
        $password            = $primer_license_data['password'] ?: '';
        $user_vat            = $primer_license_data['companyVatNumber'];
        $callingFunction     = "primer_cancel_invoice_cron";
        $url_slug            = 'https://erp-mydataapi.primer.gr';
        $send_api_invoice    = true;
        $auth                = base64_encode("$username" . ':' . "$password");

        $curl_args = array(
            'timeout'     => 30,
            'redirection' => 10,
            'method'      => 'POST',
            'httpversion' => '1.1',
            'headers'     => array(
                'Authorization' => 'Basic ' . $auth,
                'Content-Type'  => 'application/json',
                'charset=UTF-8'
            ),
            'sslverify'   => false
        );

        $total_vat_number = "$user_vat";

        $receipt_args = array(
            'posts_per_page' => -1,
            'post_type'      => 'primer_receipt',
            'post_status'    => 'publish',
        );

        $error_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'),
            'transmission_failure_aade' => __('Could not connect to AADE. Please check your general settings if you want to enable transmission failure option or contact Primer Software if the problem persists.', 'primer'),
            'no_remaining'              => __('You have no other monthly invoices left.Please go to MyData settings and press "Get Remaining" button if you are sure that the month is passed and you have remaining invoices.', 'primer'),
            'orders_converted'          => __('Orders converted', 'primer'),
            'api_not_sent'              => __('API not sent.', '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>',
            'error_notice_template'     => '<div class="notice notice-error"><p>%s</p></div>',
            'success_notice_template'   => '<div class="notice notice-success"><p>%s</p></div>'
        ];

        $receipt_query = new WP_Query($receipt_args);

        if ($receipt_query->have_posts()):
            while ($receipt_query->have_posts()):
                $receipt_query->the_post();
                $transmission_failure_receipt = get_post_meta(get_the_ID(), 'transmission_failure_check', true);
                if (!empty($transmission_failure_receipt)) {
                    $receipt_ids[] = get_the_ID();
                }
            endwhile;
        endif;

        if (!empty($receipt_ids)) {
            foreach ($receipt_ids as $receipt_id) {
                $receipt_id     = (int) $receipt_id;
                $order_id       = get_post_meta($receipt_id, 'order_id_to_receipt', true);
                $order          = wc_get_order($order_id);
                $check_for_mark = $order->get_meta('order_id_from_credit_receipt');

                if (empty(get_post_meta($check_for_mark, 'response_invoice_mark', true))) {
                    $get_mark_from_receipt   = $order->get_meta('order_id_from_receipt');
                    $post_id_failed          = $order->get_meta('order_id_from_receipt');
                    $receipt_id_failed       = $order->get_meta('order_id_from_credit_receipt');
                    $connectionFailedMessage = get_post_meta($receipt_id_failed, 'connection_fail_message', true);
                    $branchID                = get_post_meta($post_id_failed, 'branchID', true);

                    if ($branchID == null) {
                        $branchID = 0;
                    }

                    $order          = new WC_Order($order_id);
                    $id_of_order    = $order->get_id();
                    $orders[]       = $id_of_order;
                    $issue_date     = new DateTime("now", new DateTimeZone("Europe/Athens"));
                    $gr_time        = $issue_date->format('Y-m-d');
                    $receipt_log_id = wp_insert_post(array(
                        'post_type'      => 'primer_receipt_log',
                        'post_title'     => 'Credit Receipt report for #' . $id_of_order,
                        'comment_status' => 'closed',
                        'ping_status'    => 'closed',
                        'post_status'    => 'publish',
                    ));

                    if (!ini_get('allow_url_fopen')) {
                        $response_data     .= sprintf($error_messages['error_popup_template'], $error_messages['allow_url_fopen']);
                        $receipt_log_value .= $error_messages['allow_url_fopen'];
                        break;
                    }
                    if (!extension_loaded('bcmath')) {
                        $response_data     .= sprintf($error_messages['error_popup_template'], $error_messages['bcmath']);
                        $receipt_log_value .= $error_messages['bcmath'];
                        break;
                    }

                    if (!empty($order->get_date_paid())) {
                        $order_paid_date = date('F j, Y', $order->get_date_paid()->getTimestamp());
                    } else {
                        $order_paid_date = date('F j, Y', $order->get_date_created()->getTimestamp());
                    }

                    update_post_meta($receipt_log_id, 'receipt_log_order_id', $id_of_order);

                    if (!empty($receipt_log_id)) {
                        $order->update_meta_data('credit_log_id_for_order', $receipt_log_id);
                        $order->save();
                        update_post_meta($receipt_log_id, 'receipt_log_order_date', $order_paid_date);
                    }

                    $order_country = $order_invoice_type = $order_vatNumber = $user_order_email = $currency = $currency_symbol = $user_id = $order_total_price = $user_full_name = $user_data = $invoice_term = $response_data = $invoice_time = $receipt_log_value = $total = $series = '';

                    $receipt_log_value_array = array();
                    $insert_taxonomy         = 'receipt_status';
                    $serie                   = get_post_meta($receipt_id, '_primer_receipt_series', true);
                    $number                  = get_post_meta($receipt_id, '_primer_receipt_number', true);
                    $invoice_type            = get_the_terms($receipt_id, 'receipt_status');
                    $invoice_type_slug       = $invoice_type[0]->slug;
                    $invoice_type_name       = explode('-', $invoice_type_slug);
                    $order_invoice_type      = $invoice_type_name[1];
                    $vat_number              = $order->get_meta('_billing_vat');

                    $create_json_instance        = new Create_json();
                    $Vat_exemption_categories    = $create_json_instance->getVatExemptionCategories();
                    $Vat_exemption_categories_en = $create_json_instance->getVatExemptionCategoriesEn();

                    $invoice_data = $create_json_instance->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, true, $get_mark_from_receipt);

                    if ($invoice_data == "break") {
                        break;
                    }

                    $curl_args['body'] = json_encode($invoice_data);
                    $response          = wp_remote_post($url, $curl_args);
                    $response_message  = wp_remote_retrieve_body($response);
                    $response_code     = wp_remote_retrieve_response_code($response);
                    $response_to_array = null;

                    if (is_wp_error($response)) {
                        $response_data             .= sprintf($error_messages['error_notice_template'], $response->get_error_message());
                        $receipt_log_value_array[] = $response->get_error_message();
                    }

                    if (!empty($response_to_array)) {
                        $response_to_array = json_decode($response_to_array);
                    }

                    $general_settings = get_option('primer_generals');

                    if ($general_settings['primer_cron_transmission_failure'] != 'on' && ($response_code == 502 || $response_code == 512)) {
                        $receipt_log_value         .= $error_messages['transmission_failure_aade'];
                        $response_data             .= sprintf($error_messages['error_notice_template'], $error_messages['transmission_failure_aade']);
                        $receipt_log_value_array[] = $error_messages['transmission_failure_aade'];
                        break;
                    }

                    $string_0_remaining     = 'You have no other Monthly Invoices remaining';
                    $check_string_remaining = strpos($response_message, $string_0_remaining);

                    if ($check_string_remaining !== false && $api_type == 'production') {
                        $mydata_options['check_0_remaining'] = 1;
                        update_option('primer_mydata', $mydata_options);
                    }

                    $generated_uid     = strtoupper(sha1(iconv("UTF-8", "ISO-8859-7", strval($invoice_data['invoice'][0]['issuer']['vatNumber']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['issueDate']) . '-' . strval($invoice_data['invoice'][0]['issuer']['branch']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['invoiceType']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['series']) . '-' . strval($invoice_data['invoice'][0]['invoiceHeader']['aa']))));
                    $string_r          = 'It has already been sent for another invoice';
                    $validate_response = strpos($response_message, $string_r);

                    if ($validate_response !== false) {
                        $create_status_instance = new Create_json();
                        $status                 = $create_status_instance->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);
                        if ($status == "break") {
                            continue;
                        } else {
                            update_option('primer_mydata', $mydata_options);
                        }
                    }

                    if ($mydata_options['check_0_remaining'] == 1 && $api_type == 'production') {
                        $receipt_log_value         .= $error_messages['no_remaining'];
                        $response_data             .= sprintf($error_messages['error_notice_template'], $error_messages['no_remaining']);
                        $receipt_log_value_array[] = $error_messages['no_remaining'];
                        break;
                    }

                    $response_to_array = json_decode($response_message);

                    if ($response_code == 400 || $response_code == 422) {
                        $response_data             .= sprintf($error_messages['error_notice_template'], $response_message);
                        $receipt_log_value_array[] = $response_to_array;
                        update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                        continue;
                    }

                    if ($response_code == 403) {
                        $response_data             .= sprintf($error_messages['error_notice_template'], $response_message);
                        $receipt_log_value_array[] = $response_message;
                        update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                        continue;
                    }

                    if (!empty($response_to_array)) {
                        $response_from_array = $response_to_array->response;
                        if (!empty($response_from_array)) {
                            if (($response_from_array[0]->statusCode == 'Success')) {
                                $invoice_uid      = $response_from_array[0]->invoiceUid;
                                $invoice_mark     = $response_from_array[0]->invoiceMark;
                                $invoice_authcode = $response_from_array[0]->authenticationCode;

                                $post_id = wp_insert_post(array(
                                    'post_type'      => 'primer_receipt',
                                    'post_title'     => 'Credit Receipt for order #' . $id_of_order . '-failed',
                                    'comment_status' => 'closed',
                                    'ping_status'    => 'closed',
                                    'post_status'    => 'publish',
                                ));

                                wp_set_object_terms($post_id, $invoice_term, $insert_taxonomy, false);

                                if ($post_id) {
                                    $order_date_co     = $order->get_meta('order_date_failed');
                                    $order_datetime_co = $order->get_meta('order_datetime_failed');
                                    $issue_date        = new DateTime($order_datetime_co, new DateTimeZone("Europe/Athens"));
                                    $invoice_date      = $issue_date->format('d/m/Y');
                                    $invoice_time      = $issue_date->format('H:i');
                                    update_post_meta($post_id, 'credit_success_mydata_date', $invoice_date);
                                    update_post_meta($post_id, 'credit_success_mydata_time', $invoice_time);
                                    update_post_meta($post_id, 'send_to_api_type', $api_type);
                                    if ($api_type == 'test') {
                                        $url_slug = 'https://test-mydataapi.primer.gr';
                                    }
                                    update_post_meta($post_id, 'order_id_to_receipt', $id_of_order);
                                    $order->update_meta_data('order_id_from_credit_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);
                                    update_post_meta($post_id, 'credit_receipt', 'yes');
                                    update_option('primer_mydata', $mydata_options);
                                    if (!empty($invoice_uid)) {
                                        update_post_meta($post_id, 'response_invoice_uid', $invoice_uid);
                                    }
                                    if (!empty($invoice_mark)) {
                                        update_post_meta($post_id, 'response_invoice_mark', $invoice_mark);
                                    }
                                    if (!empty($invoice_authcode)) {
                                        update_post_meta($post_id, 'response_invoice_authcode', $invoice_authcode);
                                    }
                                    update_post_meta($post_id, 'branchID', $branchID);
                                    update_post_meta($post_id, 'connection_fail_message', $connectionFailedMessage);
                                    $order_log_id = $order->get_meta('credit_log_id_for_order');
                                    if ($order_log_id) {
                                        update_post_meta($post_id, 'credit_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);
                                        if (empty($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');
                                        }
                                    }
                                }

                                primer_generate_qr($post_id, $generated_uid);

                                $primer_options = new Primer_Options();
                                $post_ids_str   = '';

                                if (!empty($post_id)) {
                                    $post_ids_str = $total_vat_number . $invoice_mark;
                                }

                                $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);
                                $zip_response           = '';
                                $upload_dir             = wp_upload_dir()['basedir'];
                                $upload_url             = wp_upload_dir()['baseurl'] . '/exported_html_files';

                                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 $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');
                                    }
                                    $zip_response = ($create_zip == 'created') ? $upload_url . '/' . $post_ids_str . '_html.zip' : false;
                                }

                                if ($zip_response !== false) {
                                    $html_body_args['invoiceFile'] = curl_file_create(WP_CONTENT_DIR . '/uploads/exported_html_files/' . $post_ids_str . '_html.zip', 'application/zip', $post_ids_str . '_html.zip');
                                }

                                if ($mydata_options['primer_use_api_smtp'] == 'on') {
                                    $html_post_fields['sendEmail'] = "true";
                                    $html_post_fields['email']     = $user_order_email;
                                }

                                $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"
                                        ],
                                    ),
                                );

                                $homepage          = file_get_contents($post_url, false, stream_context_create($arrContextOptions));
                                $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();
                                foreach ($data['invoice'][0]['invoiceDetails'] as $invoiceDetails) {
                                    if ($invoiceDetails['vatExemptionCategory'] != null) {
                                        $varExemptionCategory[] = $invoiceDetails['vatExemptionCategory'];
                                    }
                                }

                                $varExemptionCategory = array_unique($varExemptionCategory);
                                $varExemptionCategory = array_values($varExemptionCategory);
                                $count                = count($varExemptionCategory);
                                $is_greece            = $order->get_meta('_billing_country') == 'GR' ? true : false;

                                if ($is_greece) {
                                    if ($count > 0) {
                                        $exception_vat = '<div><span class="skin bold">ΑΠΑΛΛΑΓΗ ΑΠΟ ΤΟ Φ.Π.Α :</span></div>';
                                        for ($i = 0; $i < $count; $i++) {
                                            $exception_vat .= '<div>' . $Vat_exemption_categories[$varExemptionCategory[$i]] . '</div>';
                                        }
                                    } else {
                                        $exception_vat = '';
                                    }
                                    $modified_homepage = str_replace('<div class="cont_notation"><span class="skin bold">ΠΑΡΑΤΗΡΗΣΕΙΣ:</span>', '<div class="cont_notation">' . $exception_vat . '<span class="skin bold">ΠΑΡΑΤΗΡΗΣΕΙΣ:</span>', $modified_homepage);
                                } else {
                                    if ($count > 0) {
                                        $exception_vat = '<div><span class="skin bold">EXEMPTION FROM VAT :</span></div>';
                                        for ($i = 0; $i < $count; $i++) {
                                            $exception_vat .= '<div>' . $Vat_exemption_categories_en[$varExemptionCategory[$i]] . '</div>';
                                        }
                                    } else {
                                        $exception_vat = '';
                                    }
                                    $modified_homepage = str_replace('<div class="cont_notation"><span class="skin bold">COMMENTS:</span>', '<div class="cont_notation">' . $exception_vat . '<span class="skin bold">COMMENTS:</span>', $modified_homepage);
                                }

                                $isDeliveryNote       = $data['invoice'][0]['invoiceHeader']['isDeliveryNote'];
                                $deliveryStyle        = $isDeliveryNote ? 'height: 140px' : 'height: 120px';
                                $deliveryStyleSecond  = $isDeliveryNote ? 'height: 180px' : 'height: 160px';
                                $billing_invoice_type = $order->get_meta('_billing_invoice_type') == 'receipt' ? true : false;

                                if ($billing_invoice_type && $is_greece) {
                                    $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                    $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                } elseif ($billing_invoice_type && !$is_greece) {
                                    $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                    $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyle) . '">', $modified_homepage);
                                } elseif (!$billing_invoice_type && $is_greece) {
                                    $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                    $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                } elseif (!$billing_invoice_type && !$is_greece) {
                                    $modified_homepage = str_replace('<div class="information left">', '<div class="information left" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                    $modified_homepage = str_replace('<div class="information right">', '<div class="information right" style="' . esc_attr($deliveryStyleSecond) . '">', $modified_homepage);
                                }
                                if (!$is_greece) {
                                    $modified_homepage = str_replace('<tr><p class="table_titles">CUSTOMER INFORMATION</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles" style="white-space: nowrap; text-align: center;">CUSTOMER INFORMATION</p></td></tr><tr>', $modified_homepage);
                                    $modified_homepage = str_replace('<tr><p class="table_titles">OTHER INFORMATION</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles">OTHER INFORMATION</p></td></tr><tr>', $modified_homepage);
                                } else {
                                    $modified_homepage = str_replace('<tr><p class="table_titles">ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗ</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles" style="white-space: nowrap; text-align: center;">ΣΤΟΙΧΕΙΑ ΠΕΛΑΤΗ</p></td></tr><tr>', $modified_homepage);
                                    $modified_homepage = str_replace('<tr><p class="table_titles">ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ</p>', '<tr><td colspan="2" style="text-align: center;"><p class="table_titles">ΛΟΙΠΑ ΣΤΟΙΧΕΙΑ</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);
                                $primer_smtp_options = get_option('primer_emails');

                                $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['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';
                                }

                                $email_logs = '';

                                if (!empty($primer_automatically_send_file) && $primer_automatically_send_file === 'yes' && $user_order_email != '' && $user_order_email != null) {
                                    $primer_smtp = PrimerSMTP::get_instance();
                                    if (!empty($primer_smtp_options['email_from_name'])) {
                                        $from_name_email = $primer_smtp_options['email_from_name'];
                                    } else {
                                        $from_name_email = '';
                                    }
                                    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 (!$primer_smtp->credentials_configured()) {
                                        $email_logs .= __('Configure your SMTP credentials', 'primer') . "\n";
                                    }
                                    if (!empty($mailResultSMTP['error']) && !$primer_smtp->credentials_configured()) {
                                        $response_data .= sprintf($error_messages['error_notice_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);
                                $order->save();
                                $response_data = sprintf($error_messages['success_notice_template'], $error_messages['orders_converted']);
                            } else {
                                $mydata_options['last_request'] = $orders;
                                if (!empty($url_slug)) {
                                    $mydata_options['last_request_url'] = $url_slug;
                                }
                                update_option('primer_mydata', $mydata_options);
                                $response_data             .= is_object($response_from_array[0]->errors) ? json_encode($response_from_array[0]->errors) : $response_from_array[0]->errors;
                                $receipt_log_value_array[] = $response_data;
                                continue;
                            }
                        } else {
                            $receipt_log_value         .= $error_messages['api_not_sent'];
                            $receipt_log_value_array[] = $error_messages['api_not_sent'];
                            update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                            $inside_response_msg = $response_message ?: __('Something wrong', 'primer');
                            $response_data       .= sprintf($error_messages['error_notice_template'], $inside_response_msg . ' ' . $response_code);
                        }
                    } else {
                        $receipt_log_value         .= $error_messages['api_not_sent'];
                        $receipt_log_value_array[] = $error_messages['api_not_sent'];
                        update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                        $response_data .= sprintf($error_messages['error_notice_template'], $error_messages['api_not_sent']);
                    }

                    if (!empty($receipt_log_value_array)) {
                        update_post_meta($receipt_log_id, 'receipt_log_error', $receipt_log_value_array);
                        update_post_meta($receipt_log_id, 'receipt_log_total_status', 'only_errors');
                    }

                    if (!empty($log_ids)) {
                        foreach ($log_ids as $log_id) {
                            update_post_meta($log_id, 'receipt_log_error', $receipt_log_value_array);
                            if (!empty($receipt_log_value_array)) {
                                update_post_meta($log_id, 'receipt_log_total_status', 'only_errors');
                            }
                        }
                    }
                }

            }
        }

        wp_die();
    }

    public function primer_get_woocommerce_tax_rates() {
        global $wpdb;

        $tax_rates = array();
        $taxes     = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}woocommerce_tax_rates");

        foreach ($taxes as $tax) {
            $tax_rates[] = $tax->tax_rate;
        }

        $tax_rates_arr = array_values(array_unique($tax_rates, SORT_REGULAR));
        $response      = json_encode(array('counter' => count($tax_rates_arr)));

        die($response);
    }

    // Export
    private function get_export_config($primer_export_options) {
        $config = array(
            'client_name'                 => isset($_POST['export_select_client_name']) ? sanitize_text_field($_POST['export_select_client_name']) : ($primer_export_options['export_select_client_name'] ?? ''),
            'client_company'              => isset($_POST['export_select_client_company']) ? sanitize_text_field($_POST['export_select_client_company']) : ($primer_export_options['export_select_client_company'] ?? ''),
            'client_vat'                  => isset($_POST['export_select_client_vat']) ? sanitize_text_field($_POST['export_select_client_vat']) : ($primer_export_options['export_select_client_vat'] ?? ''),
            'client_activity'             => isset($_POST['export_select_client_activity']) ? sanitize_text_field($_POST['export_select_client_activity']) : ($primer_export_options['export_select_client_activity'] ?? ''),
            'client_address'              => isset($_POST['export_select_client_address']) ? sanitize_text_field($_POST['export_select_client_address']) : ($primer_export_options['export_select_client_address'] ?? ''),
            'client_phone'                => isset($_POST['export_select_client_phone']) ? sanitize_text_field($_POST['export_select_client_phone']) : ($primer_export_options['export_select_client_phone'] ?? ''),
            'client_email'                => isset($_POST['export_select_client_email']) ? sanitize_text_field($_POST['export_select_client_email']) : ($primer_export_options['export_select_client_email'] ?? ''),
            'client_web'                  => isset($_POST['export_select_client_webpage']) ? sanitize_text_field($_POST['export_select_client_webpage']) : ($primer_export_options['export_select_client_webpage'] ?? ''),
            'product_name'                => isset($_POST['export_select_product_name']) ? sanitize_text_field($_POST['export_select_product_name']) : ($primer_export_options['export_select_product_name'] ?? ''),
            'product_quantity'            => isset($_POST['export_select_product_quantity']) ? sanitize_text_field($_POST['export_select_product_quantity']) : ($primer_export_options['export_select_product_quantity'] ?? ''),
            'vat_amount_per_product'      => isset($_POST['export_select_vat_amount']) ? sanitize_text_field($_POST['export_select_vat_amount']) : ($primer_export_options['export_select_vat_amount'] ?? ''),
            'total_amount_per_product'    => isset($_POST['export_select_total_amount_per_product']) ? sanitize_text_field($_POST['export_select_total_amount_per_product']) : ($primer_export_options['export_select_total_amount_per_product'] ?? ''),
            'net_amount_per_product'      => isset($_POST['export_select_net_amount_per_product']) ? sanitize_text_field($_POST['export_select_net_amount_per_product']) : ($primer_export_options['export_select_net_amount_per_product'] ?? ''),
            'total_amount'                => isset($_POST['export_select_total_amount']) ? sanitize_text_field($_POST['export_select_total_amount']) : ($primer_export_options['export_select_total_amount'] ?? ''),
            'total_vat_amount'            => isset($_POST['export_select_total_vat_amount']) ? sanitize_text_field($_POST['export_select_total_vat_amount']) : ($primer_export_options['export_select_total_vat_amount'] ?? ''),
            'total_net_amount'            => isset($_POST['export_select_total_net_amount']) ? sanitize_text_field($_POST['export_select_total_net_amount']) : ($primer_export_options['export_select_total_net_amount'] ?? ''),
            'invoice_number'              => isset($_POST['export_select_invoice_number']) ? sanitize_text_field($_POST['export_select_invoice_number']) : ($primer_export_options['export_select_invoice_number'] ?? ''),
            'invoice_series_number'       => isset($_POST['export_select_invoice_series_number']) ? sanitize_text_field($_POST['export_select_invoice_series_number']) : ($primer_export_options['export_select_invoice_series_number'] ?? ''),
            'invoice_date'                => isset($_POST['export_select_invoice_date']) ? sanitize_text_field($_POST['export_select_invoice_date']) : ($primer_export_options['export_select_invoice_date'] ?? ''),
            'export_invoice_type'         => isset($_POST['export_select_invoice_type']) ? sanitize_text_field($_POST['export_select_invoice_type']) : ($primer_export_options['export_select_invoice_type'] ?? ''),
            'export_payment_method'       => isset($_POST['export_payment_method']) ? sanitize_text_field($_POST['export_payment_method']) : ($primer_export_options['export_payment_method'] ?? ''),
            'export_type'                 => isset($_POST['export_type']) ? sanitize_text_field($_POST['export_type']) : 'xlsx',
            'leave_blank_row'             => isset($_POST['export_leave_blank_row']) ? sanitize_text_field($_POST['export_leave_blank_row']) : ($primer_export_options['export_leave_blank_row'] ?? ''),
            'first_excel_column_name'     => isset($_POST['export_first_excel_column_name']) ? sanitize_text_field($_POST['export_first_excel_column_name']) : ($primer_export_options['export_first_excel_column_name'] ?? ''),
            'export_only_invoice'         => isset($_POST['export_only_invoice_details']) ? sanitize_text_field($_POST['export_only_invoice_details']) : ($primer_export_options['export_only_invoice_details'] ?? ''),
            'export_from'                 => isset($_POST['mydata_export_from']) ? sanitize_text_field($_POST['mydata_export_from']) : ($primer_export_options['mydata_export_from'] ?? ''),
            'export_to'                   => isset($_POST['mydata_export_to']) ? sanitize_text_field($_POST['mydata_export_to']) : ($primer_export_options['mydata_export_to'] ?? ''),
            'enable_schedule'             => isset($_POST['export_enable_schedule']) ? sanitize_text_field($_POST['export_enable_schedule']) : ($primer_export_options['export_enable_schedule'] ?? ''),
            'send_email'                  => isset($_POST['export_email_check']) ? sanitize_text_field($_POST['export_email_check']) : ($primer_export_options['export_email_check'] ?? ''),
            'ajax_send_email'             => isset($_POST['export_send_email']) ? sanitize_text_field($_POST['export_send_email']) : '',
            'receipt_uid'                 => isset($_POST['export_receipt_uid']) ? sanitize_text_field($_POST['export_receipt_uid']) : ($primer_export_options['export_receipt_uid'] ?? ''),
            'receipt_mark'                => isset($_POST['export_receipt_mark']) ? sanitize_text_field($_POST['export_receipt_mark']) : ($primer_export_options['export_receipt_mark'] ?? ''),
            'receipt_authentication_code' => isset($_POST['export_authentication_code']) ? sanitize_text_field($_POST['export_authentication_code']) : ($primer_export_options['export_authentication_code'] ?? ''),
        );

        return $config;
    }

    private function get_column_titles() {
        return array(
            'invoice_number'              => __('Invoice Number', 'primer'),
            'invoice_series_number'       => __('Series of the Invoice', 'primer'),
            'client_name'                 => __('Client Name', 'primer'),
            'client_vat'                  => __('Client VAT', 'primer'),
            'client_company'              => __('Client Company', 'primer'),
            'client_activity'             => __('Client Activity', 'primer'),
            'client_address'              => __('Client Address', 'primer'),
            'client_phone'                => __('Client Phone number', 'primer'),
            'client_email'                => __('Client Email', 'primer'),
            'client_web'                  => __('Client Webpage', 'primer'),
            'product_name'                => __('Product name', 'primer'),
            'product_quantity'            => __('Product Quantity', 'primer'),
            'vat_amount_per_product'      => __('VAT Amount per product', 'primer'),
            'total_amount_per_product'    => __('Total Amount per product', 'primer'),
            'net_amount_per_product'      => __('Net amount (without VAT) per product', 'primer'),
            'total_amount'                => __('Total Amount', 'primer'),
            'total_vat_amount'            => __('Total (Sum) VAT Amount', 'primer'),
            'total_net_amount'            => __('Total (Sum) Net Amount', 'primer'),
            'invoice_date'                => __('Invoice Date', 'primer'),
            'invoice_type'                => __('Invoice Type', 'primer'),
            'payment_method'              => __('Payment Method', 'primer'),
            'receipt_uid'                 => __('UID', 'primer'),
            'receipt_mark'                => __('Μ.ΑΡ.Κ.', 'primer'),
            'receipt_authentication_code' => __('AUTHENTICATION CODE', 'primer')
        );
    }

    private function get_invoice_type_label($invoice_type_slug) {
        $labels = array(
            'greek_receipt'   => __('Απόδειξη Λιανικής Πώλησης'),
            'greek_invoice'   => __('Τιμολόγιο Πώλησης'),
            'english_receipt' => __('Τιμολόγιο Πώλησης / Ενδοκοινοτικές Παραδόσεις'),
            'english_invoice' => __('Τιμολόγιο Πώλησης / Παραδόσεις Τρίτων Χωρών'),
            'credit-receipt'  => __('Πιστωτικό Στοιχείο Λιανικής'),
            'credit-invoice'  => __('Πιστωτικό Τιμολόγιο Συσχετιζόμενο'),
        );

        return $labels[$invoice_type_slug] ?? '';
    }

    private function build_receipt_query_args($export_config) {
        $mydata_options = get_option('primer_mydata');
        $search_api     = $mydata_options['mydata_api'] == 'production_api' ? 'production' : 'test';

        $receipt_args = array(
            'posts_per_page' => -1,
            'post_type'      => 'primer_receipt',
            'post_status'    => 'publish',
            'order'          => 'DESC',
            'meta_query'     => array(
                'relation' => 'AND',
                array(
                    'key'   => 'send_to_api_type',
                    'value' => $search_api
                ),
                array(
                    'key'   => 'receipt_status',
                    'value' => 'issued'
                )
            )
        );

        if (!empty($export_config['export_from']) && !empty($export_config['export_to'])) {
            $receipt_args['date_query'] = array(
                array(
                    'after'     => array(
                        'year'  => date('Y', strtotime($export_config['export_from'])),
                        'month' => date('m', strtotime($export_config['export_from'])),
                        'day'   => date('d', strtotime($export_config['export_from'])),
                    ),
                    'before'    => array(
                        'year'  => date('Y', strtotime($export_config['export_to'])),
                        'month' => date('m', strtotime($export_config['export_to'])),
                        'day'   => date('d', strtotime($export_config['export_to'])),
                    ),
                    'inclusive' => true,
                    'column'    => 'post_date',
                )
            );
        } elseif (!empty($export_config['export_to'])) {
            $receipt_args['date_query'] = array(
                array(
                    'before'    => array(
                        'year'  => date('Y', strtotime($export_config['export_to'])),
                        'month' => date('m', strtotime($export_config['export_to'])),
                        'day'   => date('d', strtotime($export_config['export_to'])),
                    ),
                    'inclusive' => true,
                    'column'    => 'post_date',
                )
            );
        } elseif (!empty($export_config['export_from'])) {
            $receipt_args['date_query'] = array(
                array(
                    'after'     => array(
                        'year'  => date('Y', strtotime($export_config['export_from'])),
                        'month' => date('m', strtotime($export_config['export_from'])),
                        'day'   => date('d', strtotime($export_config['export_from'])),
                    ),
                    'inclusive' => true,
                    'column'    => 'post_date',
                )
            );
        }

        return $receipt_args;
    }

    private function get_tax_rates_array($wpdb) {
        $taxes     = $wpdb->get_results("SELECT DISTINCT tax_rate FROM {$wpdb->prefix}woocommerce_tax_rates");
        $tax_rates = array_map(function($tax) {
            return $tax->tax_rate;
        }, $taxes);

        return array_values(array_unique($tax_rates, SORT_REGULAR));
    }

    private function collect_invoice_row_data($receipt_id, $total_order, $count_product, $export_config, $tax_rates_arr, $receipt_count) {
        $row_data = array();

        $is_credit_receipt  = get_post_meta($receipt_id, 'credit_receipt', true);
        $log_for_order      = get_post_meta($receipt_id, $is_credit_receipt ? 'credit_log_id_for_order' : 'log_id_for_order', true);
        $json_send_to_api   = get_post_meta($log_for_order, 'json_send_to_api', true);
        $json_send_to_api   = json_decode($json_send_to_api, true);

        $user_display_name = get_post_meta($receipt_id, 'receipt_client_id', true);
        $user_data         = get_user_by('ID', $user_display_name);
        $invoice_type      = get_the_terms($receipt_id, 'receipt_status');
        $invoice_type_slug = !empty($invoice_type) ? $invoice_type[0]->slug : '';

        $row_data['user_first_name']       = $total_order->get_billing_first_name();
        $row_data['user_last_name']        = $total_order->get_billing_last_name();
        $row_data['client_email']          = $total_order->get_billing_email();
        $row_data['client_address']        = $total_order->get_billing_address_1() . $total_order->get_billing_address_2();
        $row_data['client_phone']          = $total_order->get_billing_phone();
        $row_data['client_vat']            = $total_order->get_meta('_billing_vat');
        $row_data['client_company']        = $total_order->get_meta('_billing_company');
        $row_data['client_activity']       = $total_order->get_meta('_billing_store');
        $row_data['client_web']            = $user_data->user_url ?? '';
        $row_data['invoice_type_slug']     = $invoice_type_slug;
        $row_data['invoice_type_value']    = $this->get_invoice_type_label($invoice_type_slug);
        $row_data['receipt_number']        = get_post_meta($receipt_id, '_primer_receipt_number', true);
        $row_data['receipt_series_number'] = get_post_meta($receipt_id, '_primer_receipt_series', true);

        $receipt_date = get_post_meta($receipt_id, 'success_mydata_date', true);
        $receipt_time = get_post_meta($receipt_id, 'success_mydata_time', true);

        if (empty($receipt_date)) {
            $receipt_date = get_the_date('d/m/Y', $receipt_id);
        }

        if (empty($receipt_time)) {
            $receipt_time = get_the_date('H:i', $receipt_id);
        }

        $row_data['invoice_date'] = "$receipt_date $receipt_time";

        $row_data['products']       = $this->collect_product_data_from_json($json_send_to_api, $invoice_type_slug, $count_product, $export_config);
        $row_data['totals']         = $this->collect_totals_data_from_json($json_send_to_api, $invoice_type_slug, $count_product, $export_config);

        $row_data['payment_method'] = $total_order->get_payment_method_title();

        $row_data['receipt_uid']                 = get_post_meta($receipt_id, 'response_invoice_uid', true);
        $row_data['receipt_mark']                = get_post_meta($receipt_id, 'response_invoice_mark', true);
        $row_data['receipt_authentication_code'] = get_post_meta($receipt_id, 'response_invoice_authcode', true);

        if (!empty($export_config['vat_rate_column'])) {
            $row_data['vat_rates'] = $this->collect_vat_rates_data($total_order, $tax_rates_arr, $receipt_count, $count_product);
        }

        return $row_data;
    }

    private function collect_product_data_from_json($json_send_to_api, $invoice_type_slug, $count_product, $export_config) {
        $products = array(
            'names'         => array(),
            'quantities'    => array(),
            'vat_amounts'   => array(),
            'total_amounts' => array(),
            'net_amounts'   => array(),
        );

        $is_credit  = in_array($invoice_type_slug, array(
            'credit-receipt',
            'credit-invoice'
        ));
        $multiplier = $is_credit ? -1 : 1;

        $invoice_details = $json_send_to_api['invoice'][0]['invoiceDetails'] ?? [];

        foreach ($invoice_details as $detail) {
            $products['names'][]      = $detail['name'] ?? '';
            $products['quantities'][] = ($detail['quantity'] ?? 1) * $multiplier;

            $tax_amount   = $multiplier * floatval($detail['vatAmount'] ?? 0);
            $net_amount   = $multiplier * floatval($detail['netValue'] ?? 0);
            $total_amount = $net_amount + $tax_amount;

            $products['vat_amounts'][]   = number_format($tax_amount, 2);
            $products['total_amounts'][] = number_format($total_amount, 2);
            $products['net_amounts'][]   = number_format($net_amount, 2);
        }

        if (!empty($export_config['leave_blank_row'])) {
            $products['names'][]         = '';
            $products['quantities'][]    = '';
            $products['vat_amounts'][]   = '';
            $products['total_amounts'][] = '';
            $products['net_amounts'][]   = '';
        }

        return $products;
    }

    private function collect_totals_data_from_json($json_send_to_api, $invoice_type_slug, $count_product, $export_config) {
        $is_credit  = in_array($invoice_type_slug, [
            'credit-receipt',
            'credit-invoice'
        ]);

        $multiplier = $is_credit ? -1 : 1;

        $invoice_summary = $json_send_to_api['invoice'][0]['invoiceSummary'] ?? [];

        $total_tax      = floatval($invoice_summary['totalVatAmount'] ?? 0);
        $total          = floatval($invoice_summary['totalGrossValue'] ?? 0);
        $net_total      = floatval($invoice_summary['totalNetValue'] ?? 0);

        $formatted_vat    = number_format($multiplier * $total_tax, 2, '.', '');
        $formatted_amount = number_format($multiplier * $total, 2, '.', '');
        $formatted_net    = number_format($multiplier * $net_total, 2, '.', '');

        $totals = [
            'vat'    => array_fill(0, max(1, $count_product), $formatted_vat),
            'amount' => array_fill(0, max(1, $count_product), $formatted_amount),
            'net'    => array_fill(0, max(1, $count_product), $formatted_net),
        ];

        if (!empty($export_config['leave_blank_row'])) {
            array_push($totals['vat'], '');
            array_push($totals['amount'], '');
            array_push($totals['net'], '');
        }

        return $totals;

    }

    private function collect_vat_rates_data($total_order, $tax_rates_arr, $receipt_count, $count_product) {
        $vat_rates              = array();
        $order_customer_country = $total_order->get_billing_country();

        foreach ($total_order->get_items('tax') as $item) {
            $tax_rate_id = $item->get_rate_id();
            $tax_percent = WC_Tax::get_rate_percent($tax_rate_id);
            $tax_total   = $item->get_tax_total();

            $vat_rates[$tax_percent] = array(
                'rate_id'  => $tax_rate_id,
                'total'    => number_format((float) $tax_total, 2),
                'position' => $receipt_count,
            );
        }

        return $vat_rates;
    }

    public function export_invoice_to_report() {
        global $wpdb;

        $primer_export_options = get_option('primer_export');
        $export_config         = $this->get_export_config($primer_export_options);
        $receipt_args          = $this->build_receipt_query_args($export_config);

        $upload_dir = wp_upload_dir()['basedir'];
        if (!file_exists($upload_dir . '/primer-export-invoices')) {
            mkdir($upload_dir . '/primer-export-invoices');
        }

        $receipt_query = new WP_Query($receipt_args);
        $tax_rates_arr = $this->get_tax_rates_array($wpdb);

        $grouped_receipts = [];

        if ($receipt_query->have_posts()) {
            while ($receipt_query->have_posts()) {
                $receipt_query->the_post();

                $receipt_id = get_the_ID();
                if ($receipt_id == null) {
                    continue;
                }

                $order_id = get_post_meta($receipt_id, 'order_id_to_receipt', true);

                if (empty($order_id)) {
                    continue;
                }

                $total_order = wc_get_order($order_id);

                if (empty($total_order)) {
                    continue;
                }

                $transmission_failure_check = $total_order->get_meta('transmission_failure_check');

                $grouped_receipts[$order_id][] = [
                    'receipt_id'                 => $receipt_id,
                    'total_order'                => $total_order,
                    'transmission_failure_check' => $transmission_failure_check,
                    'product_name_fields'        => get_post_meta($receipt_id, 'receipt_product', false),
                ];
            }
            wp_reset_postdata();
        }

        $invoice_args  = array();
        $receipt_count = 0;

        foreach ($grouped_receipts as $order_id => $receipts_list) {
            $receipts_to_export = [];
            foreach ($receipts_list as $data) {
                if (in_array($data['transmission_failure_check'], ['1', '3'])) {
                    $receipts_to_export[] = $data;
                }
            }
            if (empty($receipts_to_export)) {
                foreach ($receipts_list as $data) {
                    if ($data['transmission_failure_check'] == '2' ||
                        get_post_meta($data['receipt_id'], 'credit_receipt', true) == 'yes') {
                        $receipts_to_export[] = $data;
                    }
                }
            }

            foreach ($receipts_to_export as $data) {
                $receipt_id          = $data['receipt_id'];
                $total_order         = $data['total_order'];
                $product_name_fields = $data['product_name_fields'];

                $count_product = $export_config['export_only_invoice'] == 'on' ? 1 : count($product_name_fields);
                $row_data      = $this->collect_invoice_row_data($receipt_id, $total_order, $count_product, $export_config, $tax_rates_arr, $receipt_count);

                $this->add_row_to_invoice_args($invoice_args, $row_data, $export_config);

                $receipt_count++;
            }
        }

        ksort($invoice_args, SORT_NUMERIC);

        $this->export_invoice_files($invoice_args, $export_config['export_type'], $export_config['leave_blank_row'], $export_config['first_excel_column_name'], $export_config['send_email'], $export_config['ajax_send_email']);
    }

    private function is_product_export_enabled($export_config) {
        return (
            !empty($export_config['product_name']) ||
            !empty($export_config['product_quantity']) ||
            !empty($export_config['vat_amount_per_product']) ||
            !empty($export_config['total_amount_per_product']) ||
            !empty($export_config['net_amount_per_product'])
        );
    }

    private function add_row_to_invoice_args(&$invoice_args, $row_data, $export_config) {
        $titles = $this->get_column_titles();

        $is_product_export_enabled = $this->is_product_export_enabled($export_config);
        if ($is_product_export_enabled) {
            $number_of_rows = count($row_data['products']['names']);
        } else {
            $number_of_rows = 1;
            if (count($row_data['products']['names']) === 0) {
                $number_of_rows = 0;
            }
        }

        if ($number_of_rows === 0) {
            return;
        }

        $has_blank_row_option            = !empty($export_config['leave_blank_row']);
        $should_blank_last_row_in_helper = $is_product_export_enabled && $has_blank_row_option;

        $fill_and_append_repeat = function($col_key, $col_title, $value) use (&$invoice_args, $number_of_rows, $should_blank_last_row_in_helper) {
            if (isset($col_key) && !empty($col_key)) {
                $column_data = array_fill(0, $number_of_rows, $value);
                if ($should_blank_last_row_in_helper) {
                    $column_data[$number_of_rows - 1] = '';
                }
                if (!isset($invoice_args[$col_key][$col_title])) {
                    $invoice_args[$col_key][$col_title] = [];
                }
                $invoice_args[$col_key][$col_title] = array_merge($invoice_args[$col_key][$col_title], $column_data);
            }
        };

        $fill_and_append_only_once = function($col_key, $col_title, $value) use (&$invoice_args, $number_of_rows) {
            if (isset($col_key) && !empty($col_key)) {
                $column_data    = array_fill(0, $number_of_rows, '');
                $column_data[0] = $value;
                if (!isset($invoice_args[$col_key][$col_title])) {
                    $invoice_args[$col_key][$col_title] = [];
                }
                $invoice_args[$col_key][$col_title] = array_merge($invoice_args[$col_key][$col_title], $column_data);
            }
        };

        if ($is_product_export_enabled && isset($row_data['products'])) {
            foreach ($row_data['products']['names'] as $product_index => $product_name) {
                if (isset($export_config['product_name']) && !empty($export_config['product_name'])) {
                    $col_key   = $export_config['product_name'];
                    $col_title = $titles['product_name'];
                    if (!isset($invoice_args[$col_key][$col_title])) $invoice_args[$col_key][$col_title] = [];
                    $invoice_args[$col_key][$col_title][] = $product_name ?? '';
                }

                if (isset($export_config['product_quantity']) && !empty($export_config['product_quantity'])) {
                    $col_key   = $export_config['product_quantity'];
                    $col_title = $titles['product_quantity'];
                    if (!isset($invoice_args[$col_key][$col_title])) $invoice_args[$col_key][$col_title] = [];
                    $invoice_args[$col_key][$col_title][] = $row_data['products']['quantities'][$product_index] ?? '';
                }

                if (isset($export_config['vat_amount_per_product']) && !empty($export_config['vat_amount_per_product'])) {
                    $col_key   = $export_config['vat_amount_per_product'];
                    $col_title = $titles['vat_amount_per_product'];
                    if (!isset($invoice_args[$col_key][$col_title])) $invoice_args[$col_key][$col_title] = [];
                    $invoice_args[$col_key][$col_title][] = $row_data['products']['vat_amounts'][$product_index] ?? '';
                }

                if (isset($export_config['total_amount_per_product']) && !empty($export_config['total_amount_per_product'])) {
                    $col_key   = $export_config['total_amount_per_product'];
                    $col_title = $titles['total_amount_per_product'];
                    if (!isset($invoice_args[$col_key][$col_title])) $invoice_args[$col_key][$col_title] = [];
                    $invoice_args[$col_key][$col_title][] = $row_data['products']['total_amounts'][$product_index] ?? '';
                }

                if (isset($export_config['net_amount_per_product']) && !empty($export_config['net_amount_per_product'])) {
                    $col_key   = $export_config['net_amount_per_product'];
                    $col_title = $titles['net_amount_per_product'];
                    if (!isset($invoice_args[$col_key][$col_title])) $invoice_args[$col_key][$col_title] = [];
                    $invoice_args[$col_key][$col_title][] = $row_data['products']['net_amounts'][$product_index] ?? '';
                }
            }
        }

        $client_name           = $row_data['user_first_name'] . ' ' . $row_data['user_last_name'];
        $client_activity_value = in_array($row_data['invoice_type_slug'], ['greek_invoice', 'english_invoice', 'credit-invoice']) ? ($row_data['client_activity'] ?? '') : '';

        $fill_and_append_only_once($export_config['client_name'], $titles['client_name'], $client_name);
        $fill_and_append_only_once($export_config['client_vat'], $titles['client_vat'], $row_data['client_vat'] ?? '');
        $fill_and_append_only_once($export_config['client_company'], $titles['client_company'], $row_data['client_company'] ?? '');
        $fill_and_append_only_once($export_config['client_activity'], $titles['client_activity'], $client_activity_value);
        $fill_and_append_only_once($export_config['client_address'], $titles['client_address'], $row_data['client_address'] ?? '');
        $fill_and_append_only_once($export_config['client_phone'], $titles['client_phone'], $row_data['client_phone'] ?? '');
        $fill_and_append_only_once($export_config['client_email'], $titles['client_email'], $row_data['client_email'] ?? '');
        $fill_and_append_only_once($export_config['client_web'], $titles['client_web'], $row_data['client_web'] ?? '');
        $fill_and_append_only_once($export_config['invoice_date'], $titles['invoice_date'], $row_data['invoice_date'] ?? '');
        $fill_and_append_only_once($export_config['export_invoice_type'], $titles['invoice_type'], $row_data['invoice_type_value'] ?? '');
        $fill_and_append_only_once($export_config['export_payment_method'], $titles['payment_method'], $row_data['payment_method'] ?? '');
        $fill_and_append_only_once($export_config['receipt_uid'], $titles['receipt_uid'], $row_data['receipt_uid'] ?? '');
        $fill_and_append_only_once($export_config['receipt_mark'], $titles['receipt_mark'], $row_data['receipt_mark'] ?? '');
        $fill_and_append_only_once($export_config['receipt_authentication_code'], $titles['receipt_authentication_code'], $row_data['receipt_authentication_code'] ?? '');
        $fill_and_append_only_once($export_config['total_amount'], $titles['total_amount'], $row_data['totals']['amount'][0] ?? '');
        $fill_and_append_only_once($export_config['total_vat_amount'], $titles['total_vat_amount'], $row_data['totals']['vat'][0] ?? '');
        $fill_and_append_only_once($export_config['total_net_amount'], $titles['total_net_amount'], $row_data['totals']['net'][0] ?? '');

        $fill_and_append_repeat($export_config['invoice_number'], $titles['invoice_number'], $row_data['receipt_number'] ?? '');
        $fill_and_append_repeat($export_config['invoice_series_number'], $titles['invoice_series_number'], $row_data['receipt_series_number'] ?? '');

        if (!$is_product_export_enabled && $has_blank_row_option) {
            foreach ($invoice_args as $col_key => $data) {
                foreach ($data as $col_title => $vals) {
                    $invoice_args[$col_key][$col_title][] = '';
                }
            }
        }

    }

    private function build_header_row($invoice_args) {
        $header_row = array();

        foreach ($invoice_args as $col_letter => $data) {
            if (is_array($data) && !empty($data)) {
                $header_row[$col_letter] = key($data);
            }
        }

        ksort($header_row, SORT_STRING);

        return apply_filters('primer_export_csv_headers', $header_row);
    }

    private function build_data_rows($invoice_args) {
        $data_rows = array();

        $num_rows = 0;
        foreach ($invoice_args as $data) {
            if (is_array($data) && !empty($data)) {
                $num_rows = count(reset($data));
                break;
            }
        }

        if ($num_rows > 0) {
            for ($i = 0; $i < $num_rows; $i++) {
                $row = array();
                foreach ($invoice_args as $col_letter => $data) {
                    if (is_array($data) && !empty($data)) {
                        $column_data = reset($data);
                        $row[$col_letter] = $column_data[$i] ?? '';
                    }
                }
                $data_rows[] = $row;
            }
        }

        return apply_filters('primer_export_csv_data', $data_rows);
    }

    public function export_invoice_files($invoice_args, $export_type, $primer_leave_blank_row, $primer_first_excel_column_name, $export_send_email, $ajax_send_email) {
        $primer_export_data = get_option('primer_export');

        $export_config      = array(
            'type'                    => $export_type,
            'leave_blank_row'         => isset($primer_export_data['export_leave_blank_row']) ? $primer_export_data['export_leave_blank_row'] : $primer_leave_blank_row,
            'first_excel_column_name' => isset($primer_export_data['export_first_excel_column_name']) ? $primer_export_data['export_first_excel_column_name'] : $primer_first_excel_column_name,
            'export_totals_row'       => isset($primer_export_data['export_row_totals']) ? sanitize_text_field($primer_export_data['export_row_totals']) : '',
            'send_email'              => isset($primer_export_data['export_email_check']) ? $primer_export_data['export_email_check'] : $export_send_email,
        );

        $header_row = $this->build_header_row($invoice_args);
        $data_rows  = $this->build_data_rows($invoice_args);
        $filename   = $this->generate_export_filename($export_config['type']);
        $file_path  = $this->get_export_file_path($filename);

        if ($export_config['type'] == 'csv') {
            $this->export_to_csv($file_path, $header_row, $data_rows, $export_config);
        } else {
            $this->export_to_xlsx($file_path, $header_row, $data_rows, $export_config);
        }

        $response = $this->send_export_response($file_path, $filename, $export_config, $primer_export_data);

        wp_die($response);
    }

    private function export_to_xlsx($file_path, $header_row, $data_rows, $export_config) {
        $spreadsheet = new Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        $row_index   = 1;

        if (!empty($export_config['first_excel_column_name'])) {
            foreach ($header_row as $col_letter => $col_title) {
                $cell = $col_letter . '1';
                $sheet->setCellValue($cell, $col_title);
                $header_style = $sheet->getStyle($cell);
                $header_style->getFont()->setBold(true);
                $header_style->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFC1E1C1');
            }
            $sheet->freezePane('A2');
            $row_index = 2;
        }

        foreach ($data_rows as $data_items) {

            $is_empty_row = isset($data_items['is_empty_row']) && $data_items['is_empty_row'] === true;

            foreach ($header_row as $col_letter => $col_title) {
                $cell = $col_letter . $row_index;
                if ($is_empty_row) {
                    $sheet->setCellValue($cell, '');
                    continue;
                }

                $value = $data_items[$col_letter] ?? '';

                if (in_array($col_title, ['Τελική Αξία παραγγελίας', 'Τελική Αξία προϊόντος',
                                          'Καθαρή Αξία προϊόντος', 'Αξία Φ.Π.Α. προϊόντος',
                                          'Αξία Φ.Π.Α. παραγγελίας', 'Καθαρή Αξία παραγγελίας',
                                          'Ποσότητα Προϊόντος',
                                          'Total Amount per product', 'Net amount (without VAT) per product',
                                          'VAT Amount per product', 'Total Amount',
                                          'Total (Sum) VAT Amount', 'Total (Sum) Net Amount', 'Product Quantity'])) {

                    $cleaned_value = str_replace(',', '', $value);
                    $numeric_value = is_numeric($cleaned_value) ? (float)$cleaned_value : 0.0;

                    if ($value === '' || $value === null || $numeric_value === 0.0) {
                        $sheet->setCellValue($cell, ' ');
                    } else {
                        $sheet->setCellValue($cell, $numeric_value, DataType::TYPE_NUMERIC);
                        $sheet->getStyle($cell)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
                    }
                } else {
                    $sheet->setCellValueExplicit($cell, (string)$value, DataType::TYPE_STRING);
                }
            }
            $row_index++;
        }

        if ($export_config['export_totals_row'] == 'on') {
            $this->add_totals_row($sheet, $header_row, $row_index, $export_config);
        }

        $writer = new Xlsx($spreadsheet);
        $writer->save($file_path);
    }

    private function add_totals_row($sheet, $header_row, $row_index, $export_config) {
        $sheet->setCellValue('A' . $row_index, 'ΣΥΝΟΛΑ');

        $header_style = $sheet->getStyle('A' . $row_index);
        $header_style->getFont()->setBold(true);
        $header_style->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFC1E1C1');

        $sum_columns = [
            'Τελική Αξία προϊόντος', 'Total Amount per product',
            'Καθαρή Αξία προϊόντος', 'Net amount (without VAT) per product',
            'Αξία Φ.Π.Α. προϊόντος', 'VAT Amount per product',
            'Ποσότητα Προϊόντος', 'Product Quantity',
            'Total Amount', 'Τελική Αξία παραγγελίας',
            'Total (Sum) VAT Amount', 'Αξία Φ.Π.Α. παραγγελίας',
            'Total (Sum) Net Amount', 'Καθαρή Αξία παραγγελίας'
        ];

        $last_data_row = $row_index - 1;
        $first_data_row = !empty($export_config['first_excel_column_name']) ? 2 : 1;

        $column_letters = array_keys($header_row);
        $last_column = end($column_letters);

        if ($last_column) {
            $sheet->getStyle('A' . $row_index . ':' . $last_column . $row_index)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FFC1E1C1');
        }

        foreach ($header_row as $col_letter => $col_title) {
            $cell = $col_letter . $row_index;

            if (in_array($col_title, $sum_columns)) {
                $formula = '=SUM(' . $col_letter . $first_data_row . ':' . $col_letter . $last_data_row . ')';
                $sheet->setCellValue($cell, $formula);
                $sheet->getStyle($cell)->getFont()->setBold(true);
            } else {
                if ($col_letter !== 'A' || $col_title !== reset($header_row)) {
                    $sheet->setCellValue($cell, '');
                }
            }
        }
    }

    private function send_export_response($file_path, $filename, $export_config, $primer_export_data) {
        $upload_dir = wp_upload_dir();
        $file_url   = $upload_dir['baseurl'] . '/primer-export-invoices/' . $filename;

        $response = json_encode(array(
            'file'      => $file_url,
            'file_name' => $filename
        ));

        if (!empty($export_config['send_email'])) {
            $this->send_export_email($file_path, $filename, $primer_export_data);
        }

        return $response;
    }

    private function send_export_email($file_path, $filename, $primer_export_data) {
        $export_admin_emails = $primer_export_data['export_send_email'] ?? '';

        if (empty($export_admin_emails)) {
            return;
        }

        $admin_emails = array_map('trim', array_map('sanitize_email', explode(',', $export_admin_emails)));
        $admin_emails = array_filter($admin_emails);

        if (empty($admin_emails)) {
            return;
        }

        $primer_smtp         = PrimerSMTP::get_instance();
        $primer_smtp_options = get_option('primer_emails');
        $smtp_type           = $primer_smtp_options['smtp_type'] ?? 'wordpress_default';
        $subject             = __('Primer Software, your export file.', 'primer');
        $message             = __('Hello, your export file is ready.', 'primer');

        foreach ($admin_emails as $to_email) {
            if ($smtp_type == 'wordpress_default') {
                wp_mail($to_email, $subject, $message, '', $file_path);
            } else {
                $from_name = $primer_smtp_options['email_from_name'] ?? '';
                $primer_smtp->primer_mail_sender($to_email, $from_name, $subject, $message, $file_path);
            }
        }
    }

    private function generate_export_filename($export_type) {
        $extension = ($export_type == 'csv') ? 'csv' : 'xlsx';

        return sanitize_file_name($export_type . '-export-' . date('Y-m-d H-i') . '.' . $extension);
    }

    private function get_export_file_path($filename) {
        $upload_dir = wp_upload_dir()['basedir'];
        $export_dir = $upload_dir . '/primer-export-invoices';

        if (!file_exists($export_dir)) {
            mkdir($export_dir, 0755, true);
        }

        return $export_dir . '/' . $filename;
    }

    private function export_to_csv($file_path, $header_row, $data_rows, $export_config) {
        $delimiter = ';';
        $fh = @fopen($file_path, 'w');
        fprintf($fh, chr(0xEF) . chr(0xBB) . chr(0xBF));

        if (!empty($export_config['first_excel_column_name'])) {
            fputcsv($fh, $header_row, $delimiter);
        }
        foreach ($data_rows as $data_items) {
            $row_to_write = [];
            $is_empty_row = isset($data_items['is_empty_row']) && $data_items['is_empty_row'] === true;
            foreach ($header_row as $col_letter => $col_title) {
                $value = $data_items[$col_letter] ?? '';
                if ($is_empty_row) {
                    $row_to_write[] = '';
                    continue;
                }
                if (in_array($col_title, ['Τελική Αξία προϊόντος', 'Total Amount per product', 'Καθαρή Αξία προϊόντος',
                                          'Net amount (without VAT) per product', 'Αξία Φ.Π.Α. προϊόντος', 'VAT Amount per product',
                                          'Total Amount', 'Total (Sum) VAT Amount', 'Total (Sum) Net Amount'])) {
                    if ($value === '' || $value === null || $value === 0 || $value === '0') {
                        $row_to_write[] = '';
                    } else {
                        $formatted_value = str_replace('.', ',', $value);
                        $row_to_write[] = $formatted_value;
                    }
                } else {
                    $row_to_write[] = $value;
                }
            }
            fputcsv($fh, $row_to_write, $delimiter);
        }
        fclose($fh);
    }


    public function set_csv_headers($filename) {
        $now = date("D, d M Y H:i:s");
        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
        header("Last-Modified: {$now} GMT");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Disposition: attachment;filename={$filename}");
        header("Content-Transfer-Encoding: binary");
    }

    public function set_excel_headers($filename) {
        $now = date("D, d M Y H:i:s");
        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Content-Transfer-Encoding: binary");
    }

    public function export_csv_log($log_ids, $log_successful, $log_failed) {
        global $wpdb;

        $post_type   = 'pr_log_automation';
        $type        = 'automation_log';
        $meta_values = $header_row = $data_rows = array();

        $args = array(
            'post_type'      => $post_type,
            'posts_per_page' => -1,
            'post_status'    => 'publish',
            'inclusive'      => true,
        );

        if (!empty($log_ids)) {
            $args['post__in'] = $log_ids;
        }

        if (!empty($log_successful)) {
            $meta_values['receipt_log_automation_total_status'][] = 'only_issued';
        }

        if (!empty($log_failed)) {
            $meta_values['receipt_log_automation_total_status'][] = 'only_errors';
        }

        if (!empty($meta_values)) {
            $args['meta_query']['relation'] = 'AND';
            $i                              = 0;
            foreach ($meta_values as $key => $meta_value) {
                $i++;
                $args['meta_query'][$i]['key']   = $key;
                $args['meta_query'][$i]['value'] = $meta_value;
            }
        }

        $the_query = new WP_Query($args);

        if ($the_query->have_posts()) :
            $postmeta_headers = array();
            while ($the_query->have_posts()) : $the_query->the_post();
                $id         = get_the_ID();
                $post_metas = get_post_meta($id, '', true);
            endwhile;

            $header_row = array(
                0 => __('Order No', 'primer'),
                1 => __('Order Date', 'primer'),
                2 => __('Invoice No', 'primer'),
                3 => __('Invoice Date', 'primer'),
                4 => __('Client', 'primer'),
                5 => __('Issued receipt', 'primer'),
                6 => __('Email send', 'primer'),
                7 => __('Receipt Error', 'primer'),
                8 => __('Email Error', 'primer'),
            );

            $columns = count($header_row);

            rewind_posts();

            $check_id = array();

            while ($the_query->have_posts()) : $the_query->the_post();
                $order_id               = get_post_meta(get_the_ID(), 'receipt_log_automation_order_id', true);
                $order_date             = get_post_meta(get_the_ID(), 'receipt_log_automation_order_date', true);
                $log_order_id           = get_post_meta(get_the_ID(), 'receipt_log_automation_order_id', true);
                $receipt_log_invoice_id = get_post_meta(get_the_ID(), 'receipt_log_invoice_id', true);

                if (get_post_meta($receipt_log_invoice_id, '_primer_receipt_series', true) == "EMPTY") {
                    $invoice_no = get_post_meta($receipt_log_invoice_id, '_primer_receipt_number', true);
                } else {
                    $invoice_no = get_post_meta($receipt_log_invoice_id, '_primer_receipt_series', true) . " " . get_post_meta($receipt_log_invoice_id, '_primer_receipt_number', true);
                }

                $invoice_log_id    = $invoice_no;
                $invoice_log_date  = get_post_meta(get_the_ID(), 'receipt_log_automation_invoice_date', true);
                $meta_key          = 'order_id_to_receipt';
                $get_invoice_by_id = $wpdb->get_col($wpdb->prepare("
					SELECT key1.post_id
					FROM $wpdb->postmeta key1
					WHERE key1.meta_key = %s AND key1.meta_value = '$log_order_id'", $meta_key));

                if (empty($invoice_log_id)) {
                    if (!empty($get_invoice_by_id)) {
                        $invoice_log_id = $get_invoice_by_id[0];
                    }
                }

                if (empty($invoice_log_date)) {
                    if (!empty($get_invoice_by_id)) {
                        $invoice_log_date = get_the_date('F j, Y', $get_invoice_by_id[0]);
                    }
                }

                $order_from_invoice_log = get_post_meta(get_the_ID(), 'receipt_log_automation_order_id', true);
                $invoice_log_client     = get_post_meta(get_the_ID(), 'receipt_log_automation_client', true);
                $order                  = wc_get_order($order_from_invoice_log);

                if (is_a($order, 'WC_Order_Refund')) {
                    $order = wc_get_order($order->get_parent_id());
                }

                if (!empty($order->get_billing_first_name())) {
                    $user_first_name = $order->get_billing_first_name();
                    $user_last_name  = $order->get_billing_last_name();
                    $user_full_name  = $user_first_name . ' ' . $user_last_name;
                } elseif (!empty($order->get_billing_company())) {
                    $user_full_name = $order->get_billing_company();
                } else {
                    $user_full_name = 'RETAIL CLIENT';
                }

                if (empty($invoice_log_client)) {
                    $invoice_log_client = $user_full_name;
                }

                $receipt_log_status = get_post_meta(get_the_ID(), 'receipt_log_automation_status', true);

                switch ($receipt_log_status) {
                    case 'issued':
                        $receipt_log_status_text = 'Yes';
                        break;
                    default:
                        $receipt_log_status_text = 'No';
                        break;
                }

                $receipt_log_email_status = get_post_meta(get_the_ID(), 'receipt_log_automation_email', true);

                switch ($receipt_log_email_status) {
                    case 'sent':
                        $receipt_log_email_status_text = 'Yes';
                        break;
                    default:
                        $receipt_log_email_status_text = 'No';
                        break;
                }

                $receipt_log_error = json_encode(get_post_meta(get_the_ID(), 'receipt_log_automation_error', true));

                if ($receipt_log_error == "\"\"") {
                    $receipt_log_error = "Successful";
                }

                $receipt_log_email_error = get_post_meta(get_the_ID(), 'receipt_log_automation_email_error', true);

                if ($receipt_log_error != "Successful") {
                    $receipt_log_email_error = "Receipt error";
                }

                $row = array();
                $row[0]      = $order_id;
                $row[1]      = $order_date;
                $row[2]      = $invoice_log_id;
                $row[3]      = $invoice_log_date;
                $row[4]      = $invoice_log_client;
                $row[5]      = $receipt_log_status_text;
                $row[6]      = $receipt_log_email_status_text;
                $row[7]      = $receipt_log_error;
                $row[8]      = $receipt_log_email_error;
                $row         = apply_filters('primer_export_csv_row', $row, get_the_ID(), $header_row);
                $data_rows[] = $row;
            endwhile;
        endif;

        $header_row = apply_filters('primer_export_csv_headers', $header_row);
        $data_rows  = apply_filters('primer_export_csv_data', $data_rows);
        $filename   = sanitize_file_name($type . '-export-' . date('Y-m-d H-i') . '.csv');
        $this->set_csv_headers($filename);
        $upload_dir = wp_upload_dir()['basedir'];

        if (!file_exists($upload_dir . '/primer-automation-logs')) {
            mkdir($upload_dir . '/primer-automation-logs');
        }

        $csv_dir_file = $upload_dir . '/primer-automation-logs/' . $filename;

        $fh = @fopen("$csv_dir_file", 'w');
        fprintf($fh, chr(0xEF) . chr(0xBB) . chr(0xBF));
        fputcsv($fh, $header_row);

        foreach ($data_rows as $data_row) {
            fputcsv($fh, $data_row);
        }

        fclose($fh);

        $automation_options    = get_option('primer_automation');
        $activation_automation = $automation_options['activation_automation'];

        $primer_smtp = PrimerSMTP::get_instance();

        if (!empty($automation_options['email_subject'])) {
            $primer_smtp_subject = $automation_options['email_subject'];
        } else {
            $primer_smtp_subject = __('Test email subject', 'primer');
        }

        $primer_send_success_log = $primer_send_fail_log = '';

        if (!empty($automation_options['send_successful_log'])) {
            $primer_send_success_log = $automation_options['send_successful_log'];
        }

        if (!empty($automation_options['send_failed_log'])) {
            $primer_send_fail_log = $automation_options['send_failed_log'];
        }

        if (!empty($activation_automation)) {
            if (!empty($primer_send_success_log) || !empty($primer_send_fail_log)) {
                if (($primer_send_success_log == 'on') || ($primer_send_fail_log == 'on')) {
                    $automation_admin_emails = $automation_options['admin_email'];
                    if (!empty($automation_admin_emails)) {
                        $admin_emails = explode(',', $automation_admin_emails);
                        foreach ($admin_emails as $admin_email) {
                            $emails[] = trim(sanitize_email($admin_email));
                        }
                        if (!empty($emails) && !empty($log_ids)) {
                            $primer_smtp_options = get_option('primer_emails');
                            foreach ($emails as $to_admin_email) {
                                if ((file_exists($csv_dir_file)) && (filesize($csv_dir_file) > 4)) {
                                    $primer_smtp_type = $primer_smtp_options['smtp_type'];
                                    if ($primer_smtp_type == 'wordpress_default') {
                                        $mailResultSMTP = wp_mail($to_admin_email, $primer_smtp_subject, 'export file', '', $csv_dir_file);
                                    } else {
                                        if (!empty($primer_smtp_options['email_from_name'])) {
                                            $from_name_email = $primer_smtp_options['email_from_name'];
                                        } else {
                                            $from_name_email = '';
                                        }
                                        $mailResultSMTP = $primer_smtp->primer_mail_sender($to_admin_email, $from_name_email, $primer_smtp_subject, 'automation log', $csv_dir_file);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        die();
    }

    function ajax_fire_cron() {
        echo "OK";
        $this->convert_order_to_invoice();
        wp_die();
    }

}

new PrimerCron();
