<?php
/**
 * Admin: subscription and license management.
 *
 * @package Maca_Menu_List_Pro
 */

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

class Maca_MenuList_Pro_Admin_Subscription {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_menu', array($this, 'register_menu'), 99);
        add_action('admin_notices', array($this, 'admin_notices'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));
    }

    /**
     * Admin notices.
     */
    public function admin_notices() {
        if (!maca_menulist_user_can_manage_secrets()) {
            return;
        }

        if ($this->is_free_plugin_active()) {
            echo '<div class="notice notice-error"><p>';
            esc_html_e('Avaktivera gratisversionen av maca Restu innan du använder maca Restu Pro.', 'maca-restu-pro');
            echo '</p></div>';
        }
    }

    /**
     * Whether the free plugin is active (not this Pro install).
     *
     * Pro release ZIP uses folder maca-restu/ like the free plugin, so we cannot
     * rely on is_plugin_active('maca-restu/maca-restu.php') alone.
     *
     * @return bool
     */
    private function is_free_plugin_active() {
        if (!function_exists('get_plugins') || !function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $pro_basename = plugin_basename(
            defined('MACA_MENULIST_PLUGIN_FILE')
                ? MACA_MENULIST_PLUGIN_FILE
                : MACA_MENULIST_PLUGIN_DIR . 'maca-restu-pro.php'
        );

        foreach (get_plugins() as $plugin_file => $plugin_data) {
            if (!is_plugin_active($plugin_file)) {
                continue;
            }

            if ($plugin_file === $pro_basename) {
                continue;
            }

            $name = isset($plugin_data['Name']) ? $plugin_data['Name'] : '';
            if (stripos($name, 'maca Restu') === false) {
                continue;
            }

            if (stripos($name, 'pro') !== false) {
                continue;
            }

            return true;
        }

        return false;
    }

    /**
     * Register subscription submenu.
     */
    public function register_menu() {
        add_submenu_page(
            'maca-restu',
            __('Prenumeration', 'maca-restu-pro'),
            __('Prenumeration', 'maca-restu-pro'),
            maca_menulist_admin_required_cap(),
            'maca-restu-subscription',
            array($this, 'render_page')
        );
    }

    /**
     * @param string $hook Hook suffix.
     */
    public function enqueue_scripts($hook) {
        if ($hook !== 'maca-restu_page_maca-restu-subscription') {
            return;
        }

        wp_enqueue_script(
            'maca-menulist-pro-license',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/pro-license.js',
            array('jquery'),
            MACA_MENULIST_VERSION,
            true
        );

        wp_localize_script(
            'maca-menulist-pro-license',
            'macaMenulistProLicense',
            array(
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce'   => wp_create_nonce('maca_menulist_license'),
                'strings' => array(
                    'activating'   => __('Aktiverar…', 'maca-restu-pro'),
                    'deactivating' => __('Tar bort…', 'maca-restu-pro'),
                    'startingTrial'=> __('Startar testperiod…', 'maca-restu-pro'),
                    'error'        => __('Något gick fel. Försök igen.', 'maca-restu-pro'),
                ),
            )
        );
    }

    /**
     * Render subscription page.
     */
    public function render_page() {
        $license       = Maca_MenuList_License::instance();
        $data          = $license->get_stored_license();
        $is_active     = maca_menulist_pro_is_active();
        $is_trial          = $license->is_trial_license($data);
        $trial_eligibility = $license->get_trial_eligibility();
        $subscribe_url     = $license->get_subscribe_url();
        $features      = maca_menulist_pro_get_features();

        ?>
        <div class="wrap maca-pro-subscription-wrap">
            <h1><?php esc_html_e('maca Restu Pro – Prenumeration', 'maca-restu-pro'); ?></h1>

            <p class="description">
                <?php esc_html_e('Alla funktioner från gratispluginet maca Restu ingår och fungerar utan licens. Koppla en prenumeration för att låsa upp Pro-funktioner.', 'maca-restu-pro'); ?>
            </p>

            <?php if (function_exists('maca_menulist_pro_pricing_get_summary_html')) : ?>
                <div class="notice notice-info inline" style="margin:16px 0;max-width:720px;">
                    <p><?php echo maca_menulist_pro_pricing_get_summary_html(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped in helper. ?></p>
                </div>
            <?php endif; ?>

            <?php
            if (
                $is_active
                && function_exists('maca_menulist_onboarding_is_active')
                && maca_menulist_onboarding_is_active()
                && function_exists('maca_menulist_onboarding_get_admin_url')
            ) :
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only return step.
                $return_step = isset($_GET['maca_onboarding_return'])
                    ? sanitize_key(wp_unslash($_GET['maca_onboarding_return']))
                    : 'menu_type';
                if ($return_step === '') {
                    $return_step = 'menu_type';
                }
                ?>
                <div class="notice notice-success inline" style="margin:16px 0;max-width:720px;">
                    <p>
                        <?php esc_html_e('Licensen är aktiv.', 'maca-restu-pro'); ?>
                        <a href="<?php echo esc_url(maca_menulist_onboarding_get_admin_url($return_step)); ?>">
                            <?php esc_html_e('Tillbaka till Kom igång-guiden', 'maca-restu-pro'); ?>
                        </a>
                        <?php esc_html_e('för att välja onlinemeny.', 'maca-restu-pro'); ?>
                    </p>
                </div>
            <?php endif; ?>

            <div class="maca-pro-subscription-grid" style="display:flex;gap:24px;flex-wrap:wrap;margin-top:20px;">
                <div class="card" style="flex:1;min-width:280px;max-width:480px;padding:20px;">
                    <h2><?php esc_html_e('Din licens', 'maca-restu-pro'); ?></h2>

                    <?php if ($is_active) : ?>
                        <p class="maca-license-status" style="color:#00a32a;font-weight:600;">
                            <?php echo $is_trial ? esc_html__('Pro-testperiod aktiv', 'maca-restu-pro') : esc_html__('Aktiv', 'maca-restu-pro'); ?>
                        </p>
                        <?php if ($is_trial) : ?>
                            <p class="description">
                                <?php
                                if (!empty($data['days_remaining'])) {
                                    printf(
                                        /* translators: %d: days remaining */
                                        esc_html__('Du har %d dagar kvar av din gratis testperiod.', 'maca-restu-pro'),
                                        (int) $data['days_remaining']
                                    );
                                } else {
                                    esc_html_e('Gratis testperiod — alla Pro-funktioner är upplåsta.', 'maca-restu-pro');
                                }
                                ?>
                            </p>
                        <?php endif; ?>
                        <?php if (!empty($data['plan'])) : ?>
                            <p><strong><?php esc_html_e('Plan:', 'maca-restu-pro'); ?></strong> <?php echo esc_html($data['plan']); ?></p>
                        <?php endif; ?>
                        <?php if (!empty($data['expires'])) : ?>
                            <p><strong><?php esc_html_e('Förnyas / går ut:', 'maca-restu-pro'); ?></strong> <?php echo esc_html($data['expires']); ?></p>
                        <?php endif; ?>
                        <?php
                        $comp_notice = $license->get_comp_expiry_notice_context();
                        if ($comp_notice !== null) :
                            $days_left = (int) $comp_notice['days_left'];
                            ?>
                            <p class="maca-license-comp-countdown" style="color:#996800;font-weight:600;">
                                <?php
                                if ($days_left === 0) {
                                    printf(
                                        /* translators: %s: expiration date */
                                        esc_html__('Komplicensen går ut idag (%s).', 'maca-restu-pro'),
                                        esc_html($comp_notice['expires_label'])
                                    );
                                } elseif ($days_left === 1) {
                                    printf(
                                        /* translators: %s: expiration date */
                                        esc_html__('Komplicensen går ut om 1 dag (%s).', 'maca-restu-pro'),
                                        esc_html($comp_notice['expires_label'])
                                    );
                                } else {
                                    echo esc_html(
                                        sprintf(
                                            /* translators: 1: days left, 2: expiration date */
                                            __('Komplicensen går ut om %1$d dagar (%2$s).', 'maca-restu-pro'),
                                            (int) $days_left,
                                            $comp_notice['expires_label']
                                        )
                                    );
                                }
                                ?>
                            </p>
                        <?php endif; ?>
                        <?php if (!empty($data['customer_email'])) : ?>
                            <p><strong><?php esc_html_e('Konto:', 'maca-restu-pro'); ?></strong> <?php echo esc_html($data['customer_email']); ?></p>
                        <?php endif; ?>
                        <p>
                            <button type="button" class="button" id="maca-deactivate-license">
                                <?php echo $is_trial ? esc_html__('Avsluta testperiod på den här sajten', 'maca-restu-pro') : esc_html__('Ta bort licens från den här sajten', 'maca-restu-pro'); ?>
                            </button>
                        </p>
                        <p class="description" id="maca-license-message"></p>
                    <?php else : ?>
                        <p class="maca-license-status">
                            <?php esc_html_e('Ingen prenumeration är kopplad till den här sajten ännu.', 'maca-restu-pro'); ?>
                        </p>

                        <?php if (!empty($trial_eligibility['enabled']) && !empty($trial_eligibility['eligible'])) : ?>
                            <p>
                                <button type="button" class="button button-secondary button-hero" id="maca-start-trial">
                                    <?php
                                    printf(
                                        /* translators: %d: trial days */
                                        esc_html__('Starta gratis Pro-test (%d dagar)', 'maca-restu-pro'),
                                        (int) $trial_eligibility['days']
                                    );
                                    ?>
                                </button>
                            </p>
                            <p class="description">
                                <?php esc_html_e('En engångs-testperiod per webbplats. Giltighetstid och tillgänglighet styrs av maca.se — du kan inte förlänga eller starta om testperioden lokalt.', 'maca-restu-pro'); ?>
                            </p>
                        <?php endif; ?>

                        <?php if ($subscribe_url !== '') : ?>
                            <p>
                                <a class="button button-primary button-hero" href="<?php echo esc_url($subscribe_url); ?>" target="_blank" rel="noopener noreferrer">
                                    <?php esc_html_e('Prenumerera med Stripe', 'maca-restu-pro'); ?>
                                </a>
                            </p>
                        <p class="description">
                            <?php esc_html_e('Efter köp får du en licensnyckel via e-post. Klistra in den nedan för att koppla sajten till din prenumeration.', 'maca-restu-pro'); ?>
                        </p>
                        <?php endif; ?>

                        <p>
                            <label for="maca-license-key"><strong><?php esc_html_e('Licensnyckel', 'maca-restu-pro'); ?></strong></label><br>
                            <input type="text" id="maca-license-key" class="regular-text" style="margin-top:8px;" autocomplete="off" placeholder="XXXX-XXXX-XXXX-XXXX">
                        </p>
                        <p>
                            <button type="button" class="button button-primary" id="maca-activate-license">
                                <?php esc_html_e('Aktivera licens', 'maca-restu-pro'); ?>
                            </button>
                        </p>
                        <p class="description" id="maca-license-message"></p>
                    <?php endif; ?>
                </div>

                <div class="card" style="flex:1;min-width:280px;padding:20px;">
                    <h2><?php esc_html_e('Pro-funktioner', 'maca-restu-pro'); ?></h2>
                    <p class="description"><?php esc_html_e('Kräver aktiv prenumeration (en licens låser upp allt nedan).', 'maca-restu-pro'); ?></p>
                    <?php if (!empty($features)) : ?>
                        <ul style="list-style:disc;margin-left:20px;">
                            <?php foreach ($features as $feature) : ?>
                                <li style="margin-bottom:12px;">
                                    <strong><?php echo esc_html($feature['label']); ?></strong><br>
                                    <span class="description"><?php echo esc_html($feature['description']); ?></span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php else : ?>
                        <p class="description">
                            <?php esc_html_e('Premiumfunktioner listas här när de läggs till. Din prenumeration låser upp dem automatiskt.', 'maca-restu-pro'); ?>
                        </p>
                    <?php endif; ?>
                </div>

                <?php
                $included = function_exists('maca_menulist_pro_get_included_features')
                    ? maca_menulist_pro_get_included_features()
                    : array();
                ?>
                <?php if (!empty($included)) : ?>
                <div class="card" style="flex:1;min-width:280px;padding:20px;">
                    <h2><?php esc_html_e('Ingår i maca Restu Pro', 'maca-restu-pro'); ?></h2>
                    <p class="description"><?php esc_html_e('Tillgängligt utan prenumeration när du använder Pro-pluginet.', 'maca-restu-pro'); ?></p>
                    <ul style="list-style:disc;margin-left:20px;">
                        <?php foreach ($included as $feature) : ?>
                            <li style="margin-bottom:12px;">
                                <strong><?php echo esc_html($feature['label']); ?></strong><br>
                                <span class="description"><?php echo esc_html($feature['description']); ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
            </div>

        </div>
        <?php
    }
}
