<?php

defined('ABSPATH') || exit;

use Automattic\WooCommerce\Utilities\OrderUtil;

class PrimerOrderList {

    public array $orders_array = array();

    public array $orders_customers = array();

    public function get($page_number): array {
        date_default_timezone_set('Europe/Athens');
        $primer_licenses = get_option('primer_licenses');
        $posts_per_page  = 20;
        $order_count     = 0;

        $orders = wc_get_orders(array(
            'order'          => 'DESC',
            'posts_per_page' => $posts_per_page,
            'paged'          => $page_number,
            'offset'         => ($page_number - 1) * $posts_per_page,
            'limit'          => 20,
            'post_type'      => array('shop_order', 'shop_subscription')
        ));

        foreach ($orders as $order) {
            if (is_a($order, 'WC_Order_Refund')) {
                $order = wc_get_order($order->get_parent_id());
            }
            if (empty($order)) {
                continue;
            }
            if (!in_array(4, $primer_licenses['wpModules']) && !empty($order->get_billing_country()) && $order->get_billing_country() != 'GR') {
                continue;
            }
            $id_of_order          = $order->get_id();
            $receipt_order_status = $order->get_meta('receipt_status');

            if (empty($receipt_order_status)) {
                $order->update_meta_data('receipt_status', 'not_issued');
                $order->save();
            }

            $transmission_failure = $order->get_meta('transmission_failure_check');
            $failed_48            = $order->get_meta('failed_48');
            $order_date           = $order->get_date_paid() ?: $order->get_date_created();
            $order_paid_date      = $order_date->format('F j, Y');
            $order_paid_hour      = $order_date->format('H:i:s');
            $user                 = $order->get_user();
            $user_full_name       = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
            $payment_title        = $order->get_payment_method_title();
            $order_status         = $order->get_status();
            $is_cancelled         = $order->get_meta('cancelled');
            $receipt_id           = $order->get_meta('order_id_from_receipt');
            $credit_receipt_id    = $order->get_meta('order_id_from_credit_receipt');
            $credit_receipt_date  = $is_cancelled ? __('Cancelled', 'primer') . ', ' . get_the_date('F j, Y', $credit_receipt_id) : '';
            $receipt_date         = !empty($receipt_id) ? get_the_date('F j, Y', $receipt_id) : '';
            $currency_symbol      = get_woocommerce_currency_symbol($order->get_currency());
            $order_total_price    = number_format($order->get_total() - ($order->get_total_refunded() ?: 0), 2, '.', '');

            // Here needs work
            $log_for_order = $order->get_meta('log_id_for_order');
            $receipt_status_from_meta_url = '';
            if (!empty($log_for_order)) {
                $log_type                     = get_post_type($log_for_order);
                $base_url                     = ($log_type == 'pr_log_automation') ? admin_url('admin.php?page=primer_receipts_logs_automation') : admin_url('admin.php?page=primer_receipts_logs');
                $receipt_status_from_meta_url = $base_url . '&order_log=' . $log_for_order;
            }

            $transmission_failure_messages = [
                1 => 'Αδυναμία σύνδεσης',
                2 => 'Επιτυχής Αποστολή',
                3 => 'Αδυναμία σύνδεσης',
                4 => 'Αδυναμία Αποστολής HTML'
            ];
            $transmission_failure_message  = $transmission_failure_messages[$transmission_failure] ?? '';

            $this->orders_array[$order_count] = [
                'order_id'             => $id_of_order,
                'order_date'           => $order_paid_date,
                'order_hour'           => $order_paid_hour,
                'order_client'         => $user ? $user->display_name : $user_full_name,
                'order_price'          => $order_total_price . ' ' . $currency_symbol,
                'transmission_failure' => $transmission_failure_message,
                'accept_48'            => $failed_48,
                'order_status'         => $order_status,
                'payment_status'       => $payment_title,
                'receipt_date'         => $receipt_date,
                'credit_receipt_date'  => $credit_receipt_date,
                'receipt_status'       => $receipt_status_from_meta_url,
                'receipt_id'           => $receipt_id ?: '',
                'credit_receipt_id'    => $credit_receipt_id ?: '',
            ];
            $order_count++;
        }

        return $this->orders_array;
    }

    public function get_with_params($page_number, $order_date_from, $order_date_to, $order_customer, $order_status, $order_receipt_status): array {
        $posts_per_page  = 20;
        $primer_licenses = get_option('primer_licenses');
        $search_term     = trim(sanitize_text_field(wp_unslash($_GET['s'] ?? '')));

        if (is_array($order_status)) {
            array_map('sanitize_text_field', $order_status);
        } else {
            sanitize_text_field($order_status);
        }

        $order_args = array(
            'limit'          => 20,
            'posts_per_page' => $posts_per_page,
            'paged'          => $page_number,
            'type'           => array('shop_order', 'shop_subscription'),
            'order'          => 'DESC',
            'return'         => 'ids',
        );

        $order_args_total = array(
            'limit'          => -1,
            'posts_per_page' => -1,
            'order'          => 'DESC',
            'return'         => 'ids',
            'type'           => array('shop_order', 'shop_subscription'),
        );

        if ($order_status != '') {
            $order_args['status']       = $order_status;
            $order_args_total['status'] = $order_status;
        }

        $order_args['numberposts'] = -1;
        if (!empty($search_term)) {
            $order_args['post__in']       = array(intval(sanitize_text_field(wp_unslash($_GET['s']))));
            $order_args_total['post__in'] = array(intval(sanitize_text_field(wp_unslash($_GET['s']))));
        }

        sanitize_text_field($order_customer);
        $order_args['meta_key']         = '_customer_user';
        $order_args['meta_value']       = $order_customer;
        $order_args_total['meta_key']   = '_customer_user';
        $order_args_total['meta_value'] = $order_customer;

        if (!empty($order_receipt_status)) {
            sanitize_text_field($order_receipt_status);
            if ($order_receipt_status == 'issued' || $order_receipt_status == 'not_issued') {
                $order_args['meta_key']         = 'receipt_status';
                $order_args['meta_value']       = $order_receipt_status;
                $order_args_total['meta_key']   = 'receipt_status';
                $order_args_total['meta_value'] = $order_receipt_status;
            } elseif ($order_receipt_status == 'transmission_failure_check') {
                $order_args['meta_key']         = 'order_date_failed';
                $order_args_total['meta_key']   = 'order_date_failed';
            }
        } else {
            $order_args['meta_key']             = '';
            $order_args_total['meta_key']       = '';
        }

        sanitize_text_field($order_date_from);
        sanitize_text_field($order_date_to);

        $date_before = !empty($order_date_from) ? wc_string_to_datetime($order_date_from)->date('Y-m-d') : null;
        $date_after  = !empty($order_date_to) ? wc_string_to_datetime($order_date_to)->date('Y-m-d') : null;

        if ($date_before && $date_after) {
            $order_args['date_created']       = $date_before . '...' . $date_after;
            $order_args_total['date_created'] = $date_before . '...' . $date_after;
        } elseif ($date_before) {
            $order_args['date_created']       = '>=' . $date_before;
            $order_args_total['date_created'] = '>=' . $date_before;
        } elseif ($date_after) {
            $order_args['date_created']       = '<=' . $date_after;
            $order_args_total['date_created'] = '<=' . $date_after;
        }

        $query_orders       = wc_get_orders($order_args);
        $orders             = $query_orders;
        $order_count        = 0;
        $query_orders_total = wc_get_orders($order_args_total);
        $total_orders       = count($query_orders_total);

        foreach ($orders as $order_id) {
            $order = new WC_Order($order_id);
            if (!in_array(4, $primer_licenses['wpModules']) && $order->get_billing_country() != 'GR') {
                continue;
            }

            $order_date           = $order->get_date_paid() ?: $order->get_date_created();
            $order_paid_date      = $order_date->format('F j, Y');
            $order_paid_hour      = $order_date->format('H:i:s');
            $transmission_failure = $order->get_meta('transmission_failure_check');
            $failed_48            = $order->get_meta('failed_48');
            $order_total_price    = $order->get_total();
            $user                 = $order->get_user();
            $user_full_name       = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
            $payment_title        = $order->get_payment_method_title();
            $order_status         = $order->get_status();
            $is_cancelled         = $order->get_meta('cancelled');
            $receipt_id           = $order->get_meta('order_id_from_receipt');
            $credit_receipt_id    = $order->get_meta('order_id_from_credit_receipt');
            $credit_receipt_date  = $is_cancelled ? __('Cancelled', 'primer') . ', ' . get_the_date('F j, Y', $credit_receipt_id) : '';
            $receipt_date         = !empty($receipt_id) ? get_the_date('F j, Y', $receipt_id) : '';
            $currency_symbol      = get_woocommerce_currency_symbol($order->get_currency());

            if ($order->get_total_refunded() > 0) {
                $order_total_price -= $order->get_total_refunded();
            }

            // Need works here
            $log_for_order = $order->get_meta('log_id_for_order');
            $receipt_status_from_meta_url = '';
            if (!empty($log_for_order)) {
                $log_type = get_post_type($log_for_order);
                $base_url = ($log_type == 'pr_log_automation') ? admin_url('admin.php?page=primer_receipts_logs_automation') : admin_url('admin.php?page=primer_receipts_logs');
                $receipt_status_from_meta_url = $base_url . '&order_log=' . $log_for_order;
            }

            $transmission_failure_messages = [
                1 => 'Αδυναμία σύνδεσης',
                2 => 'Επιτυχής Αποστολή',
                3 => 'Αδυναμία σύνδεσης',
                4 => 'Αδυναμία Αποστολής HTML'
            ];
            $transmission_failure_message  = $transmission_failure_messages[$transmission_failure] ?? '';

            $this->orders_array[$order_count] = [
                'order_id'             => $order_id,
                'order_date'           => $order_paid_date,
                'order_hour'           => $order_paid_hour,
                'order_client'         => $user ? $user->display_name : $user_full_name,
                'order_price'          => $order_total_price . ' ' . $currency_symbol,
                'order_status'         => $order_status,
                'transmission_failure' => $transmission_failure_message,
                'accept_48'            => $failed_48,
                'payment_status'       => $payment_title,
                'receipt_date'         => $receipt_date,
                'credit_receipt_date'  => $credit_receipt_date,
                'receipt_status'       => $receipt_status_from_meta_url,
                'receipt_id'           => $receipt_id ?: '',
                'credit_receipt_id'    => $credit_receipt_id ?: ''
            ];
            $order_count++;
        }

        return array(
            'orders'       => $this->orders_array,
            'total_orders' => $total_orders
        );
    }

    public function get_users_from_orders($page_number): array {
        $orders      = wc_get_orders([
            'posts_per_page' => 20,
            'page'           => $page_number,
            'return'         => 'ids'
        ]);
        $order_count = 0;
        foreach ($orders as $order_id) {
            $order = new WC_Order($order_id);
            $this->orders_customers[$order_count] = [
                'order_id'        => $order_id,
                'order_client'    => $order->get_user() ? $order->get_user()->display_name : '',
                'order_client_id' => $order->get_user_id() ? $order->get_user_id() : '0'
            ];
            $order_count++;
        }

        return $this->orders_customers;
    }

    public function get_dates_from_orders(): array {
        global $wpdb;

        if (class_exists('\Automattic\WooCommerce\Utilities\OrderUtil') && OrderUtil::custom_orders_table_usage_is_enabled()) {
            $orders_table = $wpdb->prefix . 'wc_orders';

            return $wpdb->get_col("SELECT UNIX_TIMESTAMP(date_created_gmt)
             FROM {$orders_table}
             WHERE type IN ('shop_order', 'shop_subscription')
             AND status IN ('wc-completed', 'wc-processing', 'wc-pending', 'wc-on-hold', 'wc-cancelled', 'wc-refunded', 'wc-failed')"
            );
        } else {
            return $wpdb->get_col("SELECT UNIX_TIMESTAMP(post_date)
             FROM {$wpdb->posts}
             WHERE post_type = 'shop_order'
             AND post_status IN ('wc-completed', 'wc-processing', 'wc-pending', 'wc-on-hold', 'wc-cancelled', 'wc-refunded', 'wc-failed')"
            );
        }
    }

}
