<?php
/**
 * Free Global Pulse module.
 *
 * Strict-isolation entrypoint for the Global Pulse admin section.
 * Owns:
 * - section registration
 * - local admin view
 * - nav-card shell state (alert / clear)
 * - minimal shell CSS enqueue for the nav card visual layer
 * - bootstrap of the module-local Global Pulse data service
 *
 * Full section assets remain lazy-loaded by the shell manifest.
 *
 * @package Noesia_Smart_Waiter
 */

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

if ( ! class_exists( 'Noesia_Swa_Module_Global_Pulse' ) ) {
    /**
     * Free Global Pulse module.
     */
    class Noesia_Swa_Module_Global_Pulse implements Noesia_SWA_Module_Interface {

        /**
         * Unique module identifier.
         *
         * @return string
         */
        public function get_id() {
            return 'global-pulse';
        }

        /**
         * Human-readable module label.
         *
         * @return string
         */
        public function get_label() {
            return __( 'Global Pulse', 'noesia-smart-waiter' );
        }

        /**
         * Module tier.
         *
         * @return string
         */
        public function get_tier() {
            return 'free';
        }

        /**
         * Whether the module is enabled.
         *
         * @return bool
         */
        public function is_enabled() {
            $enabled = true;

            /**
             * Filter whether the free Global Pulse module is enabled.
             *
             * @param bool                            $enabled Enabled state.
             * @param Noesia_Swa_Module_Global_Pulse $module  Module instance.
             */
            $enabled = apply_filters( 'noesia_swa_module_global_pulse_enabled', $enabled, $this );

            return (bool) $enabled;
        }

        /**
         * Register module hooks.
         *
         * @return void
         */
        public function register_hooks() {
            $this->boot_local_data_service();

            add_action( 'noesia_swa_register_admin_sections', array( $this, 'register_admin_section' ) );
            add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_shell_css' ), 20 );
            add_filter( 'noesia_swa_shell_nav_card_state', array( $this, 'filter_nav_card_state' ), 10, 4 );

            /**
             * Fires when the Global Pulse module is booted.
             *
             * @param Noesia_Swa_Module_Global_Pulse $this Module instance.
             */
            do_action( 'noesia_swa_module_global_pulse_loaded', $this );
        }

        /**
         * Load the module-local Global Pulse data class if it is not already loaded.
         *
         * Safe bridge step during extraction:
         * - if the legacy kernel file still loads the class, do nothing
         * - once the kernel stops loading it, the module becomes the owner
         *
         * @return void
         */
        private function boot_local_data_service() {
            if ( class_exists( 'Noesia_SWA_Global_Pulse_Data' ) ) {
                return;
            }

            $data_file = trailingslashit( __DIR__ ) . 'includes/class-noesia-swa-global-pulse-data.php';

            if ( file_exists( $data_file ) ) {
                require_once $data_file;
            }
        }

        /**
         * Register the Global Pulse admin section.
         *
         * @param mixed $registry Admin sections registry.
         * @return void
         */
        public function register_admin_section( $registry ) {
            if ( ! $registry instanceof Noesia_SWA_Admin_Sections ) {
                return;
            }

            $registry->register_section(
                array(
                    'id'           => 'global-pulse',
                    'label'        => $this->get_label(),
                    'nav_label'    => $this->get_label(),
                    'nav_sub'      => __( 'WordPress Pulse', 'noesia-smart-waiter' ),
                    'icon'         => 'dashicons-heart',
                    'icon_type'     => 'svg',
                    'icon_svg_key'  => 'pulse',
                    'icon_color'    => '#f6c7d8',
                    'priority'      => 105,
                    'tier'         => 'free',
                    'owner'        => 'global-pulse',
                    'hero'         => false,
                    'is_visible'   => true,
                    'nav_visible'  => true,
                    'callback'     => array( $this, 'render_admin' ),
                )
            );
        }

        /**
         * Filter shell nav-card state for this module.
         *
         * Kernel is blind; module owns whether its nav card should render as
         * "clear" or "alert". If the Global Pulse update snapshot service is
         * available, use its pending_total to determine the visual state.
         *
         * @param array<string,string> $state Default shell state.
         * @param string               $section_id Section slug.
         * @param array<string,mixed>  $options Saved options.
         * @param mixed                $helper Shell data helper.
         * @return array<string,string>
         */
        public function filter_nav_card_state( $state, $section_id, $options, $helper ) {
            if ( 'global-pulse' !== sanitize_key( (string) $section_id ) ) {
                return is_array( $state ) ? $state : array();
            }

            $pending_total = 0;

            if ( function_exists( 'noesia_swa_global_pulse_get_update_snapshot' ) ) {
                $snapshot = noesia_swa_global_pulse_get_update_snapshot();

                if ( is_array( $snapshot ) && isset( $snapshot['pending_total'] ) ) {
                    $pending_total = absint( $snapshot['pending_total'] );
                }
            }

            if ( $pending_total > 0 ) {
                return array(
                    'state' => 'is-alert',
                    'color' => '#f59e0b',
                );
            }

            return array(
                'state' => 'is-clear',
                'color' => '#f6c7d8',
            );
        }

        /**
         * Render the module-local Global Pulse admin view.
         *
         * @return void
         */
        public function render_admin() {
            $module_view = trailingslashit( __DIR__ ) . 'views/admin.php';
            $legacy_view = NOESIA_SWA_PLUGIN_DIR . 'admin/partials/sections/global-pulse.php';

            /**
             * Fires before the Global Pulse admin module view renders.
             *
             * @param Noesia_Swa_Module_Global_Pulse $this Module instance.
             */
            do_action( 'noesia_swa_before_render_global_pulse_admin', $this );

            if ( file_exists( $module_view ) ) {
                include $module_view;

                /**
                 * Fires after the Global Pulse admin module view renders.
                 *
                 * @param Noesia_Swa_Module_Global_Pulse $this Module instance.
                 */
                do_action( 'noesia_swa_after_render_global_pulse_admin', $this );
                return;
            }

            if ( file_exists( $legacy_view ) ) {
                include $legacy_view;

                /**
                 * Fires after the Global Pulse legacy fallback view renders.
                 *
                 * @param Noesia_Swa_Module_Global_Pulse $this Module instance.
                 */
                do_action( 'noesia_swa_after_render_global_pulse_admin', $this );
                return;
            }

            echo '<div class="noesia-swa-card noesia-swa-card--span2">';
            echo '<div class="noesia-swa-card-header"><div>';
            echo '<h3>' . esc_html__( 'Global Pulse', 'noesia-smart-waiter' ) . '</h3>';
            echo '<p class="noesia-swa-muted">' . esc_html__( 'Module view missing.', 'noesia-smart-waiter' ) . '</p>';
            echo '</div></div>';
            echo '</div>';

            /**
             * Fires after the Global Pulse missing-view fallback renders.
             *
             * @param Noesia_Swa_Module_Global_Pulse $this Module instance.
             */
            do_action( 'noesia_swa_after_render_global_pulse_admin', $this );
        }

        /**
         * Enqueue the minimal nav-card visual layer for Global Pulse.
         *
         * This does not move business logic into the shell. It only allows the
         * module's nav card to render its alert / clear state on first paint.
         *
         * @param string $hook Current admin page hook.
         * @return void
         */
        public function enqueue_shell_css( $hook ) {
            if ( ! $this->is_plugin_admin_screen( $hook ) ) {
                return;
            }

            if ( ! apply_filters( 'noesia_swa_global_pulse_shell_css_enabled', true, $this ) ) {
                return;
            }

            $relative_path = $this->get_shell_css_relative_path();

            if ( '' === $relative_path ) {
                return;
            }

            $absolute_path = NOESIA_SWA_PLUGIN_DIR . $relative_path;

            if ( ! file_exists( $absolute_path ) ) {
                return;
            }

            wp_enqueue_style(
                'noesia-swa-global-pulse-shell-css',
                NOESIA_SWA_PLUGIN_URL . $relative_path,
                array( 'noesia-admin-css' ),
                (string) filemtime( $absolute_path )
            );
        }

        /**
         * Resolve the best available nav-card shell stylesheet.
         *
         * @return string
         */
        private function get_shell_css_relative_path() {
            $shell_relative = 'modules/free/global-pulse/assets/css/shell.css';
            $admin_relative = 'modules/free/global-pulse/assets/css/admin.css';

            if ( file_exists( NOESIA_SWA_PLUGIN_DIR . $shell_relative ) ) {
                return $shell_relative;
            }

            $allow_admin_fallback = apply_filters(
                'noesia_swa_global_pulse_allow_admin_css_shell_fallback',
                true,
                $this
            );

            if ( $allow_admin_fallback && file_exists( NOESIA_SWA_PLUGIN_DIR . $admin_relative ) ) {
                return $admin_relative;
            }

            return '';
        }

        /**
         * Whether the current screen is the plugin admin page.
         *
         * @param string $hook Current admin page hook.
         * @return bool
         */
        private function is_plugin_admin_screen( $hook ) {
            if ( 'toplevel_page_noesia_swa_settings' !== (string) $hook ) {
                return false;
            }

            return current_user_can( 'manage_options' );
        }
    }
}
