<?php
/**
 * Pro trial promo banner when no active license or trial.
 *
 * @package Maca_Menu_List_Pro
 */

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

/**
 * Site-wide admin banner to start a free Pro trial.
 */
class Maca_MenuList_Pro_Trial_Promo_Banner {

    const DISMISS_OPTION = 'maca_menulist_pro_trial_banner_dismissed';
    const CRON_HOOK = 'maca_menulist_pro_trial_promo_refresh';
    const VERSION_OPTION = 'maca_menulist_trial_promo_version';

    /**
     * @var bool
     */
    private static $bootstrapped = false;

    /**
     * @return void
     */
    public static function bootstrap() {
        if (self::$bootstrapped) {
            return;
        }
        self::$bootstrapped = true;

        add_action('admin_notices', array(__CLASS__, 'render_banner'), 5);
        add_action('admin_init', array(__CLASS__, 'handle_dismiss'));
        add_action('admin_init', array(__CLASS__, 'maybe_refresh_in_admin'), 1);
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_styles'));

        add_action(self::CRON_HOOK, array(__CLASS__, 'cron_refresh'));

        self::maybe_schedule_cron();
    }

    /**
     * Refresh trial status on admin load (install, update, or missing cache).
     *
     * @return void
     */
    public static function maybe_refresh_in_admin() {
        if (!self::should_contact_server()) {
            return;
        }

        $stored_version = (string) get_option(self::VERSION_OPTION, '');
        $version_changed = $stored_version !== MACA_MENULIST_VERSION;

        if ($version_changed) {
            update_option(self::VERSION_OPTION, MACA_MENULIST_VERSION, false);
            delete_transient(Maca_MenuList_License::TRANSIENT_PREFIX . 'trial_eligibility');
            delete_transient(Maca_MenuList_License::TRANSIENT_PREFIX . 'trial_config');
            self::refresh_from_server(true);
            self::maybe_schedule_cron();
            return;
        }

        if (false === get_transient(Maca_MenuList_License::TRANSIENT_PREFIX . 'trial_eligibility')) {
            self::refresh_from_server(true);
            self::maybe_schedule_cron();
        }
    }

    /**
     * @return void
     */
    public static function on_plugin_activate() {
        delete_option(self::DISMISS_OPTION);
        update_option(self::VERSION_OPTION, MACA_MENULIST_VERSION, false);
        delete_transient(Maca_MenuList_License::TRANSIENT_PREFIX . 'trial_eligibility');
        delete_transient(Maca_MenuList_License::TRANSIENT_PREFIX . 'trial_config');
        self::refresh_from_server(true);
        self::maybe_schedule_cron();
    }

    /**
     * @return void
     */
    public static function on_plugin_deactivate() {
        self::unschedule_cron();
    }

    /**
     * @return void
     */
    public static function cron_refresh() {
        self::refresh_from_server(true);
        self::maybe_schedule_cron();
    }

    /**
     * @return bool
     */
    public static function should_contact_server() {
        if (!class_exists('Maca_MenuList_License')) {
            return false;
        }

        $license = Maca_MenuList_License::instance();

        return !$license->is_active();
    }

    /**
     * @return bool
     */
    public static function should_display() {
        if (!function_exists('maca_menulist_user_can_manage_plugin')
            || !maca_menulist_user_can_manage_plugin()
            || !self::should_contact_server()) {
            return false;
        }

        if (get_option(self::DISMISS_OPTION, '0') === '1') {
            return false;
        }

        $cache_key = Maca_MenuList_License::TRANSIENT_PREFIX . 'trial_eligibility';
        $status    = self::get_eligibility_status(false === get_transient($cache_key));

        return !empty($status['eligible']) && !empty($status['enabled']);
    }

    /**
     * @param bool $force_refresh Skip cache.
     * @return array{eligible:bool,enabled:bool,days:int,message:string}
     */
    public static function get_eligibility_status($force_refresh = false) {
        $default = array(
            'eligible' => false,
            'enabled'  => false,
            'days'     => 30,
            'message'  => '',
        );

        if (!class_exists('Maca_MenuList_License')) {
            return $default;
        }

        return Maca_MenuList_License::instance()->get_trial_eligibility($force_refresh);
    }

    /**
     * @param bool $force_refresh Skip cache.
     * @return array{eligible:bool,enabled:bool,days:int,message:string}|null
     */
    public static function refresh_from_server($force_refresh = false) {
        if (!self::should_contact_server()) {
            self::unschedule_cron();
            return null;
        }

        return self::get_eligibility_status($force_refresh);
    }

    /**
     * @return void
     */
    public static function handle_dismiss() {
        if (!function_exists('maca_menulist_user_can_manage_plugin')
            || !maca_menulist_user_can_manage_plugin()) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!isset($_GET['maca_dismiss_pro_trial_banner'])) {
            return;
        }

        check_admin_referer('maca_dismiss_pro_trial_banner');
        update_option(self::DISMISS_OPTION, '1', false);
        wp_safe_redirect(remove_query_arg(array('maca_dismiss_pro_trial_banner', '_wpnonce')));
        exit;
    }

    /**
     * @return void
     */
    public static function enqueue_styles() {
        if (!self::should_display()) {
            return;
        }

        wp_enqueue_style(
            'maca-menulist-admin',
            MACA_MENULIST_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            MACA_MENULIST_VERSION
        );
    }

    /**
     * @return string
     */
    private static function get_subscription_url() {
        return admin_url('admin.php?page=maca-restu-subscription');
    }

    /**
     * @return void
     */
    public static function render_banner() {
        if (!self::should_display()) {
            return;
        }

        $status = self::get_eligibility_status();
        $days   = (int) $status['days'];
        $subscription_url = self::get_subscription_url();
        $dismiss_url = wp_nonce_url(
            add_query_arg('maca_dismiss_pro_trial_banner', '1'),
            'maca_dismiss_pro_trial_banner'
        );
        ?>
        <div class="maca-ml-pro-trial-banner" role="region" aria-label="<?php esc_attr_e('maca Restu Pro free trial', 'maca-restu-pro'); ?>">
            <div class="maca-ml-pro-trial-banner__inner">
                <div class="maca-ml-pro-trial-banner__badge" aria-hidden="true">Pro</div>
                <div class="maca-ml-pro-trial-banner__content">
                    <p class="maca-ml-pro-trial-banner__title">
                        <?php
                        echo esc_html(
                            sprintf(
                                /* translators: %d: trial days */
                                __('Gratis Pro-testperiod — %d dagar', 'maca-restu-pro'),
                                (int) $days
                            )
                        );
                        ?>
                    </p>
                    <p class="maca-ml-pro-trial-banner__text">
                        <?php esc_html_e(
                            'Prova onlinemeny, bordsbeställning, bokning, betalning och flerspråk gratis. Erbjuds en gång per webbplats — starta under Prenumeration.',
                            'maca-restu-pro'
                        ); ?>
                    </p>
                </div>
                <div class="maca-ml-pro-trial-banner__actions">
                    <a class="button button-primary button-hero" href="<?php echo esc_url($subscription_url); ?>">
                        <?php
                        echo esc_html(
                            sprintf(
                                /* translators: %d: trial days */
                                __('Starta gratis test (%d dagar)', 'maca-restu-pro'),
                                (int) $days
                            )
                        );
                        ?>
                    </a>
                    <a class="button" href="<?php echo esc_url($dismiss_url); ?>">
                        <?php esc_html_e('Dölj', 'maca-restu-pro'); ?>
                    </a>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * @return void
     */
    private static function maybe_schedule_cron() {
        if (!self::should_contact_server()) {
            self::unschedule_cron();
            return;
        }

        if (!wp_next_scheduled(self::CRON_HOOK)) {
            wp_schedule_event(time() + MINUTE_IN_SECONDS, 'twicedaily', self::CRON_HOOK);
        }
    }

    /**
     * @return void
     */
    private static function unschedule_cron() {
        $timestamp = wp_next_scheduled(self::CRON_HOOK);
        while ($timestamp) {
            wp_unschedule_event($timestamp, self::CRON_HOOK);
            $timestamp = wp_next_scheduled(self::CRON_HOOK);
        }
    }
}
