<?php

defined('ABSPATH') || exit;

/**
 * BundlePress Store Notice Handler
 * 
 * Fetches and displays store notices from the central API.
 */
class BundlePress_Store_Notice
{

    /**
     * Initialize the class
     */
    public static function init()
    {
        $instance = new self();
        add_action('admin_notices', [$instance, 'display_notice']);
        add_action('admin_enqueue_scripts', [$instance, 'enqueue_styles']);
    }

    /**
     * Enqueue styles and scripts for the notice
     */
    public function enqueue_styles($hook)
    {
        // Enqueue on the dashboard and BundlePress pages
        $is_dashboard = ($hook === 'index.php');
        $is_bundlepress = (strpos($hook, 'bundlepress') !== false);

        if (!$is_dashboard && !$is_bundlepress) {
            return;
        }

        $widgets_path = BUNDLEPRESS_PATH . 'assets/widgets.js';
        $widgets_url = BUNDLEPRESS_URL . 'assets/widgets.js';

        if (file_exists($widgets_path)) {
            wp_enqueue_script(
                'bundlepress-store-notice',
                $widgets_url,
                ['wp-element'],
                filemtime($widgets_path),
                true
            );

            wp_localize_script('bundlepress-store-notice', 'bundlePressData', [
                'restUrl' => esc_url_raw(rest_url()),
                'rootUrl' => esc_url_raw(home_url()),
                'wpRestNonce' => wp_create_nonce('wp_rest'),
            ]);
        }
    }

    /**
     * Display the notice in the dashboard
     */
    public function display_notice()
    {
        // Only show to admins
        if (!current_user_can('manage_options')) {
            return;
        }

        $screen = get_current_screen();
        $is_dashboard = ($screen->id === 'dashboard');
        $is_bundlepress = (strpos($screen->id, 'bundlepress') !== false);

        if (!$is_dashboard && !$is_bundlepress) {
            return;
        }

        // Just output the root element for React
        echo '<div id="bundlepress-store-notice-root" style="margin: 20px 20px 10px 0; max-width: 1210px;"></div>';
    }
}
