<?php
/**
 * Admin — Dashboard / Get Started submenu page
 */

defined('ABSPATH') || exit;

class Vunelix_Admin {

    public static function init() {
        add_action('admin_menu', [__CLASS__, 'add_submenu'], 20);
        add_action('admin_notices', [__CLASS__, 'review_notice']);
        add_action('admin_init', [__CLASS__, 'activation_redirect']);
        add_action('wp_ajax_vunelix_dismiss_review', [__CLASS__, 'dismiss_review']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_review_notice_assets']);

        // Highlight correct menu/submenu when on CPT pages
        add_filter('parent_file', function($parent_file) {
            $screen = get_current_screen();
            if ($screen && $screen->post_type === 'vunelix_widget') {
                return 'vunelix-dashboard';
            }
            return $parent_file;
        });
        add_filter('submenu_file', function($submenu_file) {
            $screen = get_current_screen();
            if (!$screen || $screen->post_type !== 'vunelix_widget') return $submenu_file;
            if ($screen->base === 'edit') return 'edit.php?post_type=vunelix_widget';
            if ($screen->base === 'post' && $screen->action === 'add') return 'post-new.php?post_type=vunelix_widget';
            return $submenu_file;
        });
    }

    /**
     * Check if current page is a Vunelix admin page (dashboard, get-started, etc.)
     */
    public static function is_vunelix_page() {
        $screen = get_current_screen();
        if (!$screen) return false;
        return ($screen->post_type === 'vunelix_widget') || strpos($screen->id, 'vunelix') !== false;
    }

    /**
     * Redirect to Dashboard on first activation
     */
    public static function activation_redirect() {
        if (get_transient('vunelix_activation_redirect')) {
            delete_transient('vunelix_activation_redirect');
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checking existence, no data processed.
            if (!isset($_GET['activate-multi'])) {
                wp_safe_redirect(admin_url('admin.php?page=vunelix-dashboard'));
                exit;
            }
        }
    }

    /**
     * Whether the review notice should render on the current admin screen.
     */
    private static function should_show_review_notice() {
        if (get_option('vunelix_review_dismissed')) return false;
        $count = wp_count_posts('vunelix_widget');
        return (($count->publish ?? 0) >= 1);
    }

    /**
     * Show review notice — after 1+ widgets created, dismissible, on all admin pages
     */
    public static function review_notice() {
        if (!self::should_show_review_notice()) return;

        $review_url = 'https://wordpress.org/support/plugin/vunelix-financial-widgets/reviews/#new-post';
        ?>
        <div class="notice vnx-review-notice">
            <p>
                Thanks for using <strong>Vunelix Widgets</strong>! We hope you're enjoying it.
                <br>A quick review helps other WordPress users discover the plugin and keeps us motivated!
            </p>
            <div class="vnx-review-actions">
                <a href="<?php echo esc_url($review_url); ?>" target="_blank" rel="noopener" class="vnx-review-btn vnx-review-btn-primary" data-action="dismiss">
                    Rate Now! &#9733;&#9733;&#9733;&#9733;&#9733;
                </a>
                <button type="button" class="vnx-review-btn vnx-review-btn-secondary" data-action="dismiss">
                    Already Reviewed
                </button>
                <button type="button" class="vnx-review-btn vnx-review-btn-secondary" data-action="dismiss">
                    Not Interested
                </button>
            </div>
        </div>
        <?php
    }

    /**
     * Enqueue review-notice JS (always when notice is shown) and the
     * minimal notice CSS only on screens where admin.css is not already loaded.
     * This replaces inline <script> / <style> blocks per WP guidelines.
     */
    public static function enqueue_review_notice_assets() {
        if (!self::should_show_review_notice()) return;

        wp_enqueue_script(
            'vunelix-review-notice',
            VUNELIX_PLUGIN_URL . 'assets/js/admin-review-notice.js',
            [],
            VUNELIX_VERSION,
            true
        );
        wp_localize_script('vunelix-review-notice', 'VunelixReviewNotice', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('vunelix_dismiss_review'),
        ]);

        // On Vunelix pages the full admin.css already provides these styles.
        $screen = get_current_screen();
        $on_vunelix_page = $screen && (($screen->post_type === 'vunelix_widget') || strpos($screen->id, 'vunelix') !== false);
        if (!$on_vunelix_page) {
            wp_enqueue_style(
                'vunelix-review-notice',
                VUNELIX_PLUGIN_URL . 'assets/css/admin-review-notice.css',
                [],
                VUNELIX_VERSION
            );
        }
    }

    /**
     * AJAX handler — permanently dismiss review notice
     */
    public static function dismiss_review() {
        check_ajax_referer('vunelix_dismiss_review');
        update_option('vunelix_review_dismissed', true);
        wp_die();
    }

    /**
     * Build full menu: top-level = Dashboard, submenus below
     */
    public static function add_submenu() {
        $slug = 'vunelix-dashboard';

        // Top-level menu — clicking "Vunelix Widgets" opens Dashboard
        add_menu_page(
            'Vunelix Widgets',
            'Vunelix Widgets',
            'edit_posts',
            $slug,
            [__CLASS__, 'render_dashboard'],
            'dashicons-chart-area',
            30
        );

        // Dashboard (first submenu replaces parent label)
        add_submenu_page($slug, 'Dashboard', 'Dashboard', 'edit_posts', $slug, [__CLASS__, 'render_dashboard']);

        // All Widgets (CPT list)
        add_submenu_page($slug, 'All Widgets', 'All Widgets', 'edit_posts', 'edit.php?post_type=vunelix_widget');

        // Add New Widget
        add_submenu_page($slug, 'Add New Widget', 'Add New Widget', 'edit_posts', 'post-new.php?post_type=vunelix_widget');

        // Get Started
        add_submenu_page($slug, 'Get Started', 'Get Started', 'edit_posts', 'vunelix-get-started', [__CLASS__, 'render_get_started']);
    }

    /**
     * Dashboard page
     */
    public static function render_dashboard() {
        $widget_count = wp_count_posts('vunelix_widget');
        $published = $widget_count->publish ?? 0;
        $widgets = vunelix_get_widgets();
        $groups = vunelix_get_widget_groups();
        $img_base = VUNELIX_PLUGIN_URL . 'assets/images/widgets/';
        $new_url = admin_url('post-new.php?post_type=vunelix_widget');
        ?>
        <div class="wrap vnx-dashboard">
            <h1 class="vnx-dashboard-title">Vunelix Widgets</h1>

            <!-- Hero Header -->
            <div class="vnx-hero">
                <div class="vnx-hero-content">
                    <p class="vnx-hero-tagline">Embed live financial data on your WordPress site — crypto, forex, stocks, and more.</p>
                    <div class="vnx-hero-actions">
                        <a href="<?php echo esc_url($new_url); ?>" class="vnx-hero-btn vnx-hero-btn-primary">Create Widget</a>
                        <a href="https://vunelix.com/widgets/overview" target="_blank" rel="noopener" class="vnx-hero-btn vnx-hero-btn-secondary">View Docs</a>
                    </div>
                </div>
                <div class="vnx-hero-stats">
                    <div class="vnx-stat-card">
                        <span class="vnx-stat-number"><?php echo intval($published); ?></span>
                        <span class="vnx-stat-label">Active Widgets</span>
                    </div>
                    <div class="vnx-stat-card">
                        <span class="vnx-stat-number"><?php echo count($widgets); ?></span>
                        <span class="vnx-stat-label">Available Types</span>
                    </div>
                </div>
            </div>

            <!-- Quick Start -->
            <div class="vnx-quick-start">
                <div class="vnx-qs-step">
                    <span class="vnx-qs-num">1</span>
                    <div><strong>Sign up</strong> — <a href="https://developers.vunelix.com/signup" target="_blank" rel="noopener">Create a free account</a> and add your domain</div>
                </div>
                <div class="vnx-qs-step">
                    <span class="vnx-qs-num">2</span>
                    <div><strong>Create</strong> — <a href="<?php echo esc_url($new_url); ?>">Add a new widget</a> and configure it</div>
                </div>
                <div class="vnx-qs-step">
                    <span class="vnx-qs-num">3</span>
                    <div><strong>Embed</strong> — Copy the shortcode and paste it into any page or post</div>
                </div>
            </div>

            <!-- Widget Slider -->
            <div class="vnx-slider">
                <div class="vnx-slider-header">
                    <h2 class="vnx-slider-heading">Widget Examples</h2>
                    <div class="vnx-slider-nav">
                        <button type="button" class="vnx-slider-arrow vnx-slider-prev" aria-label="Previous"></button>
                        <div class="vnx-slider-dots"></div>
                        <button type="button" class="vnx-slider-arrow vnx-slider-next" aria-label="Next"></button>
                    </div>
                </div>
                <div class="vnx-slider-wrap">
                    <div class="vnx-slider-track">
                        <?php
                        $has_image = [
                            'ticker-tape',
                            'crypto-heatmap', 'currency-heatmap', 'stock-heatmap',
                            'oscillators', 'technical-summary',
                            'crypto-screener',
                            'currency-converter', 'currency-cross-rates',
                            'crypto-market-movers', 'forex-market-movers', 'stock-market-movers',
                            'forex-screener', 'stock-screener',
                            'symbol-search',
                        ];
                        foreach ($has_image as $slug):
                            $w = $widgets[$slug] ?? null;
                            if (!$w) continue;
                            $img_url = $img_base . $slug . '.png';
                        ?>
                        <div class="vnx-slide">
                            <img src="<?php echo esc_url($img_url); ?>" alt="<?php echo esc_attr($w['name']); ?>">
                            <span class="vnx-slide-label"><?php echo esc_html($w['name']); ?></span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Footer Links -->
            <div class="vnx-dash-links">
                <a href="https://vunelix.com/widgets/overview" target="_blank" rel="noopener">Widget Docs</a>
                <a href="https://developers.vunelix.com/signup" target="_blank" rel="noopener">Developer Portal</a>
                <span class="vnx-dash-version">Vunelix Widgets v<?php echo esc_html(VUNELIX_VERSION); ?></span>
            </div>
        </div>
        <?php
    }

    /**
     * Get Started page
     */
    public static function render_get_started() {
        $new_url = admin_url('post-new.php?post_type=vunelix_widget');
        $all_url = admin_url('edit.php?post_type=vunelix_widget');
        ?>
        <div class="wrap vnx-dashboard">
            <h1>Get Started</h1>

            <!-- Hero -->
            <div class="vnx-gs-hero">
                <h2>Set up in under 2 minutes</h2>
                <p>No API key required. Just register your domain, create a widget, and embed it.</p>
            </div>

            <!-- Steps -->
            <div class="vnx-gs-steps">
                <div class="vnx-gs-step">
                    <div class="vnx-gs-num">1</div>
                    <div class="vnx-gs-content">
                        <h3>Register Your Domain</h3>
                        <p>Widgets are authorized per domain. <a href="https://developers.vunelix.com/signup" target="_blank" rel="noopener">Create a free account</a>, add your site URL, and you're ready.</p>
                    </div>
                </div>
                <div class="vnx-gs-step">
                    <div class="vnx-gs-num">2</div>
                    <div class="vnx-gs-content">
                        <h3>Create a Widget</h3>
                        <p>Go to <a href="<?php echo esc_url($new_url); ?>">Add New Widget</a>, pick a type, adjust settings, and hit <strong>Publish</strong>.</p>
                    </div>
                </div>
                <div class="vnx-gs-step">
                    <div class="vnx-gs-num">3</div>
                    <div class="vnx-gs-content">
                        <h3>Paste the Shortcode</h3>
                        <p>Copy the shortcode (e.g. <code>[vunelix id="12"]</code>) and paste it into any page, post, or widget area.</p>
                    </div>
                </div>
                <div class="vnx-gs-step">
                    <div class="vnx-gs-num">4</div>
                    <div class="vnx-gs-content">
                        <h3>Update Anytime</h3>
                        <p>Go to <a href="<?php echo esc_url($all_url); ?>">All Widgets</a>, edit settings, click Update. Changes apply everywhere — shortcode stays the same.</p>
                    </div>
                </div>
            </div>

            <!-- Help links -->
            <div class="vnx-gs-help">
                <h3>Need Help?</h3>
                <div class="vnx-gs-help-grid">
                    <a href="https://vunelix.com/widgets/overview" target="_blank" rel="noopener" class="vnx-gs-help-card">
                        <span class="dashicons dashicons-book"></span>
                        <strong>Documentation</strong>
                        <p>Full widget docs with examples and settings reference.</p>
                    </a>
                    <a href="https://developers.vunelix.com/signup" target="_blank" rel="noopener" class="vnx-gs-help-card">
                        <span class="dashicons dashicons-admin-users"></span>
                        <strong>Developer Portal</strong>
                        <p>Manage domains, view usage, and access your account.</p>
                    </a>
                    <a href="https://wordpress.org/support/plugin/vunelix-financial-widgets/" target="_blank" rel="noopener" class="vnx-gs-help-card">
                        <span class="dashicons dashicons-sos"></span>
                        <strong>Support</strong>
                        <p>Ask questions or report issues on WordPress.org.</p>
                    </a>
                </div>
            </div>
        </div>
        <?php
    }
}
