<?php
/**
 * Filters.php
 *
 * @since      1.0.0
 * @author     POP <info@popapi.io>

 * @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 WooPoPToSdIPec;

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

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

/**
 * Class Filters
 *
 * @author POP <info@popapi.io>
 */
class Filters
{
    /**
     * setDisable
     *
     * @param $returnBool
     *
     * @return bool|string
     */
    public static function setDisable($returnBool = false)
    {
        $data = getActiveApi();

        if ($returnBool) {
            return $data->smtpConnected;
        }

        return $data->smtpConnected ? 'disabled="disabled"' : '';
    }

    /**
     * saveAction
     *
     * @return void
     */
    public static function saveAction()
    {
        $page = filterInput($_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS);
        $tab  = filterInput($_GET, 'tab', FILTER_SANITIZE_SPECIAL_CHARS);
        if (current_user_can(Plugin::$capability) && 'wc_el_inv-options-page' === $page && 'addon' === $tab) {
            $smtpUserPl   = __('Utente indirizzo PEC del mittente', WP_FATT_SDI_PEC_TEXTDOMAIN);
            $smtpPassPl   = __('Password indirizzo PEC del mittente', WP_FATT_SDI_PEC_TEXTDOMAIN);
            $smtpHostPl   = __('Server host SMTP', WP_FATT_SDI_PEC_TEXTDOMAIN);
            $smtpSecurePl = __('Tipo di autenticazione e numero della porta', WP_FATT_SDI_PEC_TEXTDOMAIN);

            $linkText  = __('Save', WP_FATT_SDI_PEC_TEXTDOMAIN);
            $loginText = __('SMTP Credentials:', WP_FATT_SDI_PEC_TEXTDOMAIN);

            // Get current login data
            $currentSmtpUser            = get_option('wsdipec_smtp_user');
            $currentSmtpPass            = get_option('wsdipec_smtp_pass');
            $currentSmtpHost            = get_option('wsdipec_smtp_host');
            $currentSmtpExpiredPassDate = get_option('wsdipec_smtp_pass_expiration');
            $currentSmtpSecure          = get_option('wsdipec_smtp_secure');

            $data = getActiveApi();

            $output = "<div class='wsdipec_login'><span class='wsdipec_login_icon'></span>";
            $output .= '<div class="wsdipec_login_wrap">';

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

            $output .= "<input id='wsdipec_smtp_user' type='text' value='{$currentSmtpUser}' name='smtp_user' placeholder='{$smtpUserPl}'>";
            $output .= "<p><label for='wsdipec_smtp_pass_expiration'><b>" .
                       esc_html__('2FA Password Expiration:', WP_FATT_SDI_PEC_TEXTDOMAIN) . "</b></label><br>" .
                       "<input name='wsdipec_smtp_pass_expiration' type='date' value='$currentSmtpExpiredPassDate' id='wsdipec_smtp_pass_expiration'><br><small>" .
                       sprintf("%s <a href='https://docs.popapi.io/it/guides/integrations/sdi-via-pec/' target='_blank'>%s</a>",
                           esc_html__('Set the expiration date for the password used for authentication. This field is optional. Make sure to create an Application Password required for two-factor authentication.',
                               WP_FATT_SDI_PEC_TEXTDOMAIN),
                           esc_html__('Check the guide to create an Application Password.', WP_FATT_SDI_PEC_TEXTDOMAIN)) . "</small></p>";
            $output .= "<input id='wsdipec_smtp_pass' type='password' value='{$currentSmtpPass}' name='smtp_pass' placeholder='{$smtpPassPl}'>";
            $output .= "<input id='wsdipec_smtp_host' type='text' value='{$currentSmtpHost}' name='smtp_host' placeholder='{$smtpHostPl}'>";
            $output .= "<select id='wsdipec_smtp_secure' type='text' name='smtp_secure'>";
            $output .= "<option value>{$smtpSecurePl}...</option>";
            $output .= "<option value='tls' " . selected($currentSmtpSecure, 'tls',
                    false) . ">TLS su porta 587</option>";
            $output .= "<option value='ssl' " . selected($currentSmtpSecure, 'ssl',
                    false) . ">SSL su porta 465</option>";
            $output .= "</select>";
            $output .= "<a href='javascript:;' class='api-action button button-primary' id='api_smtp'>{$linkText}</a>";

            $output .= $data->smtpConnected ? sprintf('<p class="connected">%s</p>',
                __('Connessione Attiva!', WP_FATT_SDI_PEC_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';
        $checkSent  = \WcElectronInvoice\Functions\getPostMeta("_invoice_sent", null, $id, true, 'order', $provider);

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

        $text     = __('Send', WP_FATT_SDI_PEC_TEXTDOMAIN) .
                    "<span class='dashicons dashicons-cloud-upload'></span>";
        $textSent = __('Sent', WP_FATT_SDI_PEC_TEXTDOMAIN) .
                    "<span class='dashicons dashicons-yes-alt'></span>";
        $class    = '';

        // Disabled if signed send
        if ('sent' === $checkSent) {
            $disabled = 'disabled="disabled"';
            $text     = $textSent;
            $class    = 'imported';

            $output .= '<div class="wsdipec_invoice_actions_wrapper">';
            $output .= "<a {$disabled} href='javascript:;' class='{$class} api-action upload button button-primary'>{$text}</a>";
            $output .= '</div>';

            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>";
    }

    /**
     * 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 SdI PEC', WP_FATT_SDI_PEC_TEXTDOMAIN);

            $output   = '<div class="wsdipec_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 SdI PEC', WP_FATT_SDI_PEC_TEXTDOMAIN);

        $output .= '</<tr><tr class="refund wc_el_inv__refund-invoice"><td></td><td colspan="7">';
        $output .= '<div class="wsdipec_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;
    }
}
