<?php
/**
 * Admin setup wizard (step-by-step, resume anytime).
 *
 * @package Maca_Menu_List_Pro
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/onboarding.php';
require_once MACA_MENULIST_PLUGIN_DIR . 'includes/admin-opening-hours.php';

class Maca_MenuList_Admin_Onboarding {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action('admin_init', array($this, 'sync_legacy_dismissed'), 1);
        add_action('admin_menu', array($this, 'register_menu'), 11);
        add_action('admin_init', array($this, 'handle_redirect'), 2);
        add_action('admin_init', array($this, 'handle_post'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('admin_notices', array($this, 'admin_notices'));
    }

    /**
     * Keep dismissed installs aligned with the enabled option (legacy data).
     */
    public function sync_legacy_dismissed() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        maca_menulist_onboarding_sync_dismissed_enabled();
    }

    /**
     * Register wizard submenu (hidden from reorder when completed).
     */
    public function register_menu() {
        if (!maca_menulist_onboarding_is_enabled()) {
            return;
        }

        if (maca_menulist_onboarding_is_completed() && !maca_menulist_onboarding_is_active()) {
            return;
        }

        add_submenu_page(
            'maca-restu',
            maca_menulist_ob('Kom igång', 'Getting started'),
            maca_menulist_ob('Kom igång', 'Getting started'),
            maca_menulist_admin_required_cap(),
            'maca-restu-onboarding',
            array($this, 'render_page')
        );
    }

    /**
     * One-time redirect after legal acceptance.
     */
    public function handle_redirect() {
        if (!maca_menulist_user_can_manage_plugin() || !maca_menulist_onboarding_is_active()) {
            return;
        }

        if (!get_transient(MACA_MENULIST_ONBOARDING_REDIRECT_TRANSIENT)) {
            return;
        }

        delete_transient(MACA_MENULIST_ONBOARDING_REDIRECT_TRANSIENT);

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Redirect flag only.
        if (isset($_GET['page']) && sanitize_key(wp_unslash($_GET['page'])) === 'maca-restu-onboarding') {
            return;
        }

        wp_safe_redirect(maca_menulist_onboarding_get_admin_url());
        exit;
    }

    /**
     * Handle wizard form submissions.
     */
    public function handle_post() {
        if (!isset($_POST['maca_onboarding_action'])) {
            return;
        }

        if (
            !isset($_POST['maca_onboarding_nonce'])
            || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['maca_onboarding_nonce'])), 'maca_onboarding')
        ) {
            return;
        }

        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        $action = sanitize_key(wp_unslash($_POST['maca_onboarding_action']));
        $state = maca_menulist_onboarding_get_state();

        if (empty($state['status'])) {
            $state = maca_menulist_onboarding_default_state();
        }

        $step = isset($_POST['maca_onboarding_step'])
            ? sanitize_key(wp_unslash($_POST['maca_onboarding_step']))
            : maca_menulist_onboarding_resolve_step($state);

        $draft = $this->collect_draft_from_post($state);
        $sync = maca_menulist_onboarding_sync_content_mode($state, $draft);
        $state = $sync['state'];
        $draft = $sync['draft'];
        if ($sync['changed']) {
            maca_menulist_onboarding_save_state($state);
        }

        if ($action === 'dismiss') {
            $state['status'] = 'dismissed';
            $state['draft'] = $draft;
            maca_menulist_onboarding_save_state($state);
            maca_menulist_onboarding_set_enabled(false);
            wp_safe_redirect(admin_url('admin.php?page=maca-restu-dashboard&maca_onboarding_dismissed=1'));
            exit;
        }

        if ($action === 'continue_later') {
            $state['status'] = 'active';
            $state['step'] = $step;
            $state['draft'] = $draft;
            maca_menulist_onboarding_save_state($state);
            wp_safe_redirect(admin_url('admin.php?page=maca-restu-dashboard&maca_onboarding_paused=1'));
            exit;
        }

        if ($action === 'back') {
            $prev = maca_menulist_onboarding_prev_step($step, $draft);
            if ($prev !== null) {
                $state['step'] = $prev;
            }
            $state['draft'] = $draft;
            maca_menulist_onboarding_save_state($state);
            wp_safe_redirect(maca_menulist_onboarding_get_admin_url($state['step']));
            exit;
        }

        if ($action === 'skip') {
            if (!isset($state['skipped_steps']) || !is_array($state['skipped_steps'])) {
                $state['skipped_steps'] = array();
            }
            if (!in_array($step, $state['skipped_steps'], true)) {
                $state['skipped_steps'][] = $step;
            }
            $state = maca_menulist_onboarding_mark_step_done($state, $step);
            $next = maca_menulist_onboarding_next_step($step, $draft);
            $state['step'] = $next !== null ? $next : 'complete';
            $state['draft'] = $draft;
            if ($state['step'] === 'complete') {
                $state['status'] = 'completed';
            }
            maca_menulist_onboarding_save_state($state);
            wp_safe_redirect(maca_menulist_onboarding_get_admin_url($state['step']));
            exit;
        }

        if ($action === 'next' || $action === 'finish') {
            $apply = maca_menulist_onboarding_apply_step($step, $draft);
            if (is_wp_error($apply)) {
                add_settings_error('maca_onboarding', 'maca_onboarding_error', $apply->get_error_message(), 'error');
                $state['step'] = $step;
                $state['draft'] = $draft;
                maca_menulist_onboarding_save_state($state);
                return;
            }

            $state = maca_menulist_onboarding_mark_step_done($state, $step);
            $next = maca_menulist_onboarding_next_step($step, $draft);

            if ($action === 'finish' || $next === null || $step === 'complete') {
                $state['status'] = 'completed';
                $state['step'] = 'complete';
            } else {
                $state['step'] = $next;
            }

            $state['draft'] = $draft;
            maca_menulist_onboarding_save_state($state);
            wp_safe_redirect(maca_menulist_onboarding_get_admin_url($state['step']));
            exit;
        }
    }

    /**
     * Collect draft values from POST.
     *
     * @param array<string, mixed> $state Current state.
     * @return array<string, mixed>
     */
    private function collect_draft_from_post($state) {
        $existing = isset($state['draft']) && is_array($state['draft']) ? $state['draft'] : array();
        $draft = maca_menulist_onboarding_get_form_values(array('draft' => $existing));

        if (isset($_POST['maca_onboarding_content_mode'])) {
            $draft['content_mode'] = sanitize_key(wp_unslash($_POST['maca_onboarding_content_mode']));
        }
        if (isset($_POST['maca_onboarding_restaurant_name'])) {
            $draft['restaurant_name'] = sanitize_text_field(wp_unslash($_POST['maca_onboarding_restaurant_name']));
        }
        if (isset($_POST['maca_onboarding_restaurant_email'])) {
            $draft['restaurant_email'] = sanitize_email(wp_unslash($_POST['maca_onboarding_restaurant_email']));
        }
        if (isset($_POST['maca_onboarding_restaurant_address'])) {
            $draft['restaurant_address'] = sanitize_textarea_field(wp_unslash($_POST['maca_onboarding_restaurant_address']));
        }
        if (isset($_POST['maca_onboarding_restaurant_phone'])) {
            $draft['restaurant_phone'] = sanitize_text_field(wp_unslash($_POST['maca_onboarding_restaurant_phone']));
        }
        if (isset($_POST['maca_onboarding_restaurant_website'])) {
            $draft['restaurant_website'] = esc_url_raw(wp_unslash($_POST['maca_onboarding_restaurant_website']));
        }
        if (isset($_POST['maca_onboarding_restaurant_vat_number'])) {
            $draft['restaurant_vat_number'] = sanitize_text_field(wp_unslash($_POST['maca_onboarding_restaurant_vat_number']));
        }
        if (isset($_POST['maca_onboarding_price_currency'])) {
            $draft['price_currency'] = sanitize_text_field(wp_unslash($_POST['maca_onboarding_price_currency']));
        }
        if (isset($_POST['maca_onboarding_category_name'])) {
            $draft['category_name'] = sanitize_text_field(wp_unslash($_POST['maca_onboarding_category_name']));
        }
        if (isset($_POST['maca_onboarding_dish_category'])) {
            $draft['dish_category'] = sanitize_text_field(wp_unslash($_POST['maca_onboarding_dish_category']));
        }
        if (isset($_POST['maca_onboarding_dish_title'])) {
            $draft['dish_title'] = sanitize_text_field(wp_unslash($_POST['maca_onboarding_dish_title']));
        }
        if (isset($_POST['maca_onboarding_dish_price'])) {
            $draft['dish_price'] = sanitize_text_field(wp_unslash($_POST['maca_onboarding_dish_price']));
        }

        $draft['enable_table_order'] = isset($_POST['maca_onboarding_enable_table_order'])
            ? !empty($_POST['maca_onboarding_enable_table_order'])
            : !empty($existing['enable_table_order']);
        $draft['enable_bookings'] = isset($_POST['maca_onboarding_enable_bookings'])
            ? !empty($_POST['maca_onboarding_enable_bookings'])
            : !empty($existing['enable_bookings']);
        $draft['enable_info_hub'] = isset($_POST['maca_onboarding_enable_info_hub'])
            ? !empty($_POST['maca_onboarding_enable_info_hub'])
            : !empty($existing['enable_info_hub']);

        if (isset($_POST['hours']) && is_array($_POST['hours'])) {
            $draft['hours'] = wp_unslash($_POST['hours']);
        }

        return $draft;
    }

    /**
     * Enqueue wizard assets.
     *
     * @param string $hook Admin hook.
     */
    public function enqueue_assets($hook) {
        if ($hook !== 'maca-restu_page_maca-restu-onboarding') {
            return;
        }

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

        wp_enqueue_script(
            'maca-menulist-admin-onboarding',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/admin-onboarding.js',
            array('jquery'),
            MACA_MENULIST_VERSION,
            true
        );
    }

    /**
     * Resume wizard notice on maca Restu admin screens.
     */
    public function admin_notices() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only screen detection.
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';

        if ($page === 'maca-restu-onboarding') {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Query flag for one-time message.
        if (isset($_GET['maca_onboarding_paused'])) {
            echo '<div class="notice notice-info is-dismissible"><p>';
            maca_menulist_ob_e(
                'Kom igång-guiden är pausad. Dina val sparas — fortsätt när som helst under maca Restu → Kom igång.',
                'Setup wizard paused. Your progress is saved — continue anytime under maca Restu → Getting started.'
            );
            echo '</p></div>';
            return;
        }

        if (!maca_menulist_onboarding_is_active()) {
            return;
        }

        if (!$this->is_maca_menulist_admin_screen($page)) {
            return;
        }

        $state = maca_menulist_onboarding_get_state();
        $step = maca_menulist_onboarding_resolve_step($state);
        $steps = maca_menulist_onboarding_get_steps();
        $step_label = isset($steps[ $step ]['label']) ? $steps[ $step ]['label'] : '';

        echo '<div class="notice notice-info"><p>';
        printf(
            '%1$s %2$s',
            esc_html(
                maca_menulist_ob(
                    sprintf('Kom igång-guiden pågår (%s).', $step_label),
                    sprintf('Setup wizard in progress (%s).', $step_label)
                )
            ),
            wp_kses_post(
                sprintf(
                    '<a href="%1$s">%2$s</a>',
                    esc_url(maca_menulist_onboarding_get_admin_url($step)),
                    esc_html(maca_menulist_ob('Fortsätt nu', 'Continue now'))
                )
            )
        );
        echo ' ';
        maca_menulist_ob_e(
            'Du hittar guiden under maca Restu → Kom igång.',
            'You can also open maca Restu → Getting started when you are ready.'
        );
        echo '</p></div>';
    }

    /**
     * Whether the current admin screen belongs to maca Restu.
     *
     * @param string $page Page slug.
     * @return bool
     */
    private function is_maca_menulist_admin_screen($page) {
        if ($page === '' && function_exists('get_current_screen')) {
            $screen = get_current_screen();
            if ($screen && isset($screen->id) && strpos($screen->id, 'maca-restu') !== false) {
                return true;
            }
        }

        return maca_menulist_is_maca_restu_admin_page($page);
    }

    /**
     * Trial eligibility for onboarding promo (no active Pro license).
     *
     * @return array{eligible:bool,enabled:bool,days:int,message:string}|null
     */
    private function get_onboarding_trial_eligibility() {
        if (!class_exists('Maca_MenuList_License')) {
            return null;
        }

        $license = Maca_MenuList_License::instance();
        if ($license->is_active()) {
            return null;
        }

        $status = $license->get_trial_eligibility();
        if (empty($status['eligible'])) {
            return null;
        }

        return $status;
    }

    /**
     * @param array{eligible:bool,enabled:bool,days:int,message:string} $trial Trial eligibility.
     * @param string                                                     $return_step Onboarding step for return link.
     * @return void
     */
    private function render_onboarding_trial_notice($trial, $return_step = 'menu_type') {
        $days = (int) $trial['days'];
        $subscription_url = add_query_arg(
            array(
                'maca_onboarding_return' => sanitize_key($return_step),
            ),
            admin_url('admin.php?page=maca-restu-subscription')
        );
        ?>
        <div class="notice notice-info inline maca-onboarding-inline-notice maca-onboarding-trial-notice">
            <p>
                <strong><?php maca_menulist_ob_e('Gratis Pro-testperiod', 'Free Pro trial'); ?></strong>
                —
                <?php
                echo esc_html(
                    sprintf(
                        maca_menulist_ob(
                            'Prova onlinemeny och alla Pro-funktioner gratis i %d dagar.',
                            'Try the online menu and all Pro features free for %d days.'
                        ),
                        $days
                    )
                );
                ?>
            </p>
            <p class="description">
                <?php maca_menulist_ob_e(
                    'Erbjuds en gång per webbplats. Starta testperioden under Prenumeration — efter att den löpt ut kan den inte aktiveras igen.',
                    'Offered once per website. Start the trial under Subscription — when it ends it cannot be activated again.'
                ); ?>
            </p>
            <p>
                <a class="button button-primary" href="<?php echo esc_url($subscription_url); ?>">
                    <?php
                    echo esc_html(
                        sprintf(
                            maca_menulist_ob(
                                'Starta gratis test (%d dagar)',
                                'Start free trial (%d days)'
                            ),
                            $days
                        )
                    );
                    ?>
                </a>
            </p>
        </div>
        <?php
    }

    /**
     * Message when the wizard is turned off in settings.
     */
    private function render_disabled_page() {
        ?>
        <div class="wrap maca-onboarding-wrap">
            <h1><?php maca_menulist_ob_e('Kom igång med maca Restu Pro', 'Getting started with maca Restu Pro'); ?></h1>
            <div class="notice notice-info inline">
                <p>
                    <?php
                    echo wp_kses_post(
                        sprintf(
                            maca_menulist_ob(
                                'Kom igång-guiden är avstängd. Du kan konfigurera allt under Inställningar och den fullständiga guiden. Aktivera guiden igen under %s.',
                                'The setup wizard is turned off. You can configure everything under Settings and the full guide. Turn the wizard back on under %s.'
                            ),
                            '<a href="' . esc_url(maca_menulist_onboarding_get_settings_url()) . '">' . esc_html(maca_menulist_ob('Inställningar → Restaurang', 'Settings → Restaurant')) . '</a>'
                        )
                    );
                    ?>
                </p>
            </div>
            <p>
                <a class="button button-primary" href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dashboard')); ?>">
                    <?php maca_menulist_ob_e('Gå till instrumentpanelen', 'Go to dashboard'); ?>
                </a>
                <a class="button" href="<?php echo esc_url(maca_menulist_onboarding_get_settings_url()); ?>">
                    <?php maca_menulist_ob_e('Öppna inställningar', 'Open settings'); ?>
                </a>
            </p>
        </div>
        <?php
    }

    /**
     * Render wizard page.
     */
    public function render_page() {
        if (!maca_menulist_user_can_manage_plugin()) {
            return;
        }

        if (!maca_menulist_onboarding_is_enabled()) {
            $this->render_disabled_page();
            return;
        }

        $state = maca_menulist_onboarding_get_state();
        $status = isset($state['status']) ? (string) $state['status'] : '';

        if ($status === 'dismissed') {
            $this->render_disabled_page();
            return;
        }

        if ($status === '') {
            maca_menulist_onboarding_start();
            $state = maca_menulist_onboarding_get_state();
        }

        $step = maca_menulist_onboarding_resolve_step($state);
        $values = maca_menulist_onboarding_get_form_values($state);
        $sync = maca_menulist_onboarding_sync_content_mode($state, $values);
        if ($sync['changed']) {
            $state = $sync['state'];
            $state['step'] = $step;
            maca_menulist_onboarding_save_state($state);
            $values = maca_menulist_onboarding_get_form_values($state);
        } else {
            $state['step'] = $step;
            maca_menulist_onboarding_save_state($state);
        }

        $steps = maca_menulist_onboarding_get_steps();
        $slugs = maca_menulist_onboarding_get_active_step_slugs($values);
        $progress = maca_menulist_onboarding_progress_percent($state);
        $dishes_pro_active = maca_menulist_pro_has_feature('dishes');
        $trial_eligibility = $this->get_onboarding_trial_eligibility();
        $content_mode = $values['content_mode'];
        $qr_slug = function_exists('maca_menulist_get_qr_slug') ? maca_menulist_get_qr_slug() : 'qrmeny';
        $qr_url = home_url('/' . trim($qr_slug, '/') . '/');

        ?>
        <div class="wrap maca-onboarding-wrap">
            <div class="maca-onboarding-header">
                <div>
                    <h1><?php maca_menulist_ob_e('Kom igång med maca Restu Pro', 'Getting started with maca Restu Pro'); ?></h1>
                    <p class="maca-onboarding-lead">
                        <?php maca_menulist_ob_e(
                            'Konfigurera menyn steg för steg. Du kan pausa när som helst — dina val sparas automatiskt.',
                            'Set up your menu step by step. You can pause at any time — your progress is saved automatically.'
                        ); ?>
                    </p>
                </div>
                <div class="maca-onboarding-progress" aria-hidden="true">
                    <div class="maca-onboarding-progress-bar" style="width: <?php echo esc_attr((string) $progress); ?>%;"></div>
                </div>
            </div>

            <?php settings_errors('maca_onboarding'); ?>

            <?php if (!$dishes_pro_active && is_array($trial_eligibility)) : ?>
                <?php $this->render_onboarding_trial_notice($trial_eligibility, $step); ?>
            <?php endif; ?>

            <nav class="maca-onboarding-steps" aria-label="<?php maca_menulist_ob_attr_e('Guidesteg', 'Setup steps'); ?>">
                <ol>
                    <?php
                    foreach ($slugs as $index => $slug) :
                        if ($slug === 'complete') {
                            continue;
                        }
                        $done = in_array($slug, $state['completed_steps'] ?? array(), true);
                        $current = ($slug === $step);
                        $skipped = in_array($slug, $state['skipped_steps'] ?? array(), true);
                        $can_jump = maca_menulist_onboarding_can_jump_to_step($slug, $step, $state, $values);
                        $classes = array('maca-onboarding-step-item');
                        if ($done) {
                            $classes[] = 'is-done';
                        }
                        if ($current) {
                            $classes[] = 'is-current';
                        }
                        if ($skipped) {
                            $classes[] = 'is-skipped';
                        }
                        if ($can_jump && !$current) {
                            $classes[] = 'is-clickable';
                        }
                        ?>
                        <li class="<?php echo esc_attr(implode(' ', $classes)); ?>">
                            <?php if ($can_jump && !$current) : ?>
                                <a class="maca-onboarding-step-link" href="<?php echo esc_url(maca_menulist_onboarding_get_admin_url($slug)); ?>">
                                    <span class="maca-onboarding-step-num"><?php echo esc_html((string) ($index + 1)); ?></span>
                                    <span class="maca-onboarding-step-label"><?php echo esc_html($steps[ $slug ]['label']); ?></span>
                                </a>
                            <?php else : ?>
                                <span class="maca-onboarding-step-num"><?php echo esc_html((string) ($index + 1)); ?></span>
                                <span class="maca-onboarding-step-label"><?php echo esc_html($steps[ $slug ]['label']); ?></span>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ol>
            </nav>

            <form method="post" class="maca-onboarding-form" data-content-mode="<?php echo esc_attr($content_mode); ?>">
                <?php wp_nonce_field('maca_onboarding', 'maca_onboarding_nonce'); ?>
                <input type="hidden" name="maca_onboarding_step" value="<?php echo esc_attr($step); ?>">
                <?php if ($step !== 'menu_type') : ?>
                    <input type="hidden" name="maca_onboarding_content_mode" value="<?php echo esc_attr($content_mode); ?>">
                <?php endif; ?>

                <div class="maca-onboarding-panel">
                        <?php if ($dishes_pro_active && $content_mode === 'files' && !in_array($step, array('welcome', 'menu_type'), true)) : ?>
                            <div class="notice notice-info inline maca-onboarding-inline-notice">
                                <p>
                                    <?php
                                    echo wp_kses_post(
                                        sprintf(
                                            maca_menulist_ob(
                                                'Vill du använda onlinemeny? Gå tillbaka till %s och välj onlinemeny.',
                                                'Want to use an online menu? Go back to %s and choose online menu.'
                                            ),
                                            '<a href="' . esc_url(maca_menulist_onboarding_get_admin_url('menu_type')) . '">' . esc_html(maca_menulist_ob('Menytyp', 'Menu type')) . '</a>'
                                        )
                                    );
                                    ?>
                                </p>
                            </div>
                        <?php endif; ?>

                    <?php if ($step === 'welcome') : ?>
                        <h2><?php maca_menulist_ob_e('Välkommen!', 'Welcome!'); ?></h2>
                        <p><?php maca_menulist_ob_e(
                            'Guiden hjälper dig att konfigurera maca Restu Pro för din restaurang. Grundinställningarna tar några minuter; avancerade funktioner som bordsbeställning, bokningar och betalning kan du sätta upp senare under Inställningar.',
                            'This wizard helps you configure maca Restu Pro for your restaurant. It takes a few minutes for the basics; advanced features like table ordering, bookings, and payments can be set up later in Settings.'
                        ); ?></p>
                        <ul class="maca-onboarding-list">
                            <li><?php maca_menulist_ob_e('Välj PDF/bildmenyer eller onlinemeny med enskilda rätter', 'Choose PDF/image menus or an online menu with individual dishes'); ?></li>
                            <li><?php maca_menulist_ob_e('Ange restauranguppgifter (namn, adress, kontakt)', 'Enter restaurant details (name, address, contact)'); ?></li>
                            <li><?php maca_menulist_ob_e('Ställ in veckans öppettider (valfritt)', 'Set weekly opening hours (optional)'); ?></li>
                            <li><?php maca_menulist_ob_e('Skapa menykategori och lägg till din första rätt (onlinemeny med licens)', 'Create a menu category and add your first dish (online menu with license)'); ?></li>
                            <li><?php maca_menulist_ob_e('Lär dig publicera menyn på webbplatsen och QR-sidan', 'Learn how to publish the menu on your website and QR page'); ?></li>
                        </ul>
                        <p class="description"><?php maca_menulist_ob_e(
                            'Tips: använd ”Spara och fortsätt senare” när du behöver pausa. Guiden finns kvar under maca Restu → Kom igång.',
                            'Tip: use “Save and continue later” whenever you need a break. The wizard stays under maca Restu → Getting started.'
                        ); ?></p>

                    <?php elseif ($step === 'menu_type') : ?>
                        <h2><?php maca_menulist_ob_e('Hur vill du visa menyn?', 'How do you want to show your menu?'); ?></h2>
                        <?php if ($dishes_pro_active && $content_mode === 'files') : ?>
                            <div class="notice notice-info inline maca-onboarding-inline-notice">
                                <p><?php maca_menulist_ob_e(
                                    'Du har aktiv Pro-licens — du kan välja onlinemeny nedan och fortsätta med rätter i guiden.',
                                    'You have an active Pro license — you can choose online menu below and continue with dishes in the wizard.'
                                ); ?></p>
                            </div>
                        <?php endif; ?>
                        <fieldset class="maca-onboarding-choice-group">
                            <label class="maca-onboarding-choice">
                                <input type="radio" name="maca_onboarding_content_mode" value="files" <?php checked($content_mode, 'files'); ?>>
                                <span class="maca-onboarding-choice-body">
                                    <strong><?php maca_menulist_ob_e('PDF- eller bildmenyer', 'PDF or image menus'); ?></strong>
                                    <span><?php maca_menulist_ob_e(
                                        'Ladda upp lunch-/middags-PDF:er eller bilder med schemaläggning (veckodagar, tider). Samma som gratisversionen av maca Restu.',
                                        'Upload lunch/dinner PDFs or images with scheduling (weekdays, times). Same as the free maca Restu plugin.'
                                    ); ?></span>
                                </span>
                            </label>
                            <label class="maca-onboarding-choice<?php echo $dishes_pro_active ? '' : ' is-disabled'; ?>">
                                <input type="radio" name="maca_onboarding_content_mode" value="dishes" <?php checked($content_mode, 'dishes'); ?>>
                                <span class="maca-onboarding-choice-body">
                                    <strong><?php maca_menulist_ob_e('Onlinemeny (Pro)', 'Online menu (Pro)'); ?></strong>
                                    <span><?php maca_menulist_ob_e(
                                        'Registrera rätter med kategorier, priser, bilder och allergener. Möjliggör bordsbeställning, gästbetyg med mera.',
                                        'Register dishes with categories, prices, images, and allergens. Enables table ordering, guest ratings, and more.'
                                    ); ?></span>
                                </span>
                            </label>
                        </fieldset>
                        <?php if (!$dishes_pro_active) : ?>
                            <p class="description">
                                <?php
                                $subscription_url = add_query_arg(
                                    array(
                                        'maca_onboarding_return' => 'menu_type',
                                    ),
                                    admin_url('admin.php?page=maca-restu-subscription')
                                );
                                if (is_array($trial_eligibility)) {
                                    echo wp_kses_post(
                                        sprintf(
                                            maca_menulist_ob(
                                                'Onlinemeny kräver Pro. Du kan börja med PDF-menyer och byta senare, %1$s (engångs-test) eller %2$s.',
                                                'Online menu requires Pro. You can start with PDF menus and switch later, %1$s (one-time trial) or %2$s.'
                                            ),
                                            '<a href="' . esc_url($subscription_url) . '">' . esc_html(maca_menulist_ob('starta gratis testperiod', 'start a free trial')) . '</a>',
                                            '<a href="' . esc_url($subscription_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html(maca_menulist_ob('aktivera en licens', 'activate a license')) . '</a>'
                                        )
                                    );
                                } else {
                                    echo wp_kses_post(
                                        sprintf(
                                            maca_menulist_ob(
                                                'Onlinemeny kräver Pro-prenumeration. Du kan börja med PDF-menyer och byta senare, eller %s först (sidan öppnas i ny flik).',
                                                'Online menu requires a Pro subscription. You can start with PDF menus and switch later, or %s first (opens in a new tab).'
                                            ),
                                            '<a href="' . esc_url($subscription_url) . '" target="_blank" rel="noopener noreferrer">' . esc_html(maca_menulist_ob('aktivera en licens', 'activate a license')) . '</a>'
                                        )
                                    );
                                }
                                ?>
                            </p>
                        <?php endif; ?>

                    <?php elseif ($step === 'restaurant') : ?>
                        <h2><?php maca_menulist_ob_e('Restauranguppgifter', 'Restaurant details'); ?></h2>
                        <p class="description"><?php maca_menulist_ob_e(
                            'Namn och kontaktuppgifter som visas i menyfoten, utskriftsmenyn, e-post och på webbplatsen.',
                            'Name and contact details used in the menu footer, printable menu, emails, and on the website.'
                        ); ?></p>
                        <table class="form-table" role="presentation">
                            <tr>
                                <th scope="row"><label for="maca_onboarding_restaurant_name"><?php maca_menulist_ob_e('Restaurangnamn', 'Restaurant name'); ?> <span class="required">*</span></label></th>
                                <td><input type="text" class="regular-text" id="maca_onboarding_restaurant_name" name="maca_onboarding_restaurant_name" value="<?php echo esc_attr($values['restaurant_name']); ?>" required></td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="maca_onboarding_restaurant_address"><?php maca_menulist_ob_e('Adress', 'Address'); ?></label></th>
                                <td><textarea id="maca_onboarding_restaurant_address" name="maca_onboarding_restaurant_address" rows="3" class="large-text"><?php echo esc_textarea($values['restaurant_address']); ?></textarea></td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="maca_onboarding_restaurant_phone"><?php maca_menulist_ob_e('Telefon', 'Phone'); ?></label></th>
                                <td><input type="text" class="regular-text" id="maca_onboarding_restaurant_phone" name="maca_onboarding_restaurant_phone" value="<?php echo esc_attr($values['restaurant_phone']); ?>"></td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="maca_onboarding_restaurant_email"><?php maca_menulist_ob_e('E-post', 'Email'); ?></label></th>
                                <td><input type="email" class="regular-text" id="maca_onboarding_restaurant_email" name="maca_onboarding_restaurant_email" value="<?php echo esc_attr($values['restaurant_email']); ?>" placeholder="info@example.com"></td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="maca_onboarding_restaurant_website"><?php maca_menulist_ob_e('Webbplats', 'Website'); ?></label></th>
                                <td>
                                    <input type="url" class="regular-text" id="maca_onboarding_restaurant_website" name="maca_onboarding_restaurant_website" value="<?php echo esc_attr($values['restaurant_website']); ?>" placeholder="<?php echo esc_attr(home_url('/')); ?>">
                                    <p class="description"><?php maca_menulist_ob_e('Lämna tomt för att använda WordPress-webbplatsens URL i menyfoten.', 'Leave empty to use your WordPress site URL in the menu footer.'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="maca_onboarding_restaurant_vat_number"><?php maca_menulist_ob_e('Momsregistreringsnummer', 'VAT number'); ?></label></th>
                                <td><input type="text" class="regular-text" id="maca_onboarding_restaurant_vat_number" name="maca_onboarding_restaurant_vat_number" value="<?php echo esc_attr($values['restaurant_vat_number']); ?>" placeholder="SE123456789001"></td>
                            </tr>
                            <?php if ($content_mode === 'dishes') : ?>
                            <tr>
                                <th scope="row"><label for="maca_onboarding_price_currency"><?php maca_menulist_ob_e('Prisvaluta', 'Price currency'); ?></label></th>
                                <td><input type="text" class="small-text" id="maca_onboarding_price_currency" name="maca_onboarding_price_currency" value="<?php echo esc_attr($values['price_currency']); ?>"> <span class="description"><?php maca_menulist_ob_e('t.ex. kr, SEK, €', 'e.g. kr, SEK, €'); ?></span></td>
                            </tr>
                            <?php endif; ?>
                        </table>

                    <?php elseif ($step === 'opening_hours') : ?>
                        <h2><?php maca_menulist_ob_e('Öppettider', 'Opening hours'); ?></h2>
                        <p class="description"><?php maca_menulist_ob_e(
                            'Ange när ni har öppet varje veckodag. Visas på webbplatsen med [maca_opening_hours] och används även för bordsbokningar när den Pro-funktionen är aktiverad. Du kan hoppa över och redigera senare under Inställningar → Öppettider.',
                            'Set when you are open each weekday. Shown on the website with [maca_opening_hours] and also used for table reservations when that Pro feature is enabled. You can skip and edit later under Settings → Opening hours.'
                        ); ?></p>
                        <?php
                        maca_menulist_render_opening_hours_fields(
                            array(
                                'hours'             => maca_menulist_onboarding_get_hours_for_display($values['hours']),
                                'for_onboarding'    => true,
                                'show_booking_note' => false,
                            )
                        );
                        ?>

                    <?php elseif ($step === 'menu_category') : ?>
                        <div class="maca-onboarding-branch" data-mode="files" <?php echo $content_mode === 'files' ? '' : 'hidden'; ?>>
                            <h2><?php maca_menulist_ob_e('Första menykategorin', 'First menu category'); ?></h2>
                            <p class="description"><?php maca_menulist_ob_e(
                                'Skapa en kategori för dina menyer (t.ex. Lunch, Middag, Drycker). Du kan ladda upp PDF- eller bildfiler under Menyer efter detta steg.',
                                'Create a category for your menus (e.g. Lunch, Dinner, Drinks). You can upload PDF or image files under Menus after this step.'
                            ); ?></p>
                            <p>
                                <label for="maca_onboarding_category_name"><?php maca_menulist_ob_e('Kategorinamn', 'Category name'); ?> <span class="required">*</span></label><br>
                                <input type="text" class="regular-text" id="maca_onboarding_category_name" name="maca_onboarding_category_name" value="<?php echo esc_attr($values['category_name']); ?>" placeholder="<?php maca_menulist_ob_attr_e('Lunch', 'Lunch'); ?>">
                            </p>
                        </div>
                        <div class="maca-onboarding-branch" data-mode="dishes" <?php echo $content_mode === 'dishes' ? '' : 'hidden'; ?>>
                            <h2><?php maca_menulist_ob_e('Menykategori', 'Menu category'); ?></h2>
                            <p class="description"><?php maca_menulist_ob_e(
                                'Skapa din första menykategori. I nästa steg lägger du till din första rätt.',
                                'Create your first menu category. In the next step you will add your first dish.'
                            ); ?></p>
                            <p>
                                <label for="maca_onboarding_dish_category"><?php maca_menulist_ob_e('Menykategori', 'Menu category'); ?> <span class="required">*</span></label><br>
                                <input type="text" class="regular-text" id="maca_onboarding_dish_category" name="maca_onboarding_dish_category" value="<?php echo esc_attr($values['dish_category']); ?>" placeholder="<?php maca_menulist_ob_attr_e('Huvudrätt', 'Main course'); ?>">
                            </p>
                        </div>

                    <?php elseif ($step === 'first_dish') : ?>
                        <h2><?php maca_menulist_ob_e('Lägg till din första rätt', 'Add your first dish'); ?></h2>
                        <?php if ($values['dish_category'] !== '') : ?>
                            <p class="description">
                                <?php
                                printf(
                                    '%s <strong>%s</strong>',
                                    esc_html(maca_menulist_ob('Kategori:', 'Category:')),
                                    esc_html($values['dish_category'])
                                );
                                ?>
                            </p>
                        <?php endif; ?>
                        <p class="description"><?php maca_menulist_ob_e(
                            'Lägg till minst en rätt i onlinemenyn. Du kan lägga till fler rätter, allergener och bilder senare.',
                            'Add at least one dish to your online menu. You can add more dishes, allergens, and images later.'
                        ); ?></p>
                        <input type="hidden" name="maca_onboarding_dish_category" value="<?php echo esc_attr($values['dish_category']); ?>">
                        <table class="form-table" role="presentation">
                            <tr>
                                <th scope="row"><label for="maca_onboarding_dish_title"><?php maca_menulist_ob_e('Rättens namn', 'Dish name'); ?> <span class="required">*</span></label></th>
                                <td><input type="text" class="regular-text" id="maca_onboarding_dish_title" name="maca_onboarding_dish_title" value="<?php echo esc_attr($values['dish_title']); ?>" required></td>
                            </tr>
                            <tr>
                                <th scope="row"><label for="maca_onboarding_dish_price"><?php maca_menulist_ob_e('Pris (valfritt)', 'Price (optional)'); ?></label></th>
                                <td><input type="text" class="small-text" id="maca_onboarding_dish_price" name="maca_onboarding_dish_price" value="<?php echo esc_attr($values['dish_price']); ?>"></td>
                            </tr>
                        </table>

                    <?php elseif ($step === 'extras') : ?>
                        <h2><?php maca_menulist_ob_e('Valfria Pro-funktioner', 'Optional Pro features'); ?></h2>
                        <p class="description"><?php maca_menulist_ob_e(
                            'Aktivera nu eller hoppa över — allt kan konfigureras senare under Inställningar.',
                            'Enable now or skip — everything can be configured later under Settings.'
                        ); ?></p>
                        <fieldset class="maca-onboarding-checklist">
                            <?php if ($content_mode === 'dishes' && $dishes_pro_active) : ?>
                            <label>
                                <input type="checkbox" name="maca_onboarding_enable_table_order" value="1" <?php checked($values['enable_table_order']); ?>>
                                <?php maca_menulist_ob_e('Bordsbeställning — gäster beställer från mobilen', 'Table ordering — guests order from their phone'); ?>
                            </label>
                            <?php endif; ?>
                            <?php if (maca_menulist_pro_has_feature('table_bookings')) : ?>
                            <label>
                                <input type="checkbox" name="maca_onboarding_enable_bookings" value="1" <?php checked($values['enable_bookings']); ?>>
                                <?php maca_menulist_ob_e('Bordsbokning — bokningsformulär och admin-kalender', 'Table reservations — booking form and admin calendar'); ?>
                            </label>
                            <?php endif; ?>
                            <?php if (maca_menulist_pro_has_feature('info_hub')) : ?>
                            <label>
                                <input type="checkbox" name="maca_onboarding_enable_info_hub" value="1" <?php checked($values['enable_info_hub']); ?>>
                                <?php maca_menulist_ob_e('Informationsdisk — nyheter, evenemang och iCal-kalender', 'Info hub — news, events, and iCal calendar'); ?>
                            </label>
                            <?php endif; ?>
                        </fieldset>
                        <ul class="maca-onboarding-links">
                            <li><a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-subscription')); ?>"><?php maca_menulist_ob_e('Prenumeration och licens', 'Subscription & license'); ?></a></li>
                            <li><a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-settings')); ?>"><?php maca_menulist_ob_e('Alla inställningar', 'All settings'); ?></a></li>
                            <li><a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-guide')); ?>"><?php maca_menulist_ob_e('Fullständig guide', 'Full guide'); ?></a></li>
                        </ul>

                    <?php elseif ($step === 'publish') : ?>
                        <h2><?php maca_menulist_ob_e('Publicera menyn', 'Publish your menu'); ?></h2>
                        <div class="maca-onboarding-publish-grid">
                            <div class="maca-onboarding-card">
                                <h3><?php maca_menulist_ob_e('Webbplats', 'Website'); ?></h3>
                                <p><?php maca_menulist_ob_e('Lägg till menyn på valfri sida med shortcode eller block:', 'Add the menu to any page using the shortcode or block:'); ?></p>
                                <code class="maca-onboarding-code">[maca_menu_list]</code>
                                <p><a class="button" href="<?php echo esc_url(admin_url('post-new.php?post_type=page')); ?>"><?php maca_menulist_ob_e('Skapa ny sida', 'Create a new page'); ?></a></p>
                            </div>
                            <div class="maca-onboarding-card">
                                <h3><?php maca_menulist_ob_e('QR-meny', 'QR menu'); ?></h3>
                                <p><?php maca_menulist_ob_e('Gäster skannar en QR-kod för att se den meny som är aktiv just nu:', 'Guests scan a QR code to see the menu that is active right now:'); ?></p>
                                <p><a href="<?php echo esc_url($qr_url); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html($qr_url); ?></a></p>
                                <p><a class="button" href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-qr')); ?>"><?php maca_menulist_ob_e('QR-koder och utskrift', 'QR codes & print'); ?></a></p>
                            </div>
                        </div>

                    <?php elseif ($step === 'complete') : ?>
                        <h2><?php maca_menulist_ob_e('Du är redo!', 'You are ready to go!'); ?></h2>
                        <p><?php maca_menulist_ob_e(
                            'Grundinställningen är klar. Använd instrumentpanelen för översikt och nästa steg.',
                            'Basic setup is done. Use the dashboard for an overview and next steps.'
                        ); ?></p>
                        <ul class="maca-onboarding-links">
                            <?php if ($content_mode === 'files') : ?>
                                <li><a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-menus&action=add')); ?>"><?php maca_menulist_ob_e('Ladda upp din första menyfil', 'Upload your first menu file'); ?></a></li>
                            <?php else : ?>
                                <li><a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dishes&action=add')); ?>"><?php maca_menulist_ob_e('Lägg till fler rätter', 'Add more dishes'); ?></a></li>
                            <?php endif; ?>
                            <li><a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dashboard')); ?>"><?php maca_menulist_ob_e('Öppna instrumentpanelen', 'Open dashboard'); ?></a></li>
                            <li><a href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-guide')); ?>"><?php maca_menulist_ob_e('Läs hela guiden', 'Read the full guide'); ?></a></li>
                        </ul>
                    <?php endif; ?>
                </div>

                <div class="maca-onboarding-actions">
                    <?php if (maca_menulist_onboarding_prev_step($step, $values) !== null) : ?>
                        <button type="submit" name="maca_onboarding_action" value="back" class="button"><?php maca_menulist_ob_e('Tillbaka', 'Back'); ?></button>
                    <?php endif; ?>

                    <span class="maca-onboarding-actions-spacer"></span>

                    <?php if ($step !== 'complete') : ?>
                        <button type="submit" name="maca_onboarding_action" value="continue_later" class="button"><?php maca_menulist_ob_e('Spara och fortsätt senare', 'Save and continue later'); ?></button>
                        <?php if (!empty($steps[ $step ]['optional'])) : ?>
                            <button type="submit" name="maca_onboarding_action" value="skip" class="button"><?php maca_menulist_ob_e('Hoppa över detta steg', 'Skip this step'); ?></button>
                        <?php endif; ?>
                        <button type="submit" name="maca_onboarding_action" value="next" class="button button-primary"><?php maca_menulist_ob_e('Fortsätt', 'Continue'); ?></button>
                    <?php else : ?>
                        <a class="button button-primary" href="<?php echo esc_url(admin_url('admin.php?page=maca-restu-dashboard')); ?>"><?php maca_menulist_ob_e('Gå till instrumentpanelen', 'Go to dashboard'); ?></a>
                    <?php endif; ?>

                    <?php if ($step !== 'complete') : ?>
                        <button type="submit" name="maca_onboarding_action" value="dismiss" class="button-link maca-onboarding-dismiss" onclick="return confirm('<?php echo esc_js(maca_menulist_ob('Dölj kom igång-guiden? Du kan fortfarande konfigurera allt under Inställningar och guiden.', 'Hide the setup wizard? You can still configure everything under Settings and the guide.')); ?>');"><?php maca_menulist_ob_e('Stäng guiden', 'Dismiss wizard'); ?></button>
                    <?php endif; ?>
                </div>
            </form>
        </div>
        <?php
    }
}
