<?php

defined('ABSPATH') || exit;

class PrimerReceiptList {

    public array $receipt_array = array();

    public array $receipt_params_array = array();

    public array $receipt_date_range = array();

    public function get($page_number):array {
        $receipt_args   = array(
            'posts_per_page' => 20,
            'paged'          => $page_number,
            'post_type'      => 'primer_receipt',
            'post_status'    => 'publish'
        );

        $receipt_query = new WP_Query($receipt_args);

        if ($receipt_query->have_posts()) {
            while ($receipt_query->have_posts()) {
                $receipt_query->the_post();
                $receipt_id            = get_the_ID();
                $receipt_status        = get_post_meta($receipt_id, 'receipt_status', true);
                $invoice_client_name   = get_post_meta($receipt_id, 'receipt_client', true) ?: '';
                $log_id_for_order      = get_post_meta($receipt_id, 'log_id_for_order', true);
                $is_credit_receipt     = get_post_meta($receipt_id, 'credit_receipt', true);
                $is_cancelled_receipt  = get_post_meta($receipt_id, 'cancelled', true);
                $receipt_status_text   = __($receipt_status === 'issued' ? 'Issued' : 'Not Issued', 'primer');
                $credit_receipt        = $is_credit_receipt ? 'yes' : '';
                $cancelled_receipt     = $is_cancelled_receipt ? 'yes' : '';
                $log_id_for_order      = $is_credit_receipt ? get_post_meta($receipt_id, 'credit_log_id_for_order', true) : $log_id_for_order;

                // Needs works here too
                $receipt_status_from_meta_url = '';
                if (!empty($log_id_for_order)) {
                    $log_type = get_post_type($log_id_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_id_for_order;
                }

                $json_send_to_api = get_post_meta($log_id_for_order, 'json_send_to_api', true);
                $json_decoded     = json_decode(preg_replace(['/\"name\":\s*\".*?\",/', '/,\"extra\":\s*\{[^}]*\},?/'], '', $json_send_to_api), true);
                $receipt_price    = number_format($json_decoded['invoice'][0]['invoiceSummary']['totalGrossValue'], 2, '.', '');

                $this->receipt_array[] = array(
                    'receipt_id'           => $receipt_id,
                    'receipt_date'         => get_the_date('F j, Y'),
                    'receipt_hour'         => get_the_time('H:i:s'),
                    'receipt_client'       => $invoice_client_name,
                    'receipt_price'        => $receipt_price,
                    'receipt_status'       => $receipt_status_text,
                    'receipt_error_status' => $receipt_status_from_meta_url,
                    'credit_receipt'       => $credit_receipt,
                    'cancelled_receipt'    => $cancelled_receipt,
                );
            }
        }
        wp_reset_postdata();

        return $this->receipt_array;
    }

    public function get_with_params($page_number, $receipt_date_from, $receipt_date_to, $receipt_customer, $receipt_status, $receipt_type):array {
        $receipt_date_from   = sanitize_text_field($receipt_date_from) ?: '';
        $receipt_date_to     = sanitize_text_field($receipt_date_to) ?: '';
        $receipt_customer    = sanitize_text_field($receipt_customer) ?: '';
        $receipt_status      = sanitize_text_field($receipt_status) ?: '';
        $receipt_type        = sanitize_text_field($receipt_type) ?: '';
        $search_term         = trim(sanitize_text_field(wp_unslash($_GET['s'] ?? '')));
        $meta_values         = array();

        $receipt_args = array(
            'posts_per_page' => 20,
            'paged'          => $page_number,
            'limit'          => 20,
            'post_type'      => 'primer_receipt',
            'post_status'    => 'publish'
        );
        $receipt_args_total = array(
            'posts_per_page' => -1,
            'limit'          => -1,
            'post_type'      => 'primer_receipt',
            'post_status'    => 'publish'
        );

        if (!empty($receipt_status)) {
            $meta_values['receipt_status'][] = $receipt_status;
        }
        if (!empty($receipt_type)) {
            $meta_values['receipt_type'][]   = $receipt_type;
        }
        if (!empty($receipt_customer)) {
            $meta_values['receipt_client'][] = $receipt_customer;
        }

        if (!empty($meta_values)) {
            $receipt_args['meta_query']['relation'] = 'AND';
            $receipt_args_total['meta_query']['relation'] = 'AND';
            foreach ($meta_values as $key => $meta_value) {
                $receipt_args['meta_query'][] = array(
                    'key'     => $key,
                    'value'   => $meta_value,
                    'compare' => 'IN'
                );
                $receipt_args_total['meta_query'][] = array(
                    'key'     => $key,
                    'value'   => $meta_value,
                    'compare' => 'IN'
                );
            }
        }
        if (!empty($receipt_date_from) || !empty($receipt_date_to)) {
            $receipt_args['date_query']['relation'] = 'AND';
            $receipt_args_total['date_query']['relation'] = 'AND';
            $receipt_args['date_query'][] = array(
                'after'       => $receipt_date_from,
                'before'      => $receipt_date_to,
                'compare'     => 'BETWEEN',
                'inclusive'   => true
            );
            $receipt_args_total['date_query'][] = array(
                'after'       => $receipt_date_from,
                'before'      => $receipt_date_to,
                'compare'     => 'BETWEEN',
                'inclusive'   => true
            );
        }
        $i = 0;
        if (!empty($search_term)) {
            $receipt_args['meta_query'][$i + 1]['relation'] = 'OR';
            $receipt_args['meta_query'][$i + 1][] = [
                'key'         => 'order_id_to_receipt',
                'value'       => array(intval(sanitize_text_field( wp_unslash( $_GET['s'] )))),
                'compare'     => 'IN'
            ];
            $receipt_args['meta_query'][$i + 1][] = [
                'key'         => '_primer_receipt_number',
                'value'       => array(intval(sanitize_text_field( wp_unslash( $_GET['s'] )))),
                'compare'     => 'IN'
            ];

        }
        if (!empty($search_term)) {
            $receipt_args_total['meta_query'][$i + 1]['relation'] = 'OR';
            $receipt_args_total['meta_query'][$i + 1][] = array(
                'key'         => 'order_id_to_receipt',
                'value'       => array(intval(sanitize_text_field(wp_unslash($_GET['s'])))),
                'compare'     => 'IN'
            );
            $receipt_args_total['meta_query'][$i + 1][] = array(
                'key'         => '_primer_receipt_number',
                'value'       => array(intval(sanitize_text_field(wp_unslash($_GET['s'])))),
                'compare'     => 'IN'
            );
        }

        $receipt_args['fields']       = 'ids';
        $receipt_args_total['fields'] = 'ids';
        $receipt_query                = get_posts($receipt_args);
        $receipt_query_total          = get_posts($receipt_args_total);
        $total_receipt                = count($receipt_query_total);

        foreach ($receipt_query as $receipt_id) {
            $receipt_status       = get_post_meta($receipt_id, 'receipt_status', true);
            $invoice_client       = get_post_meta($receipt_id, 'receipt_client', true);
            $order_id             = get_post_meta($receipt_id,'order_id_to_receipt', true);
            $is_credit_receipt    = get_post_meta($receipt_id, 'credit_receipt');
            $is_cancelled_receipt = get_post_meta($receipt_id, 'cancelled', true);

            $order                = wc_get_order($order_id);
            $log_id               = $order->get_meta('log_id_for_order');
            $user_full_name       = !empty($order) ? $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() : '';
            $invoice_client       = $invoice_client ?: $user_full_name;
            $receipt_status_text  = ($receipt_status === 'issued') ? 'Issued' : 'Not Issued';
            $credit_receipt       = $is_credit_receipt ? 'yes' : '';
            $cancelled_receipt    = $is_cancelled_receipt ? 'yes' : '';
            $log_id               = $is_credit_receipt ? get_post_meta($receipt_id, 'credit_log_id_for_order', true) : $log_id;

            // Needs works here too
            $receipt_status_from_meta_url = '';
            if (!empty($log_id)) {
                $log_type = get_post_type($log_id);
                if ($log_type == 'pr_log_automation') {
                    $receipt_status_from_meta_url = admin_url('admin.php?page=primer_receipts_logs_automation');
                } else {
                    $receipt_status_from_meta_url = admin_url('admin.php?page=primer_receipts_logs');
                }
                $receipt_status_from_meta_url .= '&order_log=' . $log_id;
            }

            $this->receipt_params_array[] = array(
                'receipt_id'           => $receipt_id,
                'receipt_date'         => get_the_date('F j, Y', $receipt_id),
                'receipt_hour'         => get_the_time('H:i:s', $receipt_id),
                'receipt_client'       => $invoice_client,
                'receipt_price'        => get_post_meta($receipt_id, 'receipt_price', true),
                'receipt_status'       => $receipt_status_text,
                'receipt_error_status' => $receipt_status_from_meta_url,
                'credit_receipt'       => $credit_receipt,
                'cancelled_receipt'    => $cancelled_receipt,
            );
        }

        $this->receipt_params_array['total_receipt'] = $total_receipt;
        return $this->receipt_params_array;
    }

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

        $receipt_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'primer_receipt' AND post_status = 'publish'");

        if (empty($receipt_ids)) {
            return array();
        }

        $receipts          = implode(',', array_fill(0, count($receipt_ids), '%d'));
        $receipts_data     = $wpdb->get_results($wpdb->prepare(
            "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = 'receipt_client' AND post_id IN ($receipts)", $receipt_ids), ARRAY_A);
        $receipt_customers = array();

        foreach ($receipts_data as $data) {
            $receipt_customers[] = array(
                'receipt_client'    => sanitize_text_field($data['meta_value']),
                'receipt_client_id' => sanitize_text_field($data['meta_value']),
            );
        }

        return $receipt_customers;
    }

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

        $results = $wpdb->get_col("SELECT post_date FROM $wpdb->posts WHERE post_type = 'primer_receipt' AND post_status = 'publish'");

        $this->receipt_date_range = array();
        foreach ($results as $post_date) {
            $this->receipt_date_range[] = strtotime($post_date);
        }

        return $this->receipt_date_range;
    }

}
