<?php
/**
 * Flavor – Restaurant Menu
 *
 * Onboarding "Get Started" page.
 *
 * A short setup checklist that ticks itself off automatically as the user
 * reaches each milestone — create a category, add a dish, add a photo and put
 * the menu on a page. Nothing is checked by hand; every step reflects the real
 * state of the site. Identical in the Free and Pro plugins.
 *
 * @package    FlavorMenu
 * @copyright  Copyright (c) 2024 Flavor Studio
 * @license    GPL-2.0-or-later
 * @link       https://flavor-menu.com
 */

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

class Flavor_Onboarding {

    const SLUG          = 'flavor-get-started';
    const ACTION_CREATE = 'flavor_onboarding_create_page';
    const OPT_RENDERED  = 'flavor_menu_rendered';
    const OPT_PAGE      = 'flavor_onboarding_menu_page';
    public static function init() {
        add_action( 'admin_menu', array( __CLASS__, 'register_page' ), 5 );
        add_action( 'admin_post_' . self::ACTION_CREATE, array( __CLASS__, 'handle_create_page' ) );

        // After Freemius shows its own opt-in / skip screen, route the user to the
        // Get Started page. We must NOT redirect on activation ourselves — doing so
        // races Freemius's opt-in screen, skips past it, and prevents the install
        // from ever being registered (which silently zeroes out Freemius stats).
        if ( function_exists( 'flavor_fs' ) ) {
            flavor_fs()->add_filter( 'after_connect_url',         array( __CLASS__, 'page_url' ) );
            flavor_fs()->add_filter( 'after_skip_url',            array( __CLASS__, 'page_url' ) );
            flavor_fs()->add_filter( 'after_pending_connect_url', array( __CLASS__, 'page_url' ) );
        }
    }

    // -------------------------------------------------------------------------
    // Step detection — all based on the real state of the site
    // -------------------------------------------------------------------------

    public static function has_category() {
        $count = wp_count_terms( array( 'taxonomy' => 'flavor_menu_cat', 'hide_empty' => false ) );
        return ! is_wp_error( $count ) && (int) $count > 0;
    }

    public static function has_dish() {
        $counts = wp_count_posts( 'flavor_menu_item' );
        return $counts && (int) $counts->publish > 0;
    }

    public static function has_photo() {
        $ids = get_posts( array(
            'post_type'      => 'flavor_menu_item',
            'post_status'    => 'publish',
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'meta_query'     => array( array( 'key' => '_thumbnail_id', 'compare' => 'EXISTS' ) ), // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
        ) );
        return ! empty( $ids );
    }

    /** True once the menu has rendered on the front end at least once (any page builder). */
    public static function is_embedded() {
        return (bool) get_option( self::OPT_RENDERED );
    }

    /** Which page builder is active, if any: 'elementor', 'wpbakery' or '' (none). */
    public static function active_builder() {
        if ( did_action( 'elementor/loaded' ) ) {
            return 'elementor';
        }
        if ( defined( 'WPB_VC_VERSION' ) ) {
            return 'wpbakery';
        }
        return '';
    }

    // -------------------------------------------------------------------------
    // Admin page
    // -------------------------------------------------------------------------

    public static function register_page() {
        add_submenu_page(
            'edit.php?post_type=flavor_menu_item',
            __( 'Get Started', 'flavor-restaurant-menu' ),
            __( 'Get Started', 'flavor-restaurant-menu' ),
            'manage_options',
            self::SLUG,
            array( __CLASS__, 'render_page' ),
            0
        );
    }

    public static function page_url() {
        return admin_url( 'edit.php?post_type=flavor_menu_item&page=' . self::SLUG );
    }

    /** One-click: create a published "Our Menu" page containing the shortcode. */
    public static function handle_create_page() {
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You do not have permission to do this.', 'flavor-restaurant-menu' ) );
        }
        check_admin_referer( self::ACTION_CREATE );

        // Re-use the page if we already created one (no duplicates).
        $existing = (int) get_option( self::OPT_PAGE );
        if ( $existing && 'trash' !== get_post_status( $existing ) && get_post_status( $existing ) ) {
            $link = get_permalink( $existing );
            wp_safe_redirect( $link ? $link : self::page_url() );
            exit;
        }

        $page_id = wp_insert_post( array(
            'post_type'    => 'page',
            'post_title'   => __( 'Our Menu', 'flavor-restaurant-menu' ),
            'post_status'  => 'publish',
            'post_content' => '[flavor_menu]',
        ) );

        if ( $page_id && ! is_wp_error( $page_id ) ) {
            update_option( self::OPT_PAGE, (int) $page_id );
            $link = get_permalink( $page_id );
            wp_safe_redirect( $link ? $link : self::page_url() );
            exit;
        }

        wp_safe_redirect( self::page_url() );
        exit;
    }

    public static function render_page() {
        $has_cat   = self::has_category();
        $has_dish  = self::has_dish();
        $has_photo = self::has_photo();
        $embedded  = self::is_embedded();

        $flags = array( $has_cat, $has_dish, $has_photo, $embedded );
        $done  = count( array_filter( $flags ) );
        $total = count( $flags );
        $pct   = (int) round( $done / $total * 100 );

        $new_cat  = admin_url( 'edit-tags.php?taxonomy=flavor_menu_cat&post_type=flavor_menu_item' );
        $new_dish = admin_url( 'post-new.php?post_type=flavor_menu_item' );
        $all_dish = admin_url( 'edit.php?post_type=flavor_menu_item' );
        $pages    = admin_url( 'edit.php?post_type=page' );
        $create   = wp_nonce_url( admin_url( 'admin-post.php?action=' . self::ACTION_CREATE ), self::ACTION_CREATE );
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Get started with Flavor', 'flavor-restaurant-menu' ); ?></h1>
            <?php flavor_docs_link_html( '#shortcode' ); ?>

            <div style="max-width:680px;margin-top:18px;background:#fff;border:1px solid #c3c4c7;border-radius:6px;padding:24px 28px;">
                <p style="margin:0 0 16px;color:#3c434a;font-size:14px;">
                    <?php esc_html_e( 'Steps tick themselves off as you go — nothing to check by hand.', 'flavor-restaurant-menu' ); ?>
                </p>

                <div style="display:flex;align-items:center;gap:12px;margin:0 0 22px;">
                    <div style="flex:1;height:8px;border-radius:99px;background:#f0f0f1;overflow:hidden;">
                        <div style="width:<?php echo (int) $pct; ?>%;height:100%;background:#46b450;"></div>
                    </div>
                    <span style="font-size:13px;font-weight:600;color:#50575e;white-space:nowrap;">
                        <?php
                        /* translators: 1: completed steps, 2: total steps */
                        printf( esc_html__( '%1$d of %2$d done', 'flavor-restaurant-menu' ), (int) $done, (int) $total );
                        ?>
                    </span>
                </div>

                <?php if ( $done === $total ) : ?>
                    <div style="margin:0 0 18px;padding:12px 16px;background:#edf7ed;border:1px solid #46b450;border-radius:4px;color:#1e7e34;font-size:14px;">
                        <span class="dashicons dashicons-yes-alt" style="vertical-align:-3px;"></span>
                        <?php esc_html_e( "You're all set — your menu is live.", 'flavor-restaurant-menu' ); ?>
                    </div>
                <?php endif; ?>

                <?php
                self::step_row(
                    $has_cat,
                    __( 'Create your first category', 'flavor-restaurant-menu' ),
                    __( 'Group your dishes, e.g. Starters, Mains, Drinks', 'flavor-restaurant-menu' ),
                    $has_cat ? '' : '<a href="' . esc_url( $new_cat ) . '" class="button">' . esc_html__( 'Add category', 'flavor-restaurant-menu' ) . '</a>'
                );
                self::step_row(
                    $has_dish,
                    __( 'Add your first dish', 'flavor-restaurant-menu' ),
                    __( 'Give it a name, a price and a category', 'flavor-restaurant-menu' ),
                    $has_dish ? '' : '<a href="' . esc_url( $new_dish ) . '" class="button">' . esc_html__( 'Add dish', 'flavor-restaurant-menu' ) . '</a>'
                );
                self::step_row(
                    $has_photo,
                    __( 'Add a photo to a dish', 'flavor-restaurant-menu' ),
                    __( 'A featured image makes the card grid shine', 'flavor-restaurant-menu' ),
                    $has_photo ? '' : '<a href="' . esc_url( $all_dish ) . '" class="button">' . esc_html__( 'Edit a dish', 'flavor-restaurant-menu' ) . '</a>'
                );

                $embed_actions = $embedded ? '' :
                    '<a href="' . esc_url( $create ) . '" class="button button-primary">' . esc_html__( 'Create menu page for me', 'flavor-restaurant-menu' ) . '</a> ' .
                    '<a href="' . esc_url( $pages ) . '" class="button">' . esc_html__( 'Choose existing page', 'flavor-restaurant-menu' ) . '</a>';
                self::step_row(
                    $embedded,
                    __( 'Put your menu on a page', 'flavor-restaurant-menu' ),
                    __( 'The step that takes your menu live — new page in one click, or add it to a page you already have', 'flavor-restaurant-menu' ),
                    $embed_actions
                );

                // Page-builder users don't need the shortcode — point them to the native element instead.
                $builder = self::active_builder();
                if ( ! $embedded && '' !== $builder ) {
                    $hint = 'elementor' === $builder
                        ? __( 'Using Elementor? Edit any page, find the “Menu Card” widget and drop it in — every option is a visual control, no shortcode needed.', 'flavor-restaurant-menu' )
                        : __( 'Using WPBakery? Add the “Menu Card” element (Restaurant category) to any page — every option is a visual control, no shortcode needed.', 'flavor-restaurant-menu' );
                    echo '<div style="margin:2px 0 0 40px;padding:10px 14px;background:#f0f6fc;border-left:3px solid #2271b1;border-radius:3px;color:#3c434a;font-size:13px;line-height:1.5;">' . esc_html( $hint ) . '</div>';
                }
                ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render a single checklist row. $actions_html is already-escaped markup.
     */
    private static function step_row( $done, $title, $desc, $actions_html ) {
        $icon = $done
            ? '<span style="flex:none;width:26px;height:26px;border-radius:50%;background:#edf7ed;color:#1e7e34;display:inline-flex;align-items:center;justify-content:center;"><span class="dashicons dashicons-yes" style="font-size:18px;width:18px;height:18px;"></span></span>'
            : '<span style="flex:none;width:26px;height:26px;border-radius:50%;border:2px solid #c3c4c7;display:inline-block;box-sizing:border-box;"></span>';

        $title_style = $done ? 'color:#646970;text-decoration:line-through;' : 'color:#1d2327;';
        ?>
        <div style="display:flex;align-items:center;gap:14px;padding:14px 0;border-top:1px solid #f0f0f1;">
            <?php echo wp_kses_post( $icon ); ?>
            <div style="flex:1;min-width:0;">
                <div style="font-size:15px;<?php echo esc_attr( $title_style ); ?>"><?php echo esc_html( $title ); ?></div>
                <div style="font-size:12px;color:#787c82;margin-top:2px;"><?php echo esc_html( $desc ); ?></div>
            </div>
            <?php if ( $actions_html ) : ?>
                <div style="flex:none;"><?php echo wp_kses_post( $actions_html ); ?></div>
            <?php endif; ?>
        </div>
        <?php
    }
}
