<?php
/**
 * XmlOrdersList.php
 *
 * @since      1.0.0
 * @package    WcElectronInvoice\Admin\Settings\Fields
 * @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\Admin\Settings\Fields;

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

use WcElectronInvoice\Admin\Settings\OptionPage;
use WcElectronInvoice\Admin\XmlOrderListTable;
use WcElectronInvoice\Plugin;

/**
 * Class XmlOrdersList
 *
 * @since  1.0.0
 * @author alfiopiccione <alfio.piccione@gmail.com>
 */
final class XmlOrdersList
{
    /**
     * List type
     *
     * @since 1.0.0
     */
    const LIST_TYPE = 'shop_order';

    /**
     * XmlOrdersList constructor.
     *
     * @since 1.0.0
     */
    public function __construct()
    {
        $this->init();
    }

    /**
     * Init
     *
     * @since 1.0.0
     */
    private function init()
    {
        add_action('wc_el_inv-after_settings_form', array($this, 'template'));
    }

    /**
     * Summary data
     *
     * @return object
     */
    private function summaryData()
    {
        //  Initialized
        $sentCount   = 0;
        $noSentCount = 0;

        if (! empty(XmlOrderListTable::$filteredListIndex)) {
            foreach (XmlOrderListTable::$filteredListIndex as $summary) {
                $sent = $summary['invoice_sent'] ?? '';
                switch ($sent) {
                    case 'sent':
                        $sentCount++;
                        break;
                    case 'no_sent':
                        $noSentCount++;
                        break;
                    default:
                        break;
                }
            }
        }

        return (object)array(
            'sent'   => $sentCount,
            'noSent' => $noSentCount,
        );
    }

    /**
     * Filter customer
     *
     * @return string
     * @since 1.0.0
     */
    private function filterSelects()
    {
        // @codingStandardsIgnoreLine
        $type        = \WcElectronInvoice\Functions\filterInput($_GET, 'filter_type', FILTER_UNSAFE_RAW);
        $currentType = null;

        if (isset($type) && '' !== $type) {
            $currentType = $type;
        }

        $selectOptions = array(
            'invoice'           => esc_html__('Invoice', WC_EL_INV_TEXTDOMAIN),
            'shop_order_refund' => esc_html__('Credit note', WC_EL_INV_TEXTDOMAIN),
        );

        // Choice type
        $choiceTypeCheck = OptionPage::init()->getOptions('invoice_choice_type');
        if ('on' === $choiceTypeCheck) {
            $selectOptions['receipt'] = esc_html_x('Receipt', 'invoice_choice', WC_EL_INV_TEXTDOMAIN);
        }

        $output = '<label for="filter_type">';
        $output .= '<select id="filter_type" name="filter_type">';
        $output .= "<option value=''>" . esc_html__('All type', WC_EL_INV_TEXTDOMAIN) . "</option>";
        foreach ($selectOptions as $key => $option) {
            $selected = $currentType === $key ? 'selected="selected"' : '';
            $output   .= "<option {$selected} value={$key}>{$option}</option>";
        }
        $output .= '</select>';
        $output .= '</label>';

        return $output;
    }

    /**
     * Bulk Action
     *
     * @return string
     */
    public static function buttonBulkAction()
    {
        // Filter by state
        $actions = array(
            'sent'    => esc_html__('Mark as Sent', WC_EL_INV_TEXTDOMAIN),
            'no_sent' => esc_html__('Mark as Not Sent', WC_EL_INV_TEXTDOMAIN),
        );

        $output = '<label class="actions_bulk_label" for="actions_bulk">';
        $output .= '<select id="action_bulk" name="action_bulk">';
        $output .= "<option value=''>" . esc_html__('Bulk Action', WC_EL_INV_TEXTDOMAIN) . "</option>";
        foreach ($actions as $key => $actionName) {
            $output .= "<option value='{$key}'>{$actionName}</option>";
        }
        $output .= '</select>';
        $output .= '</label>';

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $output;
    }

    /**
     * Bulk Actions
     *
     * @param array orders data
     *
     * @since 1.1.0
     *
     */
    private function bulkActions($orders)
    {
        // @codingStandardsIgnoreLine
        $state    = \WcElectronInvoice\Functions\filterInput($_GET, 'filter_state', FILTER_UNSAFE_RAW);
        $provider = \WcElectronInvoice\Functions\filterInput($_GET, 'filter_provider', FILTER_UNSAFE_RAW);
        $dateIN   = \WcElectronInvoice\Functions\filterInput($_GET, 'date_in', FILTER_UNSAFE_RAW);
        $dateOUT  = \WcElectronInvoice\Functions\filterInput($_GET, 'date_out', FILTER_UNSAFE_RAW);

        // State options
        $selectOptionsState = array(
            'completed'  => esc_html__('Completed', WC_EL_INV_TEXTDOMAIN),
            'processing' => esc_html__('Processing', WC_EL_INV_TEXTDOMAIN),
            'refunded'   => esc_html__('Refunded', WC_EL_INV_TEXTDOMAIN),
        );

        $currentState = null;
        if (isset($state) && '' !== $state) {
            $currentState = $state;
        }

        $currentProvider = null;
        if (isset($provider) && '' !== $provider) {
            $currentProvider = $provider;
        }

        // Js error not set date value
        $dateIN  = 'NaN' !== $dateIN ? $dateIN : time();
        $dateOUT = 'NaN' !== $dateOUT ? $dateOUT : time();
        $output  = '';

        // DatePicker scripts.
        wp_script_is('wc_el_inv_datepicker', 'registered') ? wp_enqueue_script('wc_el_inv_datepicker') : null;
        wp_script_is('datepicker-lang', 'registered') ? wp_enqueue_script('datepicker-lang') : null;
        $licenseKey = OptionPage::getK();
        // Admin page
        $adminUrl = admin_url() . "admin.php?page=wc_el_inv-options-page&tab=xml";

        $output .= ' <div class="bulk-actions">';
        // Filter date
        $output .= sprintf('<span><input placeholder="%s" type="text" value="%s" id="date_in" class="wc_el_inv-datepicker"></span>',
            esc_html__('From: ', WC_EL_INV_TEXTDOMAIN),
            isset($dateIN) && false !== $dateIN ? date('Y-m-d', $dateIN) : ''
        );
        $output .= sprintf('<span><input placeholder="%s" type="text" value="%s" id="date_out" class="wc_el_inv-datepicker"></span>',
            esc_html__('To: ', WC_EL_INV_TEXTDOMAIN),
            isset($dateOUT) && false !== $dateOUT ? date('Y-m-d', $dateOUT) : ''
        );

        // Filter by type
        $output .= $this->filterSelects();

        // Filter by state
        $output .= '<label for="filter_state">';
        $output .= '<select id="filter_state" name="filter_state">';
        $output .= "<option value=''>" . esc_html__('All state', WC_EL_INV_TEXTDOMAIN) . "</option>";
        foreach ($selectOptionsState as $key => $option) {
            $selected = $currentState === $key ? 'selected="selected"' : '';
            $output   .= "<option {$selected} value={$key}>{$option}</option>";
        }
        $output .= '</select>';
        $output .= '</label>';

        // Filter by provider
        $ordersProviderQuery = \WcElectronInvoice\Providers\OrderQuery::instance();
        $providers           = $ordersProviderQuery->get_providers() ?: [];
        if (count($providers) > 1) {
            $output .= '<label for="filter_provider">';
            $output .= '<select id="filter_provider" name="filter_provider">';
            $output .= "<option value='all'>" . esc_html__('All provider', WC_EL_INV_TEXTDOMAIN) . "</option>";
            foreach ($providers as $provider) {
                $providerName = ucfirst($provider->get_label());
                $selected     = $currentProvider === $provider->name() ? 'selected="selected"' : '';
                $output       .= "<option {$selected} value={$provider->name()}>{$providerName}</option>";
            }
            $output .= '</select>';
            $output .= '</label>';
        }

        // Filter button
        $output .= '<span class="actions-button">';
        $output .= sprintf(
            '<a class="button button-secondary filter" href="%1$s" title="%2$s">' .
            '<span class="dashicons dashicons-filter"></span> %2$s</a>',
            esc_url($adminUrl),
            esc_html__('Filter', WC_EL_INV_TEXTDOMAIN)
        );

        $level = \WcElectronInvoice\Wizard::popGetUserLevel();
        $bulkDownloadEnabled = \WcElectronInvoice\Wizard::isUserLevelGte($level, 'growth');
        if (0 !== $orders) {
            $filtered = (isset($dateIN) && false !== $dateIN || isset($dateOUT) && false !== $dateOUT) ? 'yes' : 'no';

            if ($bulkDownloadEnabled) {
                // New save_bulk
                $output   .= sprintf(
                    '<a id="start-download-btn" class="button button-secondary button-save save-all"><span class="dashicons dashicons-media-archive"></span> %s</a>',
                    esc_html__('Download XML', WC_EL_INV_TEXTDOMAIN)
                );

                $urlCsv = esc_url_raw(add_query_arg([
                    self::LIST_TYPE => 'all',
                    'key'           => $licenseKey,
                    'format'        => 'xml',
                    'save'          => 'true',
                    'all'           => 'true',
                    'type'          => 'csv',
                    'filtered'      => $filtered,
                    'v'             => time(),
                ], site_url('/' . \WcElectronInvoice\EndPoint\Endpoints::ENDPOINT)));
                $output .= sprintf(
                    '<a class="button button-secondary button-csv save-all-csv" target="_blank" href="%1$s" title="%2$s">' .
                    '<span class="dashicons dashicons-list-view"></span> %2$s</a>',
                    $urlCsv,
                    esc_html__('Download CSV orders', WC_EL_INV_TEXTDOMAIN)
                );
            } else {
                $title = esc_attr__('Bulk download is available starting from the Growth plan.', WC_EL_INV_TEXTDOMAIN);
                $paidOnlyBadge = sprintf(
                    '<span class="pop-premium-badge">%s</span>',
                    esc_html(\WcElectronInvoice\Functions\getPremiumBadgeLabel('growth', $level))
                );
                $output .= sprintf(
                    '<a class="button button-secondary button-save save-all disabled pop-has-premium-badge" href="#" aria-disabled="true" onclick="return false;" title="%1$s">%3$s<span class="dashicons dashicons-media-archive"></span> %2$s</a>',
                    $title,
                    esc_html__('Download XML', WC_EL_INV_TEXTDOMAIN),
                    $paidOnlyBadge
                );
                $output .= sprintf(
                    '<a class="button button-secondary button-csv save-all-csv disabled pop-has-premium-badge" href="#" aria-disabled="true" onclick="return false;" title="%1$s">%3$s<span class="dashicons dashicons-list-view"></span> %2$s</a>',
                    $title,
                    esc_html__('Download CSV orders', WC_EL_INV_TEXTDOMAIN),
                    $paidOnlyBadge
                );
            }
        }

        $output .= '</span>';

        $output .= '</div>';

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $output;
    }

    /**
     * Notice
     *
     * @since 1.0.0
     */
    private function notice()
    {
        // Notice no found or disabled view
        $createdZip   = \WcElectronInvoice\Functions\filterInput($_GET, 'created_zip', FILTER_UNSAFE_RAW);
        $foundOrder   = \WcElectronInvoice\Functions\filterInput($_GET, 'found_order', FILTER_UNSAFE_RAW);
        $disabledView = \WcElectronInvoice\Functions\filterInput($_GET, 'disabled_view', FILTER_UNSAFE_RAW);

        if (isset($foundOrder) && 'no' === $foundOrder) : ?>
            <div class="pop-notice notice-error is-dismissible">
                <p><span class="dashicons dashicons-no"></span>
                    <?php esc_html_e(
                        'No order found!',
                        WC_EL_INV_TEXTDOMAIN
                    ); ?>
                </p>
            </div>
        <?php endif;

        if (isset($disabledView) && 'yes' === $disabledView) : ?>
            <div class="pop-notice notice-error is-dismissible">
                <p><span class="dashicons dashicons-no"></span>
                    <?php esc_html_e(
                        'The display of all xml is disabled. First filter orders by user and / or dates.',
                        WC_EL_INV_TEXTDOMAIN
                    ); ?>
                </p>
            </div>
        <?php endif;

        if (isset($createdZip) && 'error' === $createdZip) : ?>
            <div class="pop-notice notice-error is-dismissible">
                <p><span class="dashicons dashicons-no"></span>
                    <?php esc_html_e(
                        'Error: .zip file not created',
                        WC_EL_INV_TEXTDOMAIN
                    ); ?>
                </p>
            </div>
        <?php endif;
    }

    /**
     * Xml list template
     *
     * @since 1.1.0
     */
    public function template()
    {
        // Get key
        $key = OptionPage::getK();
        if (\WcElectronInvoice\Functions\noKey($key)) {
            return;
        }

        $xmlOrdersListTable = new XmlOrderListTable(array());
        $orders             = $xmlOrdersListTable->getOrdersData();

        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        $orderToSearch = \WcElectronInvoice\Functions\filterInput($_GET, 'order_search', FILTER_SANITIZE_NUMBER_INT);

        // Notice
        $this->notice();
        // List table.
        echo '<div class="wrap">';
        echo '<form id="wp-list-table-invoice-form" method="post">';
        echo '<!-- filters_wrap --><div class="filters_wrap">';

        echo '<!-- date_type_state --><div class="filter-line date_type_state">';
        echo '<div class="filter-selects">';
        $this->bulkActions($orders);
        echo '</div>';
        echo '</div><!-- /date_type_state -->';

        echo '<!-- search --><div class="filter-line search">';
        $searchButton      = esc_html__('Search', WC_EL_INV_TEXTDOMAIN);
        $searchPlaceholder = esc_html__('Order or invoice number', WC_EL_INV_TEXTDOMAIN);
        $adminUrl          = admin_url() . "admin.php?page=wc_el_inv-options-page&tab=xml";
        echo "<label id='wc_el_inv_order_search_label' for='wc_el_inv_order_search'>";
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo "<input id='wc_el_inv_order_search' type='search' name='wc_el_inv_order_search' value='{$orderToSearch}' title='{$searchPlaceholder}' placeholder='{$searchPlaceholder}'>";
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo "<a href='{$adminUrl}' class='wc_el_inv_order_search_trigger button button-secondary'><span class='dashicons dashicons-search'></span> {$searchButton}</a></label>";
        echo '</div><!-- /search -->';

        echo '</div><!-- /filters_wrap -->';

        // Summary
        echo '<!-- summary-data --><div class="summary-data">';
        $summaryTitle = esc_html__('Summary', WC_EL_INV_TEXTDOMAIN);
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo "<h3>{$summaryTitle}</h3>";
        $data        = $this->summaryData();
        $labelLines  = esc_html__('Totals:', WC_EL_INV_TEXTDOMAIN);
        $labelSent   = esc_html__('Sent:', WC_EL_INV_TEXTDOMAIN);
        $labelNoSent = esc_html__('No Sent:', WC_EL_INV_TEXTDOMAIN);
        $lineCount   = XmlOrderListTable::$filteredListCount;
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo "<p class='count-sent'>{$labelLines}<strong> {$lineCount}</strong></p>";
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo "<p class='count-sent'>{$labelSent}<strong> {$data->sent}</strong></p>";
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo "<p class='count-no-sent'>{$labelNoSent}<strong> {$data->noSent}</strong></p>";

        $level = \WcElectronInvoice\Wizard::popGetUserLevel();
        if (\WcElectronInvoice\Wizard::isUserLevelGte($level, 'growth')) {
            $docCount = sprintf('<span class="dashicons dashicons-media-archive"></span>%s <b>%s</b>.',
                __('Documents ready for download:', WC_EL_INV_TEXTDOMAIN),
                $lineCount
            );
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo '<div class="pop-progress" id="progress-container"><span>' . $docCount . '</span><div id="progress-bar"></div></div>';
        }

        $tempZip = glob(
            Plugin::getPluginDirPath('/') . '/tempZip/*'
        );
        if (! empty($tempZip)) {
            $fileInfo = pathinfo($tempZip[0]);
            if ('zip' === $fileInfo['extension']) {
                $url       = Plugin::getPluginDirUrl('/tempZip') . "/{$fileInfo['filename']}.{$fileInfo['extension']}";
                $label     = esc_html__('Last Download', WC_EL_INV_TEXTDOMAIN);
                $filename  = esc_attr($fileInfo['filename']);
                $extension = esc_attr($fileInfo['extension']);
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                echo "<hr><strong>{$label}:</strong> <a class='last-download' href='{$url}'><span><i class='dashicons dashicons-media-archive'></i> {$filename}.{$extension}</span></a>";
            }
        }
        echo '</div><!-- /summary-data -->';

        $xmlOrdersListTable->prepare_items();
        $xmlOrdersListTable->display();
        echo '</form>';
        echo '</div>'; // wrap
    }
}
