<?php
/**
 * Utils.php
 *
 * @since      1.0.0
 * @author     POP <info@popapi.io>
 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright 2025 POP <info@popapi.io>
 *
 * 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\Functions;

use WcElectronInvoice\Admin\Settings\OptionPage;
use WooPoPToSdIPec\Plugin;
use function WcElectronInvoice\Functions\getOrderInvoiceFileProgressiveNumber;
use function WcElectronInvoice\Functions\getPaymentMethodInvoiceCode;

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

/**
 * Is WooCommerce active
 *
 * @return bool If the function WC exists.
 * @since 1.0.0
 *
 */
function isWooCommerceActive()
{
    return function_exists('WC');
}

/**
 * Filter Input
 *
 * @param array  $data    The haystack of the elements.
 * @param string $key     The key of the element within the haystack to filter.
 * @param int    $filter  The filter to use.
 * @param array  $options The option for the filter var.
 *
 * @return bool|mixed The value filtered on success false if filter fails or key doesn't exists.
 * @uses  filter_var() To filter the value.
 *
 * @since 1.0.0
 *
 */
function filterInput($data, $key, $filter = FILTER_DEFAULT, $options = array())
{
    return isset($data[$key]) ? filter_var($data[$key], $filter, $options) : false;
}

/**
 * Filter Input Array
 *
 * @param array  $data An array with string keys containing the data to filter.
 * @param array  $args An array defining the arguments. A valid key is a string
 *                     containing a variable name and a valid value is either a
 *                     filter type, or an
 *                     array optionally specifying the filter, flags and options.
 *                     If the value is an array, valid keys are filter
 *                     which specifies the filter type,
 *                     flags which specifies any flags that apply to the
 *                     filter, and options which specifies any options that
 *                     apply to the filter. See the example below for a better understanding.
 * @param string $key  The key of the element within the haystack to filter.
 *
 * @return bool|mixed
 */
function filterInputArray($data, $args, $key)
{
    return isset($data[$key]) ? filter_var_array($data, $args) : false;
}

/**
 * Is Ajax Request
 *
 * Define that this is a request made via ajax.
 * It's not the traditional WordPress ajax request, infact the DOING_AJAX is not set.
 * It's a convention that the argument passed with the ajaxAction query are made by an ajax request.
 *
 * @return bool
 * @since 1.0.0
 *
 */
function isAjaxRequest()
{
    // @codingStandardsIgnoreLine
    $action = filterInput($_POST, 'ajaxAction', FILTER_SANITIZE_SPECIAL_CHARS);

    // No ajax request ?
    if (empty($_POST) && ! (bool)$action &&
        ! defined('DOING_AJAX') ||
        (defined('DOING_AJAX') && ! DOING_AJAX)
    ) {
        return false;
    }

    return true;
}

/**
 * Is Associative Array
 *
 * @param array $array The array to know if is associative or not.
 *
 * @return bool         True if array is associative, false otherwise.
 * @since  1.0.0
 *
 */
function isArrayAssoc(array $array)
{
    return array_keys($array) !== range(0, count($array) - 1);
}

/**
 * Implode Assoc
 *
 * Implode an associative array
 *
 * @param string $glue    The string to use for separate the elements value.
 * @param string $assGlue The string to use to separate key and value.
 * @param array  $arr     The array to implode.
 *
 * @return string|bool The array imploded. False if $arr is not an array. False if $arr is not associative.
 * @since 1.0.0
 *
 */
function implodeAssoc($glue, $assGlue, $arr)
{
    if (wp_is_numeric_array($arr)) {
        return false;
    }

    // The string.
    $string = '';

    foreach ($arr as $k => $v) {
        if (! $v) {
            continue;
        }

        $string .= $k . $assGlue . $v . $glue;
    }

    // Remove the latest glue string.
    $string = rtrim($string, $glue);

    return $string;
}

/**
 * Insert an element into array in a specific position
 *
 * @param array $needle    The array to insert in.
 * @param array $haystack  The array to insert on.
 * @param mixed $pos       The key or index where the array should be inserted.
 * @param bool  $preserve  If the original value and positions should be preserved.
 * @param bool  $recursive To merge recursively or not the result array.
 *
 * @return array            The new merged array
 * @since  1.0.0
 *
 */
function arrayInsertInPos($needle, array &$haystack, $pos, $preserve = false, $recursive = false)
{
    $keys = array_filter(array_intersect(array_keys($needle), array_keys($haystack)), 'is_string');

    if (is_array($pos)) {
        list($key, $before) = $pos;
        $before = (isset($before) && true === $before) ? true : false;
        $pos    = array_search($key, array_keys($haystack), true);
        $pos    = $before ? $pos : $pos + 1;
    }

    if ($keys) {
        if ($preserve) {
            $arr =& $needle;
        } else {
            $arr =& $haystack;
        }

        foreach ($keys as $k => $v) {
            unset($arr[$v]);
        }
    }

    $start    = array_splice($haystack, 0, (int)$pos);
    $func     = $recursive ? 'array_merge_recursive' : 'array_merge';
    $haystack = call_user_func_array($func, array($start, (array)$needle, $haystack));

    return $haystack;
}

/**
 * Helper for get Wc Order class name
 *
 * @param $obj
 * @param $classname
 *
 * @return string
 *
 */
function wcOrderClassName($obj, $classname)
{
    if (isWooCommerceActive() && \WC()->version >= '4.0.1') {
        if ('\WC_Order' === $classname) {
            if ($obj instanceof \WC_Order) {
                return '\WC_Order';
            } elseif ($obj instanceof \Automattic\WooCommerce\Admin\Overrides\Order) {
                return '\Automattic\WooCommerce\Admin\Overrides\Order';
            }
        } elseif ('\WC_Order_Refund' === $classname) {
            if ($obj instanceof \WC_Order_Refund) {
                return '\WC_Order_Refund';
            } elseif ($obj instanceof \Automattic\WooCommerce\Admin\Overrides\OrderRefund) {
                return '\Automattic\WooCommerce\Admin\Overrides\OrderRefund';
            }
        } else {
            return $classname;
        }
    }

    return $classname;
}

/**
 * wcOrderInvoiceNumber
 *
 * @param $order_id
 *
 * @return string
 * @since 1.0.0
 *
 */
function wcOrderInvoiceNumber($order_id)
{
    $options = OptionPage::init();

    $order              = wc_get_order($order_id);
    $wcOrderClass       = \WcElectronInvoice\Functions\wcOrderClassName($order, '\WC_Order');
    $wcOrderRefundClass = \WcElectronInvoice\Functions\wcOrderClassName($order, '\WC_Order_Refund');

    if (! $order instanceof $wcOrderClass && ! $order instanceof $wcOrderRefundClass) {
        return '';
    }

    $number = $order->get_meta('order_number_invoice');

    // Numeration type
    $numerationType = $order->get_meta('_billing_choice_type') ?: 'invoice';

    if ('shop_order_refund' === $order->get_type()) {
        $parentOrder    = wc_get_order($order->get_parent_id());
        $numerationType = $parentOrder->get_meta('_billing_choice_type');
        $number         = $order->get_meta("refund_number_invoice-{$order_id}");
        if ('receipt' === $numerationType) {
            $numerationType = 'credit_note_receipt';
        } else {
            $numerationType = 'credit_note';
        }
    }

    // Number of digits
    $digits = $options->getOptions('number_digits_in_invoice');
    $digits = isset($digits) && '' !== $digits ? $digits : 2;
    // Prefix
    $prefix = $options->getOptions("prefix_{$numerationType}_number");

    /**
     * Invoice prefix filter
     */
    $prefix = apply_filters("wc_el_inv-prefix_{$numerationType}", $prefix, $order);

    // Suffix
    $suffix           = $options->getOptions('suffix_invoice_number');
    $suffixYear       = $options->getOptions('suffix_year_invoice_number');
    $suffixYearFormat = $options->getOptions('suffix_year_format_invoice_number') ?: 'Y';
    if ('on' === $suffixYear) {
        if ('shop_order' === $order->get_type()) {
            $created = $order->has_status('completed') ? $order->get_date_completed() : $order->get_date_created();
        } else {
            $created = $order->get_date_created();
        }
        $suffix = "/" . $created->format($suffixYearFormat);
    } else {
        $suffix = isset($suffix) && '' !== $suffix ? $suffix : '';
    }

    /**
     * Invoice suffix filter
     */
    $suffix = apply_filters('wc_el_inv-suffix_number', $suffix, $order);

    // Invoice number
    $invNumber = str_pad($number, $digits, '0', STR_PAD_LEFT);

    // Invoice number
    $number = isset($number) && 0 !== $number && '' !== $number ? "{$prefix}{$invNumber}{$suffix}" : '';

    return $number;
}

/**
 * wcOrderProgressiveFileNumber
 *
 * @param int $order_id
 *
 * @return string
 * @since 1.0.0
 *
 */
function wcOrderProgressiveFileNumber($order_id, bool $reserveNew = false)
{
    if (empty($order_id)) {
        return '';
    }

    $order = wc_get_order($order_id);
    if (! $order) {
        return '';
    }

    return getOrderInvoiceFileProgressiveNumber($order, $reserveNew);
}

/**
 * getLogConfig
 *
 * @return array
 */
function getLogConfig()
{
    $capability = property_exists(Plugin::class, 'capability') ? Plugin::$capability : 'manage_options';

    return array(
        'key'          => 'wsdipec',
        'enabled'      => defined('WP_FATT_SDI_LOG') && WP_FATT_SDI_LOG,
        'plugin_name'  => WP_FATT_SDI_NAME,
        'capability'   => $capability,
        'log_dir_slug' => 'pop-to-sdipec-log',
    );
}

/**
 * Check
 */
function addonOptions()
{
    $page = filterInput($_GET, 'page', FILTER_SANITIZE_SPECIAL_CHARS);
    $tab  = filterInput($_GET, 'tab', FILTER_SANITIZE_SPECIAL_CHARS);

    if ('wc_el_inv-options-page' === $page && 'addon' === $tab) {
        add_action('wc_el_inv-before_closing_settings_form', function () {
            if (! current_user_can(Plugin::$capability)) {
                echo sprintf('<p style="color:red">%s</p>',
                    esc_html__('POP Addon: You do not have the permissions to manage the add-on',
                        WP_FATT_SDI_PEC_TEXTDOMAIN)
                );

                return;
            }

            $out = '';
            $out .= '<!-- addon-header --><div class="addon-header">';
            $out .= sprintf('<h2>%s - v:%s</h2>',
                __('POP Addon: Fatture SdI PEC', WP_FATT_SDI_PEC_TEXTDOMAIN),
                WP_FATT_SDI_VERSION
            );
            $out .= '</div><!--/ addon-header -->';
            $out .= '<!-- addon --><div class="addon">';

            $out .= '<!-- info --><div class="info">';
            $out .= sprintf('<h4>%s</h4>',
                __('Automations:', WP_FATT_SDI_PEC_TEXTDOMAIN));

            $valueOrderStatus       = get_option('wsdipec_scheduled_order_status', 'completed');
            $valueCronJob           = get_option('wsdipec_scheduled_events');
            $valueCronJobTwiceDaily = get_option('wsdipec_scheduled_twicedaily_events');
            $sendErrorsEmail        = get_option('wsdipec_error_sending_invoice');

            $valueCronUploadJobTime = get_option('wsdipec_scheduled_events_time') ?: 12;
            $valueCronJob           = 'on' === $valueCronJob ? 'checked="checked"' : '';
            $valueCronJobTwiceDaily = 'on' === $valueCronJobTwiceDaily ? 'checked="checked"' : '';
            $sendErrorsEmail        = 'on' === $sendErrorsEmail ? 'checked="checked"' : '';

            $out .= '<input type="hidden" name="wsdipec_options" value="1">';

            // ----------------------------------------------------- //
            // Order status for cron job
            $statuses      = apply_filters('wsdipec-cron_job_statuses', [
                'completed'  => __('Completed', WP_FATT_SDI_PEC_TEXTDOMAIN),
                'processing' => __('Processing', WP_FATT_SDI_PEC_TEXTDOMAIN),
            ]);
            $selectedValue = $valueOrderStatus ?? "completed";
            $out           .= '<p><label for="wc_el_inv-settings-wsdipec_scheduled_order_status">' .
                              __('Enable auto-send for status:', WP_FATT_SDI_PEC_TEXTDOMAIN) .
                              '<select id="wc_el_inv-settings-wsdipec_scheduled_order_status" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_scheduled_order_status]">';
            foreach ($statuses as $slug => $label) {
                $selected_attr = selected($slug, $selectedValue, false);
                $out           .= '<option value="' . esc_attr($slug) . '" ' . $selected_attr . '>' . esc_html($label) . '</option>';
            }
            $out .= '</select></label></p>';
            // ----------------------------------------------------- //

            $out .= sprintf('<p><label for="wc_el_inv-settings-wsdipec_scheduled_events">' .
                            '<input id="wc_el_inv-settings-wsdipec_scheduled_events" type="checkbox" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_scheduled_events]" value="on" %s>' .
                            '%s </label></p>', $valueCronJob,
                __('Enable automatic sending', WP_FATT_SDI_PEC_TEXTDOMAIN));

            $out .= sprintf('<p><label for="wc_el_inv-settings-wsdipec_scheduled_twicedaily_events">' .
                            '<input id="wc_el_inv-settings-wsdipec_scheduled_twicedaily_events" type="checkbox" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_scheduled_twicedaily_events]" value="on" %s>' .
                            '%s </label></p>', $valueCronJobTwiceDaily,
                __('Enable automatic sending of invoices for completed orders not sent in the last 7 days. (work 2 times a day)',
                    WP_FATT_SDI_PEC_TEXTDOMAIN));

            $out .= sprintf('<p><label for="wc_el_inv-settings-wsdipec_scheduled_events_time"> %s<br>' .
                            '<input id="wc_el_inv-settings-wsdipec_scheduled_events_time" type="number" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_scheduled_events_time]" value="%s">' .
                            '</label></p>',
                __('Time in hours for automatic sending of the invoice', WP_FATT_SDI_PEC_TEXTDOMAIN),
                $valueCronUploadJobTime
            );

            $smtpPecTo = get_option('wsdipec_smtp_pec_to') ?: 'sdi20@pec.fatturapa.it';
            $out       .= sprintf("<h4>%s</h4>", __('SdI configuration:', WP_FATT_SDI_PEC_TEXTDOMAIN));
            $out       .= sprintf("<p>%s<br></p>",
                __('Se hai ricevuto un indirizzo email destintario differente, puoi sostituirlo qui',
                    WP_FATT_SDI_PEC_TEXTDOMAIN)
            );
            if ('dev' === WP_FATT_SDI_MODE) {
                $out .= sprintf("<div class='pop-notice notice-info'><p><b>%s:</b> %s</p></div>",
                    esc_html__('DEV MODE - Email to', WP_FATT_SDI_PEC_TEXTDOMAIN),
                    WP_FATT_SDI_DEV_PEC_TO ?:
                        esc_html__('Set the email with the constant WP_FATT_SDI_DEV_PEC_TO', WP_FATT_SDI_PEC_TEXTDOMAIN)
                );
            } else {
                $out .= sprintf('<p><label for="wc_el_inv-settings-wsdipec_slack_integration_token">%s<br>' .
                                '<input id="wc_el_inv-settings-wsdipec_smtp_pec_to" type="text" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_smtp_pec_to]" value="%s" placeholder="sdi20@pec.fatturapa.it">' .
                                '</label></p>',
                    __('Destinatario PEC Sistema di Interscambio', WP_FATT_SDI_PEC_TEXTDOMAIN), $smtpPecTo
                );
            }

            $out .= '</div><!--/ info -->';
            $out .= '<!-- info --><div class="info">';

            // Email
            $out .= sprintf('<h4>%s</h4>',
                __('Email:', WP_FATT_SDI_PEC_TEXTDOMAIN));
            $out .= sprintf('<p><label for="wc_el_inv-settings-wsdipec_error_sending_invoice">' .
                            '<input id="wc_el_inv-settings-wsdipec_error_sending_invoice" type="checkbox" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_error_sending_invoice]" value="on" %s>' .
                            '%s <b>(%s)</b> %s</label></p>',
                $sendErrorsEmail,
                __('Send an email to the WordPress installation administrator', WP_FATT_SDI_PEC_TEXTDOMAIN),
                get_bloginfo('admin_email'),
                __('to report the failure sending the document to the SdI via PEC', WP_FATT_SDI_PEC_TEXTDOMAIN)
            );

            $out .= '</div><!--/ info -->';
            $out .= '<!-- info --><div class="info">';

            if (WP_FATT_SDI_LOG) {
                $logConfig = getLogConfig();
                $logStatus = \WcElectronInvoice\Functions\prepareDiagnosticLog($logConfig, true);
                $out     .= sprintf('<h4>%s: <span style="color:#46b450">%s</span></h4>',
                    __('Event log ', WP_FATT_SDI_PEC_TEXTDOMAIN),
                    __('Activated', WP_FATT_SDI_PEC_TEXTDOMAIN)
                );

                $out .= sprintf('<p><code style="word-break: break-all;">%s</code></p>',
                    esc_html($logStatus['file_path'])
                );

                if (! empty($logStatus['error'])) {
                    $out .= sprintf('<p><small style="color:#b32d2e">%s</small></p>',
                        esc_html($logStatus['error'])
                    );
                }

                if ($logStatus['ready']) {
                    $out .= sprintf('<p><a target="_blank" class="log-link" href="%s"><span class="dashicons dashicons-text-page"></span> %s</a><hr></p>',
                        esc_url(\WcElectronInvoice\Functions\getDiagnosticLogViewerUrl($logConfig['key'])),
                        __('View the event log ', WP_FATT_SDI_PEC_TEXTDOMAIN)
                    );
                }
            } else {
                $out .= sprintf('<h4>%s:</h4>',
                    __('Event log ', WP_FATT_SDI_PEC_TEXTDOMAIN));
                $out .= sprintf('<p><code style="word-break: break-all;">define("WP_FATT_SDI_LOG", true);</code></p>');
                $out .= sprintf('<p><small>%s</small></p>',
                    __('Enter this code in wp-config.php to activate the event log.', WP_FATT_SDI_PEC_TEXTDOMAIN)
                );
                $out .= '<hr>';
            }

            $valueCheck   = get_option('wsdipec_slack_integration');
            $valueToken   = get_option('wsdipec_slack_integration_token');
            $valueChannel = get_option('wsdipec_slack_integration_channel');
            $valueCheck   = 'on' === $valueCheck ? 'checked="checked"' : '';

            $out .= sprintf("<h4>%s</h4>", __('Slack configuration:', WP_FATT_SDI_PEC_TEXTDOMAIN));
            $out .= sprintf("<p>%s<br><strong>%s</strong><br></p>",
                __('Create Slack APP and set OAuth & Permissions Scopes', WP_FATT_SDI_PEC_TEXTDOMAIN),
                __('Required scopes: chat:write - chat:write.customize - incoming-webhook', WP_FATT_SDI_PEC_TEXTDOMAIN)
            );

            $out .= sprintf('<p><input type="hidden" name="wsdipec_options" value="1"><label for="wc_el_inv-settings-wsdipec_slack_integration">' .
                            '<input id="wc_el_inv-settings-wsdipec_slack_integration" type="checkbox" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_slack_integration]" value="on" %s>' .
                            '%s </label></p>', $valueCheck,
                __('Enable slack integration notify', WP_FATT_SDI_PEC_TEXTDOMAIN));

            $out .= sprintf('<p><label for="wc_el_inv-settings-wsdipec_slack_integration_token">%s<br>' .
                            '<input id="wc_el_inv-settings-wsdipec_slack_integration_token" type="text" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_slack_integration_token]" value="%s">' .
                            '</label></p>', __('Slack API Token', WP_FATT_SDI_PEC_TEXTDOMAIN), $valueToken);

            $out .= sprintf('<p><label for="wc_el_inv-settings-wsdipec_slack_integration_channel">%s<br>' .
                            '<input id="wc_el_inv-settings-wsdipec_slack_integration_channel" type="text" name="wc_el_inv_options[wc_el_inv-settings-wsdipec_slack_integration_channel]" value="%s">' .
                            '</label></p>', __('Slack Channel', WP_FATT_SDI_PEC_TEXTDOMAIN), $valueChannel);

            $out .= '</div><!--/ info -->';
            $out .= '</div><!--/ addon -->';

            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $out;
        }, 50);
    }
}

/**
 * Log
 *
 * @param $message
 */
function log($message)
{
    if (\WcElectronInvoice\Functions\writeDiagnosticLog($message, getLogConfig())) {
        \WooPoPToSdIPec\Functions\slack("DEBUG: " . trim($message));
    }
}

/**
 * Slack notify
 *
 * Slack configuration:
 * Create Slack APP
 *
 * - OAuth & Permissions - Scopes
 *
 * 1. chat:write
 * 2. chat:write.customize
 * 3. incoming-webhook
 *
 * Use: \POPToSdIPec\Functions\slack('message ....', 'channel_name');
 *
 * @param string $message      The message
 * @param string $slackChannel The Slack channel (debug is a developer channel)
 * @param string $emoji        The emoji
 *
 * @return bool|string
 */
function slack($message, $slackChannel = 'debug', $emoji = ':robot_face:', $debugMessage = '')
{
    $active  = get_option('wsdipec_slack_integration');
    $token   = get_option('wsdipec_slack_integration_token');
    $channel = get_option('wsdipec_slack_integration_channel') ?? $slackChannel;

    if ('dev' === WP_FATT_SDI_MODE) {
        $message = $message . "\n\n------------\n" . "Debug" . "\n------------\n" . $debugMessage;
    }

    if ('on' === $active && '' !== $token) {
        $ch   = curl_init("https://slack.com/api/chat.postMessage");
        $data = http_build_query([
            "username"   => WP_FATT_SDI_NAME . " Bot",
            "token"      => $token,
            // "#mychannel" channel ID,
            "channel"    => $channel,
            "text"       => $emoji . " " . $message,
            // :robot_face: - :warning: - :no_entry_sign: - :dart: - :boom: - :white_check_mark:
            "icon_emoji" => ":robot_face:",
        ]);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

    return false;
}

/**
 * Get key
 *
 * @param $string
 *
 * @return array|string|string[]|null
 */
function getKey($string)
{
    return preg_replace('/\s+/', '', strtolower($string));
}

/**
 * sendEmailToAdminForInvoiceCreateError
 *
 * @param $emailBody
 * @param $orderID
 *
 * @return void
 */
function sendEmailToAdminForInvoiceCreateError($emailBody, $orderID)
{
    $sendErrorsEmail = get_option('wsdipec_error_sending_invoice');
    $adminEmail      = get_bloginfo('admin_email');
    if ('on' === $sendErrorsEmail && function_exists('wp_mail')) {
        wp_mail($adminEmail,
            sprintf(__('Error creating invoice for order: #%s', WP_FATT_SDI_PEC_TEXTDOMAIN), $orderID),
            $emailBody
        );
    }
}

/**
 * getPaymentMethodCodeByMethod
 *
 * @param $method
 *
 * @return string
 */
function getPaymentMethodCodeByMethod($method)
{
    $code = getPaymentMethodInvoiceCode($method);

    return apply_filters('wsdipec-payment_method_code', $code, $method);
}

/**
 * schedulePasswordExpiryNotifications
 *
 * @return void
 */
function schedulePasswordExpiryNotifications()
{
    $currentSmtpExpiredPassDate = get_option('wsdipec_smtp_pass_expiration', null);

    if (! $currentSmtpExpiredPassDate) {
        return;
    }

    $expiry_timestamp = strtotime($currentSmtpExpiredPassDate);

    if ($expiry_timestamp === false || $expiry_timestamp <= time()) {
        return;
    }

    clearExistingNotificationCronJobs();

    $seven_days_before = $expiry_timestamp - (7 * DAY_IN_SECONDS);
    $one_day_before    = $expiry_timestamp - DAY_IN_SECONDS;
    wp_schedule_single_event($seven_days_before, 'popSdiPec_send_password_expiry_email_7_days',
        [$currentSmtpExpiredPassDate]);
    wp_schedule_single_event($one_day_before, 'popSdiPec_send_password_expiry_email_1_day',
        [$currentSmtpExpiredPassDate]);
}

/**
 * clearExistingNotificationCronJobs
 *
 * @return void
 */
function clearExistingNotificationCronJobs()
{
    $timestamp_7_days = wp_next_scheduled('popSdiPec_send_password_expiry_email_7_days');
    $timestamp_1_day  = wp_next_scheduled('popSdiPec_send_password_expiry_email_1_day');

    if ($timestamp_7_days) {
        wp_unschedule_event($timestamp_7_days, 'popSdiPec_send_password_expiry_email_7_days');
    }
    if ($timestamp_1_day) {
        wp_unschedule_event($timestamp_1_day, 'popSdiPec_send_password_expiry_email_1_day');
    }
}

/**
 * sendEmailNotification
 *
 * @param $expiryDate
 *
 * @return void
 */
function sendEmailNotification($expiryDate)
{
    $to      = get_bloginfo('admin_email');
    $subject = esc_html__('Reminder: Your password is about to expire', WP_FATT_SDI_PEC_TEXTDOMAIN);
    $headers = array('Content-Type: text/html; charset=UTF-8');

    $message = sprintf(
        '<p>%s</p><p>%s</p><p>%s</p><p>%s</p>',
        esc_html__('Dear user,', WP_FATT_SDI_PEC_TEXTDOMAIN),
        sprintf(
            esc_html__('This is a reminder that your password will expire on %s. Please update it to avoid interruptions in the PEC invoice sending system.',
                WP_FATT_SDI_PEC_TEXTDOMAIN),
            '<strong>' . esc_html(date('F j, Y', strtotime($expiryDate))) . '</strong>'
        ),
        esc_html__('If your password expires, the system for sending invoices via PEC will stop functioning.',
            WP_FATT_SDI_PEC_TEXTDOMAIN),
        esc_html__('Thank you, Your POP Team', WP_FATT_SDI_PEC_TEXTDOMAIN)
    );

    wp_mail($to, $subject, $message, $headers);
}
