<?php
/**
 * Free Calculator module.
 *
 * Strict-isolation entrypoint for the Calculator admin section.
 * Owns:
 * - section registration
 * - module-local admin view
 * - calculator/BMI shared i18n used by its local JS
 * - bootstrap of the module-local calculator data service
 * - module-owned topbar action metadata for the shared shell
 *
 * This module remains strict lazy-load only.
 *
 * @package Noesia_Smart_Waiter
 */

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

if ( ! class_exists( 'Noesia_Swa_Module_Calculator' ) ) {
    /**
     * Free Calculator module.
     */
    class Noesia_Swa_Module_Calculator implements Noesia_SWA_Module_Interface {

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

        /**
         * Human-readable module label.
         *
         * @return string
         */
        public function get_label() {
            return __( 'Calculator & BMI', '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 Calculator module is enabled.
             *
             * @param bool                          $enabled Enabled state.
             * @param Noesia_Swa_Module_Calculator $module Module instance.
             */
            $enabled = apply_filters( 'noesia_swa_module_calculator_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_filter( 'noesia_swa_admin_i18n', array( $this, 'filter_admin_i18n' ), 10, 2 );
            add_filter( 'noesia_swa_shell_topbar_actions', array( $this, 'filter_topbar_actions' ), 20, 4 );

            /**
             * Fires when the Calculator module is booted.
             *
             * @param Noesia_Swa_Module_Calculator $this Module instance.
             */
            do_action( 'noesia_swa_module_calculator_loaded', $this );
        }

        /**
         * Load the module-local Calculator data class if it is not already loaded.
         *
         * This is a safe bridge step during extraction:
         * - if the legacy kernel file still loads the class, we 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_Calculator_Data' ) ) {
                return;
            }

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

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

        /**
         * Register the Calculator 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'          => 'calculator',
                    'label'       => $this->get_label(),
                    'nav_label'   => $this->get_label(),
                    'icon'        => 'dashicons-calculator',
                    'nav_sub'     => __( 'Quick Utility', 'noesia-smart-waiter' ),
                    'priority'    => 50,
                    'tier'        => 'free',
                    'owner'       => 'calculator',
                    'is_visible'  => true,
                    'nav_visible' => true,
                    'callback'    => array( $this, 'render_admin' ),
                )
            );
        }

        /**
         * Provide module-owned shared i18n.
         *
         * These strings are consumed by the module-local calculator JS via the
         * shared localized payload, so they must belong to the module instead of
         * the kernel.
         *
         * @param array<string,string> $i18n Existing i18n payload.
         * @param mixed                $admin Admin instance.
         * @return array<string,string>
         */
        public function filter_admin_i18n( $i18n, $admin ) {
            if ( ! is_array( $i18n ) ) {
                $i18n = array();
            }

            $i18n['bmi_notice']                = __( 'Notice', 'noesia-smart-waiter' );
            $i18n['bmi_preview_title']         = __( 'BMI Preview', 'noesia-smart-waiter' );
            $i18n['bmi_preview_text']          = __( 'Enter height and weight, then click Calculate.', 'noesia-smart-waiter' );
            $i18n['bmi_result_title']          = __( 'Your BMI', 'noesia-smart-waiter' );
            $i18n['bmi_healthy_weight_range']  = __( 'Healthy weight range for this height', 'noesia-smart-waiter' );
            $i18n['bmi_optional_estimates']    = __( 'Optional estimates', 'noesia-smart-waiter' );
            $i18n['bmi_body_fat_estimate']     = __( 'Body fat estimate', 'noesia-smart-waiter' );
            $i18n['bmi_error_missing_inputs']  = __( 'Please enter height (cm) and weight (kg).', 'noesia-smart-waiter' );
            $i18n['bmi_error_positive_inputs'] = __( 'Height and weight must be greater than zero.', 'noesia-smart-waiter' );

            return $i18n;
        }

        /**
         * Register the Calculator topbar action inside the shared shell.
         *
         * Transitional ownership move:
         * - today the shell still has default topbar actions
         * - this module now asserts ownership of the calculator action metadata
         * - later, kernel defaults can be emptied safely
         *
         * @param array<int,array<string,mixed>>      $actions Existing topbar actions.
         * @param array<string,array<string,mixed>>   $sections Registered admin sections.
         * @param array<string,mixed>                 $options Saved options.
         * @param mixed                               $shell_data Shell data helper.
         * @return array<int,array<string,mixed>>
         */
        public function filter_topbar_actions( $actions, $sections, $options, $shell_data ) {
            if ( ! is_array( $actions ) ) {
                $actions = array();
            }

            $replacement = array(
                'id'       => 'calculator',
                'type'     => 'nav',
                'target'   => 'calculator',
                'icon'     => 'dashicons-calculator',
                'label'    => __( 'Calculator', 'noesia-smart-waiter' ),
                'position' => 'left',
                'priority' => 20,
                'owner'    => 'calculator',
            );

            $found = false;

            foreach ( $actions as $index => $action ) {
                if ( ! is_array( $action ) ) {
                    continue;
                }

                $action_id     = isset( $action['id'] ) ? sanitize_key( (string) $action['id'] ) : '';
                $action_target = isset( $action['target'] ) ? sanitize_key( (string) $action['target'] ) : '';

                if ( 'calculator' === $action_id || 'calculator' === $action_target ) {
                    $actions[ $index ] = array_merge( $action, $replacement );
                    $found             = true;
                    break;
                }
            }

            if ( ! $found ) {
                $actions[] = $replacement;
            }

            return $actions;
        }

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

            /**
             * Fires before the Calculator admin module view renders.
             *
             * @param Noesia_Swa_Module_Calculator $this Module instance.
             */
            do_action( 'noesia_swa_before_render_calculator_admin', $this );

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

                /**
                 * Fires after the Calculator admin module view renders.
                 *
                 * @param Noesia_Swa_Module_Calculator $this Module instance.
                 */
                do_action( 'noesia_swa_after_render_calculator_admin', $this );
                return;
            }

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

                /**
                 * Fires after the Calculator legacy fallback view renders.
                 *
                 * @param Noesia_Swa_Module_Calculator $this Module instance.
                 */
                do_action( 'noesia_swa_after_render_calculator_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__( 'Calculator', '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 Calculator missing-view fallback renders.
             *
             * @param Noesia_Swa_Module_Calculator $this Module instance.
             */
            do_action( 'noesia_swa_after_render_calculator_admin', $this );
        }
    }
}
