<?php

namespace fluXtore\Core\Admin\Utilities;

use fluXtore\Core\Settings\fluXtore_Gateway_Settings;
use fluXtore\Core\Settings\fluXtore_Settings;

if ( ! defined( 'ABSPATH' ) ) {
        exit;
}

if ( ! class_exists( 'fluXtore_Admin_Gateway_Dependencies' ) ) {
        class fluXtore_Admin_Gateway_Dependencies {
                /**
                 * @var self|null
                 */
                private static $instance = null;

                private function __construct() {}

                public static function init() {
                        if ( null !== self::$instance ) {
                                return;
                        }

                        self::$instance = new self();

                        add_action( 'admin_notices', [ self::$instance, 'render_notices' ] );
                }

                /**
                 * Retrieve a map of gateway dependency definitions.
                 *
                 * @return array<string,array<string,mixed>>
                 */
                public static function get_dependency_map() {
                        $definitions = fluXtore_Gateway_Settings::get_gateway_definitions();
                        $map         = [];

                        foreach ( $definitions as $gateway_id => $definition ) {
                                if ( empty( $definition['plugin'] ) ) {
                                        continue;
                                }

                                $map[ $gateway_id ] = [
                                        'id'     => $gateway_id,
                                        'option' => $definition['option'],
                                        'plugin' => $definition['plugin'],
                                        'label'  => isset( $definition['label'] ) ? $definition['label'] : ucfirst( $gateway_id ),
                                        'docs'   => isset( $definition['docs'] ) ? $definition['docs'] : '',
                                ];
                        }

                        if ( function_exists( 'apply_filters' ) ) {
                                $map = apply_filters( 'fluxtore_gateway_dependency_map', $map );
                        }

                        return $map;
                }

                public function render_notices() {
                        foreach ( self::get_dependency_map() as $definition ) {
                                $markup = self::build_notice_markup( $definition );

                                if ( '' !== $markup ) {
                                        echo $markup; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                                }
                        }
                }

                /**
                 * Build the HTML markup for a dependency notice.
                 *
                 * @param array<string,mixed> $definition Gateway definition.
                 *
                 * @return string
                 */
                public static function build_notice_markup( array $definition ) {
                        if ( ! self::is_gateway_enabled( $definition['option'] ) ) {
                                return '';
                        }

                        if ( self::is_dependency_active( $definition['plugin'] ) ) {
                                return '';
                        }

                        $action = self::resolve_dependency_action( $definition['plugin'] );

                        $heading = sprintf(
                                /* translators: 1: Gateway label, 2: Required plugin action. */
                                esc_html__( '%1$s gateway needs %2$s to be installed', 'fluxtore' ),
                                esc_html( $definition['label'] ),
                                esc_html( $action['plugin_name'] )
                        );

                        $message  = '<div class="notice notice-warning fluxtore-gateway-dependency">';
                        $message .= '<h3>' . $heading . '</h3>';
                        $message .= '<p>' . esc_html__( 'Install and activate the WooCommerce gateway plugin to unlock this checkout experience inside your funnels.', 'fluxtore' ) . '</p>';

                        if ( ! empty( $definition['docs'] ) ) {
                                $message .= '<p><a target="_blank" rel="noopener noreferrer" href="' . esc_url( $definition['docs'] ) . '">' . esc_html__( 'View setup guide', 'fluxtore' ) . '</a></p>';
                        }

                        if ( '' !== $action['url'] ) {
                                $message .= '<p><a class="button-primary" href="' . esc_url( $action['url'] ) . '">' . esc_html( $action['cta'] ) . '</a></p>';
                        }

                        $message .= '</div>';

                        return $message;
                }

                private static function is_gateway_enabled( $option_name ) {
                        $raw = fluXtore_Settings::get( $option_name, false );

                        if ( is_bool( $raw ) ) {
                                return $raw;
                        }

                        if ( is_numeric( $raw ) ) {
                                return (bool) intval( $raw );
                        }

                        if ( is_string( $raw ) ) {
                                $filtered = filter_var( $raw, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE );

                                if ( null !== $filtered ) {
                                        return $filtered;
                                }
                        }

                        return false;
                }

                private static function is_dependency_active( $plugin_file ) {
                        if ( function_exists( 'is_plugin_active' ) && is_plugin_active( $plugin_file ) ) {
                                return true;
                        }

                        return false;
                }

                private static function resolve_dependency_action( $plugin_file ) {
                        $plugin_name = dirname( $plugin_file );
                        $base        = rtrim( WP_PLUGIN_DIR, '/\\' ) . '/';
                        $file_path   = $base . $plugin_file;
                        $exists      = file_exists( $file_path );

                        if ( ! $exists ) {
                                $url = self::get_install_url( $plugin_name );
                                $cta = sprintf( esc_html__( 'Install %s', 'fluxtore' ), esc_html( $plugin_name ) );

                                return [
                                        'url'         => $url,
                                        'cta'         => $cta,
                                        'plugin_name' => $plugin_name,
                                ];
                        }

                        $url = self::get_activate_url( $plugin_file );
                        $cta = sprintf( esc_html__( 'Activate %s', 'fluxtore' ), esc_html( $plugin_name ) );

                        return [
                                'url'         => $url,
                                'cta'         => $cta,
                                'plugin_name' => $plugin_name,
                        ];
                }

                private static function get_install_url( $slug ) {
                        if ( ! function_exists( 'wp_nonce_url' ) || ! function_exists( 'add_query_arg' ) ) {
                                return '';
                        }

                        $url = add_query_arg(
                                [
                                        'action' => 'install-plugin',
                                        'plugin' => $slug,
                                ],
                                admin_url( 'update.php' )
                        );

                        return wp_nonce_url( $url, 'install-plugin_' . $slug );
                }

                private static function get_activate_url( $plugin_file ) {
                        if ( ! function_exists( 'wp_nonce_url' ) ) {
                                return '';
                        }

                        $args = 'plugins.php?action=activate&amp;plugin=' . $plugin_file . '&amp;plugin_status=all&amp;paged=1&amp;s';

                        return wp_nonce_url( $args, 'activate-plugin_' . $plugin_file );
                }
        }
}

fluXtore_Admin_Gateway_Dependencies::init();
