<?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 WooPoPToFattureInCloud;

use WcElectronInvoice\Admin\Settings\OptionPage;
use WcElectronInvoice\WooCommerce\Fields\InvoiceFields;
use function WcElectronInvoice\Functions\disableInvoiceOnOrderTotalZero;
use function WcElectronInvoice\Functions\sanMarinoSupport;
use function WooPoPToFattureInCloud\Functions\filterInput;
use function WooPoPToFattureInCloud\Functions\getActiveApi;
use function WooPoPToFattureInCloud\Functions\getDocType;
use function WooPoPToFattureInCloud\Functions\getUserAndCompanies;
use function WooPoPToFattureInCloud\Functions\getWCActiveGatewayCode;
use function WooPoPToFattureInCloud\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 ('oauth_device' === Api::$oauthFlow) {
            if ($data->accessToken && $data->refreshToken) {
                $disabled = 'disabled="disabled"';
            }

            if ($returnBool) {
                return ($data->accessToken && $data->refreshToken);
            }
        } else {
            if ($data->active && $data->oauthState && $data->oauthCode) {
                $disabled = 'disabled="disabled"';
            }

            if ($returnBool) {
                return ($data->active && $data->oauthState && $data->oauthCode);
            }
        }

        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) {
            $apiPl      = __('Api URL', WP_FATT_CLOUD_TEXTDOMAIN);
            $uidPl      = __('Client ID', WP_FATT_CLOUD_TEXTDOMAIN);
            $keyPl      = __('Client secret', WP_FATT_CLOUD_TEXTDOMAIN);
            $linkText   = "<span class='dashicons dashicons-admin-users'></span>" . __('Connect',
                    WP_FATT_CLOUD_TEXTDOMAIN);
            $loginText  = __('Fatture In Cloud', WP_FATT_CLOUD_TEXTDOMAIN);
            $loginTitle = __('Fatture In Cloud Login', WP_FATT_CLOUD_TEXTDOMAIN);
            // Get current login data
            $currentApiUrl = get_option('wfc_api_url') ?: "https://api-v2.fattureincloud.it";
            $currentApiUid = get_option('wfc_api_uid');
            $currentApiKey = get_option('wfc_api_key');

            // Exchange data for access token request
            $oauthExchange = filterInput($_GET, 'oauth_exchange', FILTER_UNSAFE_RAW);
            $openClass     = 'true' === $oauthExchange ? 'open' : '';

            $data       = getActiveApi();
            $oauthState = $data->oauthState;
            $oauthCode  = $data->oauthCode;

            // Access and Refresh token
            $expireAccessToken = $data->expireAccessToken;
            $accessToken       = $data->accessToken;
            $refreshToken      = $data->refreshToken;
            if ($accessToken && $refreshToken) {
                $openClass = '';
            }

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

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

            $disabled = self::setDisable();

            $output = '';

            if ($accessToken && $refreshToken) {
                // Error permissions
                if ('none' === getUserAndCompanies()->companyPermissions['invoices'] && 'none' === getUserAndCompanies()->companyPermissions['orders']) {
                    $output .= '<div class="wfc_error_permissions"><p>Attenzione: sembra che i permessi (Autorizzazioni) non sono stati impostati in modo corretto. si consiglia di riprovare la connessione o contattare il supporto.</p></div>';
                }
            }

            $output .= '<div id="wfc_wrapper">';
            $output .= "<div class='wfc_login {$openClass}'><span class='wfc_login_icon {$isUserLoggedInClass}'></span>";
            $output .= '<div class="wfc_login_wrap">';

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

            // After oauth remove fields
            if (! self::setDisable(true)) {

                // Read only api url
                if ('oauth_device' === Api::$oauthFlow) {
                    $readOnly = 'readonly="readonly"';
                }

                $output .= "<input {$readOnly} id='wfc_api_url' type='hidden' value='{$currentApiUrl}' name='api_url' placeholder='{$apiPl}'>";

                // Dev mode
                if ('oauth_token' === Api::$oauthFlow) {
                    $output .= "<input {$readOnly} id='wfc_api_uid' type='text' value='{$currentApiUid}' name='api_uid' placeholder='{$uidPl}'>";
                    $output .= "<input {$readOnly} id='wfc_api_key' type='{$keyType}' value='{$currentApiKey}' name='api_key' placeholder='{$keyPl}'>";
                }

                $output .= sprintf("<div class='permissions_check'><label><strong>%s</strong></label>",
                    __('Company Permissions:', WP_FATT_CLOUD_TEXTDOMAIN)
                );

                $output .= sprintf("<p class='permissions_desc'>%s</p><hr>",
                    __('Permissions allow you to create invoices or orders, *credit notes, *clients and  *receipts (optionals) on Fatture in Cloud',
                        WP_FATT_CLOUD_TEXTDOMAIN)
                );

                $output .= sprintf("<p><input class='select_type_document' id='wfc_api_scope_invoice' checked='checked' type='checkbox' value='1' name='wfc_api_scope_invoice'> %s</p>",
                    __('Invoices', WP_FATT_CLOUD_TEXTDOMAIN)
                );

                $output .= sprintf("<p>- %s -</p>",
                    __('Or', WP_FATT_CLOUD_TEXTDOMAIN)
                );

                $output .= sprintf("<p><input class='select_type_document' id='wfc_api_scope_order' type='checkbox' value='1' name='wfc_api_scope_order'> %s</p><hr>",
                    __('Orders', WP_FATT_CLOUD_TEXTDOMAIN)
                );

                $output .= sprintf("<p><input id='wfc_api_scope_credit_note' type='checkbox' value='1' name='wfc_api_scope_credit_note'>%s</p>",
                    __('Credit Note', WP_FATT_CLOUD_TEXTDOMAIN)
                );
                $output .= sprintf("<p><input id='wfc_api_scope_receipt' type='checkbox' value='1' name='wfc_api_scope_receipt'> %s%s</p>",
                    __('Issued Receipts', WP_FATT_CLOUD_TEXTDOMAIN),
                    defined('WP_FATT_CLOUD_RECEIPTS') ? ' - ' . __('Receipts', WP_FATT_CLOUD_TEXTDOMAIN) : ''
                );
                $output .= sprintf("<p><input id='wfc_api_scope_clients' type='checkbox' value='1' name='wfc_api_scope_clients'> %s</p>",
                    __('Clients', WP_FATT_CLOUD_TEXTDOMAIN)
                );

                // Stock Addon check
                if (defined('WP_FATT_CLOUD_STOCK_NAME') && class_exists('WooPoPToFattureInCloudStock\Plugin')) {
                    $output .= sprintf("<p><input id='wfc_api_scope_stock' type='checkbox' value='1' name='wfc_api_scope_stock'> %s</p>",
                        __('Stock', WP_FATT_CLOUD_TEXTDOMAIN)
                    );
                }

                $output .= "</div>";

                $output .= "<a {$disabled} href='javascript:;' class='api-action button button-primary' id='api_oauth'>{$linkText}</a>";
            } else {
                $linkText   = __('Logout', WP_FATT_CLOUD_TEXTDOMAIN);
                $logoutLink = admin_url('admin.php?page=wc_el_inv-options-page&tab=general&wfc_reset_login=1');
                $output     .= "<a href='{$logoutLink}' class='logout button button-primary'>{$linkText}</a>";
            }

            if ($data->active) {
                if (($oauthState && $oauthCode) && (! $accessToken && ! $refreshToken)) {
                    $loginText = __('Click to get the access token', WP_FATT_CLOUD_TEXTDOMAIN);
                    $linkText  = __('Get Token', WP_FATT_CLOUD_TEXTDOMAIN);
                    $output    .= "<p class='exchange'><strong class='login_exchange_title'>{$loginText}</strong>";
                    $output    .= "<a href='javascript:;' class='button button-primary' data-code='{$oauthCode}' data-cid='{$currentApiUid}' data-secret='{$currentApiKey}' id='api_oauth_token'>{$linkText}</a></p>";
                } elseif ($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_CLOUD_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_CLOUD_TEXTDOMAIN),
                        $expiredDateString,
                        $accessToken,
                        $refreshToken,
                        __('Refresh Token.', WP_FATT_CLOUD_TEXTDOMAIN)
                    ) : '';

                    $output .= $disabled !== '' ? sprintf('<p class="connected">%s</p>',
                        __('Fatture In Cloud Connected!', WP_FATT_CLOUD_TEXTDOMAIN)) : '';
                }
            }

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

            if ($accessToken && $refreshToken) {
                // Get user and companies data
                $userAndCompaniesData = getUserAndCompanies();
                if (is_object($userAndCompaniesData) && $userAndCompaniesData->userInfo) {
                    $output .= "<div class='wfc_user_info' id='{$userAndCompaniesData->userInfo->id}'>";
                    $output .= sprintf("<h3><strong>%s:</strong></h3>",
                        __('Account data', WP_FATT_CLOUD_TEXTDOMAIN));
                    $output .= sprintf("<p><strong>%s</strong> %s</p><p><strong>%s</strong> %s</p>",
                        __('Name:', WP_FATT_CLOUD_TEXTDOMAIN), $userAndCompaniesData->userInfo->name,
                        __('Email:', WP_FATT_CLOUD_TEXTDOMAIN), $userAndCompaniesData->userInfo->email
                    );

                    if (property_exists($userAndCompaniesData, 'companiesData')) {
                        $label  = __('Set the company to link', WP_FATT_CLOUD_TEXTDOMAIN);
                        $output .= "<label for='wfc_company_id'><strong>{$label}</strong><select id='wfc_company_id' name='company_id'>";
                        $output .= "<option value=''>" . __('- Select company -',
                                WP_FATT_CLOUD_TEXTDOMAIN) . "</option>";
                        foreach ($userAndCompaniesData->companiesData as $company) {
                            $selected = (int)$company->id === (int)$userAndCompaniesData->companyID ? 'selected="selected"' : '';
                            $output   .= "<option {$selected} value='{$company->id}'>{$company->name}</option>";
                        }
                        $output .= "</select></label>";

                        if ($userAndCompaniesData->companyID) {
                            $output .= sprintf('<p class="selected_company"><small>%s %s</small></p>',
                                __('Company set - ID:', WP_FATT_CLOUD_TEXTDOMAIN),
                                $userAndCompaniesData->companyID
                            );

                            // Company permissions
                            $labels            = array(
                                'clients'         => __('Clients', WP_FATT_CLOUD_TEXTDOMAIN),
                                'receipts'        => __('Receipts', WP_FATT_CLOUD_TEXTDOMAIN),
                                'issued_receipts' => __('Issued Receipts', WP_FATT_CLOUD_TEXTDOMAIN),
                                'stock'           => __('Stock', WP_FATT_CLOUD_TEXTDOMAIN),
                                'invoices'        => __('Invoices', WP_FATT_CLOUD_TEXTDOMAIN),
                                'orders'          => __('Orders', WP_FATT_CLOUD_TEXTDOMAIN),
                                'creditNote'      => __('Credit Note', WP_FATT_CLOUD_TEXTDOMAIN),
                            );
                            $permissionsString = '';
                            if (! empty($userAndCompaniesData->companyPermissions)) {
                                foreach ($userAndCompaniesData->companyPermissions as $key => $permission) {
                                    // Set none if NULL
                                    $iconsClass = null === $permission ? 'dashicons-sos' : 'dashicons-dismiss';
                                    $permission = null === $permission ? __('error',
                                        WP_FATT_CLOUD_TEXTDOMAIN) : $permission;

                                    $title = __($permission, WP_FATT_CLOUD_TEXTDOMAIN);
                                    $icons = $permission === 'write' ?
                                        "<span title='{$title}' class='dashicons dashicons-yes-alt'></span>" :
                                        "<span title='{$title}' class='dashicons {$iconsClass}'></span>";

                                    // Stock permission condition
                                    if ('stock' === $key && ! defined('WP_FATT_CLOUD_STOCK_NAME')) {
                                        continue;
                                    }

                                    if ('receipts' === $key && ! defined('WP_FATT_CLOUD_RECEIPTS')) {
                                        continue;
                                    }

                                    $permissionsString .= '<p>' . $labels[$key] . ': ' . $icons . '</p>';
                                }
                            }
                            $output .= sprintf("<label class='permissions'><strong>%s</strong>%s</label>",
                                __('Company Permissions:', WP_FATT_CLOUD_TEXTDOMAIN),
                                $permissionsString
                            );
                        } else {
                            $output .= sprintf('<p class="no_selected_company"><small>%s</small></p>',
                                __('(*) If you do not connect the company you will not be able to send invoices through the Fatture In Cloud API',
                                    WP_FATT_CLOUD_TEXTDOMAIN)
                            );
                        }
                    }

                    // Pay accounts
                    $payAccounts = Api::getPaymentAccounts();
                    // Pay account after selected
                    $payAccountSelectedActive = Api::getPaymentAccountActive();
                    $payAccountsList          = ! $payAccountSelectedActive ? $payAccounts : $payAccountSelectedActive;
                    // Pay methods
                    $payMethods = Api::getPaymentMethods();

                    if (is_array($payAccounts) && ! empty($payAccounts) && count($payAccounts) === 1 || ! empty($payAccountsList)) {
                        // Select
                        $output .= sprintf("<label><strong>%s</strong>",
                            __('Set the global payment account:', WP_FATT_CLOUD_TEXTDOMAIN)
                        );
                        $output .= '<select id="wfc_payment_methods" name="payment_methods">';
                        $output .= "<option value=''>" . __('- Select account -',
                                WP_FATT_CLOUD_TEXTDOMAIN) . "</option>";
                        foreach ($payAccounts as $key => $payAccount) {
                            $selected = $payAccountSelectedActive && ! empty($payAccountsList[$key]) && $payAccount['id'] === $payAccountsList[$key]['id'] ? 'selected="selected"' : '';
                            $output   .= "<option {$selected} value='{$payAccount['id']}'>{$payAccount['name']}</option>";
                        }
                        $output .= '</select></label>';
                    } else {
                        // Select
                        $output .= sprintf("<label><strong>%s</strong>",
                            __('Set the global payment account:', WP_FATT_CLOUD_TEXTDOMAIN)
                        );
                        $output .= '<select id="wfc_payment_methods" name="payment_methods">';
                        $output .= "<option value=''>" . __('- Select account -',
                                WP_FATT_CLOUD_TEXTDOMAIN) . "</option>";
                        foreach ($payAccounts as $payAccount) {
                            $output .= "<option value='{$payAccount['id']}'>{$payAccount['name']}</option>";
                        }
                        $output .= '</select></label>';
                    }

                    if (! empty($payMethods)) {
                        $output .= sprintf("<label><strong>%s</strong></label>",
                            __('Payment methods active on Fatture in Cloud:', WP_FATT_CLOUD_TEXTDOMAIN)
                        );
                        $output .= sprintf("<p class='mapping-payment-info'><small>%s</small></p>",
                            __('select the payment gateway and a payment account for each method',
                                WP_FATT_CLOUD_TEXTDOMAIN)
                        );
                        $output .= '<ul class="payment_methods">';

                        $selectedGlobalPayAccount = '';
                        foreach ($payAccounts as $key => $payAccount) {
                            $selected = $payAccountSelectedActive && ! empty($payAccountsList[$key]) && $payAccount['id'] === $payAccountsList[$key]['id'];
                            if ($selected) {
                                $selectedGlobalPayAccount = $payAccount['name'];
                            }
                        }

                        foreach ($payMethods as $payMethod) {
                            $output .= "<li data-eicode='{$payMethod['ei_payment_method']}' data-name='{$payMethod['name']}' id='{$payMethod['id']}'><strong>{$payMethod['name']}</strong>";

                            $enabledGateways = getWCActiveGatewayCode();
                            if (! empty($enabledGateways)) {
                                // Stored code mapping value
                                $storedCodeValue = (object)get_option("wfc_mapping_gateways__{$payMethod['id']}") ?? null;
                                $output          .= "<select id='wfc_mapping_gateways__{$payMethod['id']}' name='mapping_payment_gateways'>";
                                $output          .= "<option value=''>" . sprintf(__('- Select the WC method to connect to the FIC method "%s"',
                                        WP_FATT_CLOUD_TEXTDOMAIN), $payMethod['name']) . "</option>";
                                foreach ($enabledGateways as $code => $name) {
                                    // gateway selected
                                    $selected = is_object($storedCodeValue) && property_exists($storedCodeValue,
                                        'payGatewayCode') && "{$storedCodeValue->payGatewayCode}" === $code ? 'selected="selected"' : '';

                                    $output .= "<option {$selected} value='{$code}'>{$name}</option>";
                                }
                                $desc   = sprintf('<span class="desc">%s - %s</span>',
                                    __('Map the gateway to the method', WP_FATT_CLOUD_TEXTDOMAIN), $payMethod['name']);
                                $output .= "</select>{$desc}";
                            }

                            if (is_array($payAccounts) && ! empty($payAccounts) && count($payAccounts) > 1) {
                                // Stored mapping value
                                $storedValue = (object)get_option("wfc_mapping_payment_methods_{$payMethod['id']}") ?? null;
                                // Mapping payment method and payment account
                                $output .= "<hr><select id='wfc_mapping_payment_methods_{$payMethod['id']}' name='mapping_payment_methods'>";
                                $output .= "<option value=''>" . __('- Select account for method -',
                                        WP_FATT_CLOUD_TEXTDOMAIN) . "</option>";

                                // Var for check selected is set
                                $selectedSet = false;
                                foreach ($payAccounts as $key => $payAccount) {
                                    // payAccount selected
                                    $selected = is_object($storedValue) && property_exists($storedValue,
                                        'mappingData') && "{$storedValue->mappingData}" === "{$payMethod['id']}__{$payAccount['id']}" ? 'selected="selected"' : '';

                                    // Var for check selected is set
                                    if (! $selectedSet && '' !== $selected) {
                                        $selectedSet = true;
                                    }

                                    // Global payAccount selected
                                    if (! $selectedSet && '' === $selected && ('' !== $selectedGlobalPayAccount && $payAccount['name'] === $selectedGlobalPayAccount)) {
                                        $selected = 'selected="selected"';
                                    }

                                    $output .= "<option {$selected} value='{$payMethod['id']}__{$payAccount['id']}'>{$payAccount['name']}</option>";
                                }

                                $desc   = sprintf('<span class="desc">%s - %s</span>',
                                    __('Associate a payment account to the method', WP_FATT_CLOUD_TEXTDOMAIN),
                                    $payMethod['name']);
                                $output .= "</select>{$desc}";
                            } else {
                                $output .= sprintf('<span style="color: #c00c1c;" class="desc">(*) %s</span>',
                                    __('Payment account missing', WP_FATT_CLOUD_TEXTDOMAIN));
                            }

                            $output .= '</li>';
                        }
                        $output .= '</ul>';
                    }

                    $output = apply_filters('wfc-login_action_extra_section', $output);

                    $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;
        $docType   = getDocType($orderType);

        $choiceType     = isset($item['choice_type']) && '' !== $item['choice_type'] ? $item['choice_type'] : 'invoice';
        $documentID     = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_document_id", null, $id, true, 'order',
            $provider) ?: null;
        $documentPdfUrl = \WcElectronInvoice\Functions\getPostMeta('wfc-issued_document_pdf_url', null, $id, true,
            'order', $provider) ?: null;

        if ('credit_note' === $docType) {
            $refundOrder    = wc_get_order($id);
            $refundOrderID  = $refundOrder->get_id();
            $parentOrderID  = $refundOrder->get_parent_id();
            $documentID     = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_credit_note_{$refundOrderID}_document_id",
                null, $parentOrderID, true, 'order', $provider);
            $documentPdfUrl = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_credit_note_{$refundOrderID}_document_pdf_url",
                null, $parentOrderID, true, 'order', $provider) ?: null;
        }

        $documentReceiptID = \WcElectronInvoice\Functions\getPostMeta("wfc-receipt_document_id", null, $id, true,
            'order', $provider);
        $documentErrors    = \WcElectronInvoice\Functions\getPostMeta("wfc-create_invoice_errors", null, $id, true,
            'order', $provider);
        $orderChoiceType   = \WcElectronInvoice\Functions\getPostMeta("_billing_choice_type", null, $id, true, 'order',
            $provider) ?: 'invoice';
        $checkSent         = \WcElectronInvoice\Functions\getPostMeta("_invoice_sent", null, $id, true, 'order',
            $provider);
        $validDoc          = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_valid_document", null, $id, true,
            'order', $provider);
        $sendDoc           = \WcElectronInvoice\Functions\getPostMeta("wfc-issued_send_document", null, $id, true,
            'order', $provider);
        $sendingProforma   = \WcElectronInvoice\Functions\getPostMeta("wfc-sending_proforma", null, $id, true, 'order',
            $provider) ?: null;

        $wcClient    = isset($item['customer_id']) ? get_user_by('ID', $item['customer_id']) : null;
        $ficClientID = $wcClient instanceof \WP_User ? (int)get_user_meta($wcClient->ID, 'fic_client_id', true) : null;

        $scopes = get_option('wfc_api_scopes');
        if (false !== strpos($scopes, 'issued_documents.orders:a')) {
            $type = __('Order', WP_FATT_CLOUD_TEXTDOMAIN);
        } elseif ('receipt' === $choiceType && false !== strpos($scopes, 'issued_documents.receipts:a')) {
            $type = __('Receipt', WP_FATT_CLOUD_TEXTDOMAIN);
        } else {
            $type = __('Invoice', WP_FATT_CLOUD_TEXTDOMAIN);
        }

        if ('shop_order_refund' === $orderType) {
            $type = __('Credit note', WP_FATT_CLOUD_TEXTDOMAIN);
        }

        $text         = __('Upload', WP_FATT_CLOUD_TEXTDOMAIN);
        $textUploaded = __('Uploaded', WP_FATT_CLOUD_TEXTDOMAIN);
        $textSend     = __('Send', WP_FATT_CLOUD_TEXTDOMAIN);
        $textSent     = __('Sent', WP_FATT_CLOUD_TEXTDOMAIN);
        $textVerify   = __('Verify', WP_FATT_CLOUD_TEXTDOMAIN);
        $textDelete   = __('Delete', WP_FATT_CLOUD_TEXTDOMAIN);
        $textPdf      = __('Download PDF', WP_FATT_CLOUD_TEXTDOMAIN);

        $class = '';

        $output .= "<div>";

        // Disabled if signed send
        if ('sent' === $checkSent) {
            $disabled = 'disabled="disabled"';
            $text     = $textUploaded . '<span class="dashicons dashicons-yes-alt"></span>';
            $class    = 'imported';

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

            if ($documentPdfUrl) {
                $output .= "<a href='{$documentPdfUrl}' target='_blank' class='{$class} pdf-action button button-primary'>{$textPdf}</a>";
            }

            if (isset($documentID) && '' !== $documentID) {
                $output .= sprintf('<p class="invoices-view"><span class="dashicons dashicons-visibility"></span> <a target="_blank" href="https://secure.fattureincloud.it/invoices-view-%s">%s</a></p>',
                    $documentID,
                    __('See document on Fatture in Cloud', WP_FATT_CLOUD_TEXTDOMAIN)
                );
            }

            if (isset($documentID) && '' !== $documentID && $validDoc && 'invoice' === $orderChoiceType && ('invoice' === $docType || 'credit_note' === $docType)) {
                $output .= sprintf("<p class='notification_sdi sent'>%s</p>",
                    'credit_note' === $docType ? __('Credit note sent to the SDI',
                        WP_FATT_CLOUD_TEXTDOMAIN) : __('invoice sent to the SDI', WP_FATT_CLOUD_TEXTDOMAIN)
                );
            }

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

            return $output;
        }

        if (isset($documentID) && '' !== $documentID) {
            $disabled = self::setDisable();
            $text     = $textUploaded . '<span class="dashicons dashicons-yes-alt"></span>';
            $class    = 'imported';

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

            if ($documentPdfUrl) {
                $output .= "<a href='{$documentPdfUrl}' target='_blank' class='{$class} pdf-action button button-primary'>{$textPdf}</a>";
            }

            // Only invoice end credit_note
            if ('invoice' === $orderChoiceType && ('invoice' === $docType || 'credit_note' === $docType)) {
                // Verify
                $output .= "<a href='javascript:;' data-provider='{$provider}' data-id='{$id}' data-docid='{$documentID}' class='api-action button verify button-primary' id='api_verify_{$id}'>{$textVerify}</a>";
            }

            // Delete
            $output .= "<a href='javascript:;' data-provider='{$provider}' data-id='{$id}' data-docid='{$documentID}' class='api-action button delete button-primary' id='api_delete_{$id}'>{$textDelete}</a>";

            // Only invoice
            if ($validDoc && 'invoice' === $orderChoiceType && ('invoice' === $docType || 'credit_note' === $docType)) {
                // Send
                $disabledSend = $sendDoc ? 'disabled="disabled"' : '';
                $output       .= "<a {$disabledSend} href='javascript:;' data-provider='{$provider}' data-id='{$id}' data-docid='{$documentID}' class='api-action button send button-primary' id='api_send_{$id}'>{$textSend}</a>";
            }

            $output .= sprintf('<p class="invoices-view"><span class="dashicons dashicons-visibility"></span> <a target="_blank" href="https://secure.fattureincloud.it/invoices-view-%s">%s</a></p>',
                $documentID,
                __('See document on Fatture in Cloud', WP_FATT_CLOUD_TEXTDOMAIN)
            );

            if ($validDoc && 'invoice' === $orderChoiceType && 'invoice' === $docType) {
                if ($sendDoc) {
                    $output .= sprintf("<p class='notification_sdi sent'>%s</p>",
                        __('invoice sent to the SDI', WP_FATT_CLOUD_TEXTDOMAIN)
                    );
                }
            }

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

            if ($validDoc && ('receipt' === $orderChoiceType || 'receipt' === $choiceType)) {
                if ($documentReceiptID) {
                    $output .= sprintf("<p class='notification_receipt uploaded'>%s</p>",
                        __('Receipt uploaded', WP_FATT_CLOUD_TEXTDOMAIN)
                    );
                }
            }

            if ($ficClientID && is_int($ficClientID)) {
                $output .= sprintf("<p class='notification_client created'>%s</p>",
                    __('Customer record created', WP_FATT_CLOUD_TEXTDOMAIN)
                );
            }

            return $output;
        } else {
            $disabled = '';
        }

        $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} {$type}</a>";

        // Errors
        if ($documentErrors) {
            $output .= sprintf("<p class='notification_proforma not_sent'>%s</p>",
                __('Error uploading. check the data and try again', WP_FATT_CLOUD_TEXTDOMAIN)
            );
        }

        // Customer record
        if ($documentID && $ficClientID && is_int($ficClientID)) {
            $output .= sprintf("<p class='notification_client created'>%s</p>",
                __('Customer record created', WP_FATT_CLOUD_TEXTDOMAIN)
            );
        }

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

        $orderStatus     = $order->get_status();
        $orderChoiceType = $order->get_meta('_billing_choice_type') ?: 'invoice';
        if ('completed' !== $orderStatus && 'processing' !== $orderStatus) {
            if ('receipt' !== $orderChoiceType) {
                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;
        }

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

        if ($order instanceof $orderClass) {
            // Title
            $text = __('Fatture in cloud', WP_FATT_CLOUD_TEXTDOMAIN);

            $output = '<div class="wfc_order_actions_wrapper">';
            $output .= "<hr><h4>{$text}:</h4>";

            $choiceType = $order->get_meta('_billing_choice_type');
            $itemDAta   = array(
                'provider'    => 'woocommerce',
                'order_type'  => $order->get_type(),
                'choice_type' => $choiceType,
                'customer_id' => $order->get_customer_id(),
                'id'          => $order->get_id(),
            );

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

        $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 in cloud', WP_FATT_CLOUD_TEXTDOMAIN);

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