<?php
/**
 * BuildQuery.php
 *
 * @since      1.0.0
 * @package    WcElectronInvoice\Xml
 * @author     alfiopiccione <alfio.piccione@gmail.com>

 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2025 POP
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

namespace WcElectronInvoice\Xml;

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use WcElectronInvoice\EndPoint\Endpoints;
use WcElectronInvoice\Functions as F;
use WcElectronInvoice\Providers\OrdersProviderAbstract;
use WcElectronInvoice\Utils\Helpers;

/**
 * Class BuildQuery
 *
 * @since  1.0.0
 * @author alfiopiccione <alfio.piccione@gmail.com>
 */
class BuildQuery extends Endpoints
{
    /**
     * Xml Query
     *
     * @return @return bool|\WC_Order|\WC_Order_Query|\WC_Order_Refund|null
     * @since  1.0.0
     */
    public function xmlQuery()
    {
        $wpQuery = F\getWpQuery();
        $query   = null;
        $documentType = F\getRequestedProviderDocumentType();

        // @codingStandardsIgnoreLine
        $getKey    = F\filterInput($_GET, 'key', FILTER_UNSAFE_RAW);
        $key       = get_query_var('key');
        $getFormat = F\filterInput($_GET, 'format', FILTER_UNSAFE_RAW);
        $format    = get_query_var('format');
        // Get order completed data.
        $dateOrderCompleted = get_query_var('date_completed');
        // Date ID
        $dateIN = get_query_var('date_in');
        // Date ID
        $dateOUT = get_query_var('date_out');
        // get orders provider
        $getProvider    = F\filterInput($_GET, 'provider', FILTER_UNSAFE_RAW);
        $ordersProvider = get_query_var('provider');
        $provider       = $ordersProvider ?: $getProvider;

        if ('json' === $format) {
            return null;
        }

        // Setup data for query
        $data = Helpers::setQueryData(array(
            'getKey'         => $getKey,
            'key'            => $key,
            'getFormat'      => $getFormat,
            'format'         => $format,
            'provider'       => $provider,
            'admin_endpoint' => is_admin(),
        ), $wpQuery, $this);

        if (is_object($data)) {
            // Set arguments for query
            switch ($data->postType) {
                case 'shop_order':
                    $args = array(
                        'status'   => OrdersProviderAbstract::ORDERS_DEFAULT_LIST_STATUSES,
                        'limit'    => -1,
                        'orderby'  => 'date',
                        'order'    => 'ASC',
                        'provider' => $provider,
                    );

                    // Filter Order by date completed
                    if (isset($dateIN) && '' !== $dateIN && '' === $dateOUT) {
                        $args['date_modified'] = ">{$dateIN}";
                    } elseif ('' === $dateIN && isset($dateOUT) && '' !== $dateOUT) {
                        $args['date_modified'] = "<{$dateOUT}";
                    } elseif (isset($dateIN) && '' !== $dateIN && isset($dateOUT) && '' !== $dateOUT) {
                        $args['date_modified'] = "{$dateIN}...{$dateOUT}";
                    }

                    // Equal date
                    if (isset($dateIN) &&
                        isset($dateOUT) &&
                        '' !== $dateIN &&
                        '' !== $dateOUT &&
                        $dateIN === $dateOUT
                    ) {
                        $date                  = date('Y-m-d', intval($dateIN));
                        $args['date_modified'] = "{$date}";
                    }

                    if (isset($data->idTag) && '' !== $data->idTag) {
                        $args['order_id'] = intval($data->idTag);
                        $args['document_type'] = $documentType;
                    }
                    break;
                default:
                    $args = array();
                    break;
            }

            // Set query
            $query = Helpers::setQuery($data->postType, $args);

            if ($query && ! empty($args['order_id'])) {
                $query = F\resolveProviderDocument(
                    $args['order_id'],
                    $provider,
                    $args['document_type'] ?? 'shop_order',
                    F\filterInput($_GET, 'parent_id', FILTER_VALIDATE_INT) ?: 0
                );
            }
        }

        return $query;
    }
}
