<?php
/**
 * Filters.php
 *
 * @since      1.0.0
 * @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 WooPoPToFattureAruba;

use WcElectronInvoice\Admin\Settings\OptionPage;
use function WcElectronInvoice\Functions\disableInvoiceOnOrderTotalZero;
use function WcElectronInvoice\Functions\sanMarinoSupport;
use function WooPoPToFattureAruba\Functions\filterInput;
use function WooPoPToFattureAruba\Functions\getActiveApi;
use function WooPoPToFattureAruba\Functions\wcOrderClassName;

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

/**
 * Class Filters
 *
 * @author alfiopiccione <alfio.piccione@gmail.com>
 */
class Filters
{
    /**
     * setDisable
     *
     * @param $returnBool
     *
     * @return bool|string
     */
    public static function setDisable($returnBool = false)
    {
        $disabled = '';
        $data     = getActiveApi();

        if ($data->active && $data->accessToken && $data->refreshToken) {
            $disabled = 'disabled="disabled"';
        }

        if ($returnBool) {
            return ($data->active && $data->accessToken && $data->refreshToken);
        }

        return $disabled;
    }

    /**
     * loginAction
     *
     * @return void
     */
    public static function loginAction()
    {
        $page = filterInput($_GET, 'page', FILTER_UNSAFE_RAW);
        $tab  = filterInput($_GET, 'tab', FILTER_UNSAFE_RAW);
        if (current_user_can(Plugin::$capability) && 'wc_el_inv-options-page' === $page && 'addon' === $tab) {
            $uidPl      = __('Username', WP_FATT_ARUBA_TEXTDOMAIN);
            $keyPl      = __('Password', WP_FATT_ARUBA_TEXTDOMAIN);
            $linkText   = "<span class='dashicons dashicons-admin-users'></span> " . __('Connect',
                    WP_FATT_ARUBA_TEXTDOMAIN);
            $loginText  = __('Fatture Aruba:', WP_FATT_ARUBA_TEXTDOMAIN);
            // Get current login data
            $currentApiUid = get_option('waf_api_uid');
            $currentApiKey = get_option('waf_api_key');

            $data = getActiveApi();

            // Access and Refresh token
            $expireAccessToken = $data->expireAccessToken;
            $accessToken       = $data->accessToken;
            $refreshToken      = $data->refreshToken;

            // Logged class
            $isUserLoggedInClass = ($currentApiUid && $currentApiKey && $data->active) ? 'logged' : '';

            // Api key field type
            $keyType  = $accessToken ? 'password' : 'text';
            $readOnly = $accessToken ? 'readonly' : '';

            $disabled = self::setDisable();

            $output = "<div class='waf_login'><span class='waf_login_icon {$isUserLoggedInClass}'></span>";
            $output .= '<div class="waf_login_wrap">';

            $output .= "<strong class='login_title'>{$loginText}</strong>";

            // After oauth remove fields
            if (! self::setDisable(true)) {
                $oauthUrl = OAUTH_URL;
                $output   .= "<input {$readOnly} id='waf_api_url' type='hidden' value='{$oauthUrl}' name='api_url'>";
                $output   .= "<input {$readOnly} id='waf_api_uid' type='text' value='{$currentApiUid}' name='api_uid' placeholder='{$uidPl}'>";
                $output   .= "<input {$readOnly} id='waf_api_key' type='{$keyType}' value='{$currentApiKey}' name='api_key' placeholder='{$keyPl}'>";
                $output   .= "<a {$disabled} href='javascript:;' class='api-action button button-primary' id='api_oauth'>{$linkText}</a>";
            } else {
                $linkText   = __('Logout', WP_FATT_ARUBA_TEXTDOMAIN);
                $logoutLink = admin_url('admin.php?page=wc_el_inv-options-page&tab=general&waf_reset_login=1');
                $output     .= "<a href='{$logoutLink}' class='logout button button-primary'> {$linkText}</a>";
            }

            if ($data->active) {
                if ($accessToken && $refreshToken) {

                    $expiredDateString = '';
                    if ($expireAccessToken) {
                        try {
                            $timeZone = new TimeZone();
                            $timeZone = new \DateTimeZone($timeZone->getTimeZone()->getName());

                            // Set expired date time
                            $expiredDateTime = new \DateTime();
                            $expiredDateTime->setTimestamp($expireAccessToken);
                            $expiredDateTime->setTimezone($timeZone);
                            $expiredDate = $expiredDateTime->format('d-m-Y H:i');

                            // Get now date time
                            $now = new \DateTime('now');
                            $now->setTimezone($timeZone);

                            $expiredDateString = sprintf('<p><strong>%s:</strong> %s</p>',
                                __('Expiration', WP_FATT_ARUBA_TEXTDOMAIN),
                                $expiredDate
                            );
                        } catch (\Exception $e) {
                            /* ... */
                        }
                    }

                    $output .= $disabled !== '' ? sprintf('<div class="valid_access"><strong>%s</strong>%s<textarea class="token">%s</textarea><a id="api_refresh_oauth_token" href="javascript:;" class="button button-primary" data-refresh="%s">%s</a></div>',
                        __('Access Token:', WP_FATT_ARUBA_TEXTDOMAIN),
                        $expiredDateString,
                        $accessToken,
                        $refreshToken,
                        __('Refresh Token.', WP_FATT_ARUBA_TEXTDOMAIN)
                    ) : '';

                    $output .= $disabled !== '' ? sprintf('<p class="connected">%s</p>',
                        __('Connessione Attiva!', WP_FATT_ARUBA_TEXTDOMAIN)) : '';
                }
            }

            $output .= '</div>';
            $output .= '</div>';

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

    /**
     * importAction
     *
     * @param $output
     * @param $id
     * @param $item
     *
     * @return string
     */
    public static function importAction($output, $id, $item)
    {
        $key = OptionPage::getK();
        if(! $key) {
            return $output;
        }

        $provider = isset($item['order_provider']) ? $item['order_provider'] : null;
        $provider = ! $provider && isset($item['provider']) ? $item['provider'] : $provider;

        $id        = $item['id'] ?: null;
        $orderType = $item['order_type'] ?: null;

        $choiceType       = isset($item['choice_type']) && '' !== $item['choice_type'] ? $item['choice_type'] : 'invoice';
        $documentFileName = \WcElectronInvoice\Functions\getPostMeta("waf-upload_file_name", null, $id, true, 'order', $provider);
        $checkSent        = \WcElectronInvoice\Functions\getPostMeta("_invoice_sent", null, $id, true, 'order', $provider);
        $notifications    = \WcElectronInvoice\Functions\getPostMeta("waf-notifications", null, $id, true, 'order', $provider) ?: array();
        $sendingProforma  = \WcElectronInvoice\Functions\getPostMeta("waf-sending_proforma", null, $id, true, 'order', $provider);

        if ('receipt' === $choiceType) {
            return $output;
        }

        $textState        = __('State', WP_FATT_ARUBA_TEXTDOMAIN) .
                            "<span class='dashicons dashicons-info'></span>";
        $textSendPdf      = __('Pro Forma', WP_FATT_ARUBA_TEXTDOMAIN) .
                            "<span class='dashicons dashicons-pdf'></span>";
        $textNotify       = __('Notifications', WP_FATT_ARUBA_TEXTDOMAIN) .
                            "<span class='dashicons dashicons-bell'></span>";
        $text             = __('Upload', WP_FATT_ARUBA_TEXTDOMAIN) .
                            "<span class='dashicons dashicons-cloud-upload'></span>";
        $textUploaded     = __('Uploaded', WP_FATT_ARUBA_TEXTDOMAIN) .
                            "<span class='dashicons dashicons-yes-alt'></span>";
        $class            = '';
        $disabledProforma = 'disabled="disabled"';

        // Disabled if signed send
        if ('sent' === $checkSent || ($documentFileName && '' !== $documentFileName)) {
            $disabled = 'disabled="disabled"';
            $text     = $textUploaded;
            $class    = 'imported';

            // PDF send only state RC condition
            if (! empty($notifications) &&
                (array_key_exists('RC', $notifications) && isset($notifications['RC']))) {
                $disabledProforma = '';
            }

            // Private condition
            if ('private' === $item['invoice_type']
                && ! empty($notifications) &&
                (array_key_exists('MC', $notifications) && isset($notifications['MC']))) {
                $disabledProforma = '';
            }

            // Pec or sdi type 0000000 condition
            $isSdiPecEmail = (
                $item['sdi_type'] === '0000000' ||
                preg_match(\WooPoPToFattureAruba\Api::$regexPEC, $item['sdi_type']) ||
                preg_match(\WooPoPToFattureAruba\Api::$regexLEGALMAIL, $item['sdi_type']) ||
                filter_var($item['sdi_type'], FILTER_VALIDATE_EMAIL) !== false
            );

            if ($isSdiPecEmail) {
                $disabledProforma = '';
            }

            /**
             * Filter disabled send_pdf action
             */
            $disabledProforma = apply_filters('waf-disabled_proforma', $disabledProforma, $item, $notifications);

            $output .= '<div class="waf_invoice_actions_wrapper">';
            $output .= "<a {$disabled} href='javascript:;' class='{$class} api-action upload button button-primary'>{$text}</a>";
            $output .= "<a href='javascript:;' data-provider='{$provider}' data-id='{$id}' data-docname='{$documentFileName}' class='api-action button state button-primary' id='api_state_{$id}'>{$textState}</a>";
            $output .= "<a {$disabledProforma} href='javascript:;' data-provider='{$provider}' data-id='{$id}' data-docname='{$documentFileName}' class='api-action button send_pdf button-primary' id='api_send_pdf_{$id}'>{$textSendPdf}</a>";
            $output .= "<a href='javascript:;' data-provider='{$provider}' data-id='{$id}' data-docname='{$documentFileName}' class='api-action button notify button-primary' id='api_notify_{$id}'>{$textNotify}</a>";
            $output .= '</div>';

            if ($sendingProforma !== null) {
                if ($sendingProforma) {
                    $output .= sprintf("<p class='notification_proforma sent'>%s</p>",
                        __('Pro forma invoice sent', WP_FATT_ARUBA_TEXTDOMAIN)
                    );
                } else {
                    $output .= sprintf("<p class='notification_proforma not_sent'>%s</p>",
                        __('Pro forma invoice not sent', WP_FATT_ARUBA_TEXTDOMAIN)
                    );
                }
            }

            if (! empty($notifications)) {
                foreach ($notifications as $type => $notification) {
                    $timeZone = new TimeZone();
                    $timeZone = new \DateTimeZone($timeZone->getTimeZone()->getName());
                    $dateTime = new \DateTime($notification['date']);
                    $dateTime->setTimezone($timeZone);

                    $dateLabel = __('Data: ', WP_FATT_ARUBA_TEXTDOMAIN);
                    $text      = __($notification['message'], WP_FATT_ARUBA_TEXTDOMAIN);
                    $output    .= "<p class='notification_message_{$type}'><span class='date'>{$dateLabel}{$dateTime->format('d-m-Y H:i')}</span><br>{$text}</p>";
                }
            }

            return $output;
        }

        if (isset($documentFileName) && '' !== $documentFileName) {
            $disabled = self::setDisable();
        } else {
            $disabled = '';
        }

        return $output . "<a {$disabled} href='javascript:;' data-provider='{$provider}' data-id='{$id}' data-otype='{$orderType}' data-ctype='{$choiceType}' class='{$class} api-action upload button button-primary' id='api_import_{$id}'>{$text}</a>";
    }

    /**
     * deleteAction
     *
     * @param $output
     * @param $id
     * @param $item
     *
     * @return mixed|string
     */
    public static function deleteAction($output, $id, $item)
    {
        $key = OptionPage::getK();
        if(! $key) {
            return $output;
        }

        $provider = isset($item['order_provider']) ? $item['order_provider'] : null;
        $provider = ! $provider && isset($item['provider']) ? $item['provider'] : $provider;

        $id         = $item['id'] ?: null;
        $orderType  = $item['order_type'] ?: null;
        $choiceType = isset($item['choice_type']) && '' !== $item['choice_type'] ? $item['choice_type'] : 'invoice';
        $class      = '';
        $text       = __('Delete', WP_FATT_ARUBA_TEXTDOMAIN);
        $wafID      = \WcElectronInvoice\Functions\getPostMeta("waf_response_body_id_{$orderType}_{$id}", null, $id, true, 'order', $provider);
        $wafToken   = \WcElectronInvoice\Functions\getPostMeta("waf_response_body_token_{$orderType}_{$id}", null, $id, true, 'order', $provider);

        if ($wafID && $wafToken) {
            $output = $output . "<a href='javascript:;' data-provider='{$provider}' data-id='{$id}' data-otype='{$orderType}' data-ctype='{$choiceType}' data-feid='{$wafID}' data-fetoken='{$wafToken}' class='{$class} api-action delete button button-primary' id='api_delete_{$id}'>{$text}</a>";
        }

        return $output;
    }

    /**
     * WooCommerce provider only
     *
     * actionsInOrder
     *
     * @param $order
     */
    public static function actionsInOrder($order)
    {
        $key = OptionPage::getK();
        if(! $key) {
            return;
        }

        $orderClass = wcOrderClassName($order, '\WC_Order');

        if (! is_a($order, $orderClass)) {
            return;
        }

        if ('completed' !== $order->get_status() && 'processing' !== $order->get_status()) {
            return;
        }

        // No IT country return
        if (isset($order->billing['country']) && 'IT' !== $order->billing['country']) {
            return;
        }

        // Disable invoice order whit total zero
        if (disableInvoiceOnOrderTotalZero($order)) {
            return;
        }

        $choiceType = $order->get_meta('_billing_choice_type');
        if ('receipt' === $choiceType) {
            return;
        }

        $customerType = $order->get_meta('_billing_invoice_type') ?: false;
        $sanMarinoSupport = sanMarinoSupport();
        if ('private' === $customerType && 'SM' === $sanMarinoSupport->shopCountry) {
            return;
        }

        if ($order instanceof $orderClass) {
            // Title
            $text = __('Fatture Aruba', WP_FATT_ARUBA_TEXTDOMAIN);

            $output   = '<div class="waf_order_actions_wrapper">';
            $output   .= "<hr><h4>{$text}:</h4>";
            $itemDAta = array(
                'provider'    => 'woocommerce',
                'order_type'   => $order->get_type(),
                'choice_type'  => $choiceType,
                'invoice_type' => $order->get_meta('_billing_invoice_type'),
                'sdi_type'     => $order->get_meta('_billing_sdi_type'),
                'id'           => $order->get_id(),
            );

            $output .= '<div class="actions">';
            $output = self::importAction($output, $order->get_id(), $itemDAta);
            $output .= '</div></div>';

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

    /**
     * WooCommerce provider only
     *
     * refundActions
     *
     * @param $refundID
     *
     * @return void
     */
    public static function refundActions($refundID)
    {
        $key = OptionPage::getK();
        if(! $key) {
            return;
        }

        $output        = '';
        $refundOrder   = wc_get_order($refundID);
        $parentOrderID = $refundOrder->get_parent_id();
        $parentOrder   = wc_get_order($parentOrderID);

        $choiceType = $parentOrder->get_meta('_billing_choice_type');
        if ('receipt' === $choiceType) {
            return;
        }

        $customerType = $parentOrder->get_meta('_billing_invoice_type') ?: false;
        $sanMarinoSupport = sanMarinoSupport();
        if ('private' === $customerType && 'SM' === $sanMarinoSupport->shopCountry) {
            return;
        }

        $itemDAta = array(
            'provider'    => 'woocommerce',
            'order_type'  => 'shop_order_refund',
            'choice_type' => $parentOrder->get_meta('_billing_choice_type'),
            'id'          => $refundID,
        );

        // Title
        $text = __('Fatture Aruba', WP_FATT_ARUBA_TEXTDOMAIN);

        $output .= '</<tr><tr class="refund wc_el_inv__refund-invoice"><td></td><td colspan="7">';
        $output .= '<div class="waf_order_actions_wrapper">';
        $output .= "<h4>{$text} :</h4>";
        $output .= '<div class="actions">';
        $output = self::importAction($output, $refundID, $itemDAta);
        $output .= '</div></div>';
        $output .= '</td>';

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