<?php

namespace forge12\floating_menu {

    use forge12\floating_menu\component\floatingmenu\FloatingMenu;
    use forge12\floating_menu\component\floatingmenu\FloatingMenuManager;

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

    /**
     * Status page — shows environment info, plugin health checks, and menu diagnostics.
     */
    class UIStatus extends UIPageForm {

        public function __construct( $domain ) {
            parent::__construct( $domain, 'status', 'Status', 20 );
            $this->hideSubmitButton( true );
        }

        public function getSettings( $settings ) {
            return $settings;
        }

        protected function theSidebar( $slug, $page ): void {
            if ( 'status' !== $page ) {
                return;
            }
            ?>
            <div class="box">
                <h2><?php _e( 'About', 'f12-floating-menu' ); ?></h2>
                <p>
                    <?php _e( 'This page shows environment details and plugin health checks to help diagnose issues.', 'f12-floating-menu' ); ?>
                </p>
            </div>
            <?php
        }

        protected function theContent( $slug, $page, $settings ): void {
            $checks = $this->runChecks();
            ?>
            <h1><?php _e( 'Status', 'f12-floating-menu' ); ?></h1>

            <!-- Environment -->
            <div class="option-section-heading" style="margin-top:0;">
                <strong><?php _e( 'Environment', 'f12-floating-menu' ); ?></strong>
            </div>
            <table class="widefat striped" style="margin-bottom:20px;">
                <tbody>
                <?php foreach ( $checks['environment'] as $row ) : ?>
                    <tr>
                        <td style="width:40%;"><strong><?php echo esc_html( $row['label'] ); ?></strong></td>
                        <td><?php echo wp_kses_post( $row['value'] ); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <!-- Integrations -->
            <div class="option-section-heading">
                <strong><?php _e( 'Integrations', 'f12-floating-menu' ); ?></strong>
            </div>
            <table class="widefat striped" style="margin-bottom:20px;">
                <tbody>
                <?php foreach ( $checks['integrations'] as $row ) : ?>
                    <tr>
                        <td style="width:40%;"><strong><?php echo esc_html( $row['label'] ); ?></strong></td>
                        <td>
                            <?php echo $row['ok'] ? '<span style="color:#46b450;">&#10004;</span>' : '<span style="color:#dc3232;">&#10006;</span>'; ?>
                            <?php echo wp_kses_post( $row['value'] ); ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

            <!-- WPML Details (only if active) -->
            <?php if ( defined( 'ICL_SITEPRESS_VERSION' ) ) : ?>
                <div class="option-section-heading">
                    <strong><?php _e( 'WPML Details', 'f12-floating-menu' ); ?></strong>
                </div>
                <table class="widefat striped" style="margin-bottom:20px;">
                    <tbody>
                    <?php foreach ( $checks['wpml'] as $row ) : ?>
                        <tr>
                            <td style="width:40%;"><strong><?php echo esc_html( $row['label'] ); ?></strong></td>
                            <td>
                                <?php if ( isset( $row['ok'] ) ) : ?>
                                    <?php echo $row['ok'] ? '<span style="color:#46b450;">&#10004;</span>' : '<span style="color:#dc3232;">&#10006;</span>'; ?>
                                <?php endif; ?>
                                <?php echo wp_kses_post( $row['value'] ); ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>

            <!-- Floating Menus -->
            <div class="option-section-heading">
                <strong><?php _e( 'Floating Menus', 'f12-floating-menu' ); ?></strong>
            </div>
            <?php if ( empty( $checks['menus'] ) ) : ?>
                <p><?php _e( 'No floating menus found.', 'f12-floating-menu' ); ?></p>
            <?php else : ?>
                <table class="widefat striped" style="margin-bottom:20px;">
                    <thead>
                        <tr>
                            <th><?php _e( 'ID', 'f12-floating-menu' ); ?></th>
                            <th><?php _e( 'Title', 'f12-floating-menu' ); ?></th>
                            <th><?php _e( 'Position', 'f12-floating-menu' ); ?></th>
                            <th><?php _e( 'Language', 'f12-floating-menu' ); ?></th>
                            <th><?php _e( 'Links', 'f12-floating-menu' ); ?></th>
                            <th><?php _e( 'Visibility', 'f12-floating-menu' ); ?></th>
                            <th><?php _e( 'Issues', 'f12-floating-menu' ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ( $checks['menus'] as $menu ) : ?>
                        <tr>
                            <td><?php echo esc_html( $menu['id'] ); ?></td>
                            <td>
                                <a href="<?php echo esc_url( get_edit_post_link( $menu['id'] ) ); ?>">
                                    <?php echo esc_html( $menu['title'] ); ?>
                                </a>
                            </td>
                            <td><?php echo esc_html( $menu['position'] ?: '—' ); ?></td>
                            <td><?php echo esc_html( $menu['language'] ?: __( 'All', 'f12-floating-menu' ) ); ?></td>
                            <td><?php echo esc_html( $menu['links'] ); ?></td>
                            <td><?php echo wp_kses_post( $menu['visibility'] ); ?></td>
                            <td>
                                <?php if ( empty( $menu['issues'] ) ) : ?>
                                    <span style="color:#46b450;">&#10004;</span>
                                <?php else : ?>
                                    <?php foreach ( $menu['issues'] as $issue ) : ?>
                                        <span style="color:#dc3232;">&#10006; <?php echo esc_html( $issue ); ?></span><br>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
            <?php
        }

        protected function onSave( $settings ) {
            return $settings;
        }

        /**
         * Run all status checks.
         *
         * @return array
         */
        private function runChecks(): array {
            $result = [
                'environment'  => $this->checkEnvironment(),
                'integrations' => $this->checkIntegrations(),
                'wpml'         => $this->checkWpml(),
                'menus'        => $this->checkMenus(),
            ];

            return $result;
        }

        /**
         * @return array
         */
        private function checkEnvironment(): array {
            global $wp_version;

            return [
                [
                    'label' => __( 'Plugin Version', 'f12-floating-menu' ),
                    'value' => FORGE12_FLOATING_VERSION,
                ],
                [
                    'label' => __( 'WordPress Version', 'f12-floating-menu' ),
                    'value' => $wp_version,
                ],
                [
                    'label' => __( 'PHP Version', 'f12-floating-menu' ),
                    'value' => PHP_VERSION,
                ],
                [
                    'label' => __( 'Active Theme', 'f12-floating-menu' ),
                    'value' => wp_get_theme()->get( 'Name' ) . ' ' . wp_get_theme()->get( 'Version' ),
                ],
                [
                    'label' => __( 'Multisite', 'f12-floating-menu' ),
                    'value' => is_multisite() ? __( 'Yes', 'f12-floating-menu' ) : __( 'No', 'f12-floating-menu' ),
                ],
            ];
        }

        /**
         * @return array
         */
        private function checkIntegrations(): array {
            $checks = [];

            // WPML
            $wpml_active = defined( 'ICL_SITEPRESS_VERSION' );
            $checks[]    = [
                'label' => 'WPML SitePress',
                'ok'    => $wpml_active,
                'value' => $wpml_active
                    ? sprintf( __( 'Active (v%s)', 'f12-floating-menu' ), ICL_SITEPRESS_VERSION )
                    : __( 'Not active', 'f12-floating-menu' ),
            ];

            // WPML String Translation
            $wpml_st = defined( 'WPML_ST_VERSION' );
            $checks[] = [
                'label' => 'WPML String Translation',
                'ok'    => $wpml_st,
                'value' => $wpml_st
                    ? sprintf( __( 'Active (v%s)', 'f12-floating-menu' ), WPML_ST_VERSION )
                    : __( 'Not active — menu item labels cannot be translated', 'f12-floating-menu' ),
            ];

            // ICL_SITEPRESS_VERSION constant
            $checks[] = [
                'label' => 'ICL_SITEPRESS_VERSION',
                'ok'    => $wpml_active,
                'value' => $wpml_active ? '<code>defined</code>' : '<code>not defined</code>',
            ];

            // ICL_LANGUAGE_CODE constant
            $icl_lang = defined( 'ICL_LANGUAGE_CODE' );
            $checks[] = [
                'label' => 'ICL_LANGUAGE_CODE',
                'ok'    => $icl_lang,
                'value' => $icl_lang
                    ? '<code>' . esc_html( ICL_LANGUAGE_CODE ) . '</code>'
                    : '<code>not defined</code>',
            ];

            // wpml_active_languages filter
            $wpml_langs  = apply_filters( 'wpml_active_languages', [], 'skip_missing=0' );
            $langs_work  = is_array( $wpml_langs ) && ! empty( $wpml_langs );
            $checks[]    = [
                'label' => 'wpml_active_languages filter',
                'ok'    => $langs_work,
                'value' => $langs_work
                    ? sprintf( __( '%d languages: %s', 'f12-floating-menu' ), count( $wpml_langs ), implode( ', ', array_keys( $wpml_langs ) ) )
                    : __( 'Returns empty — language dropdown will have no options', 'f12-floating-menu' ),
            ];

            // icl_get_languages function
            $icl_func = function_exists( 'icl_get_languages' );
            $checks[] = [
                'label' => 'icl_get_languages()',
                'ok'    => $icl_func,
                'value' => $icl_func ? '<code>available</code>' : '<code>not available</code>',
            ];

            return $checks;
        }

        /**
         * @return array
         */
        private function checkWpml(): array {
            if ( ! defined( 'ICL_SITEPRESS_VERSION' ) ) {
                return [];
            }

            $checks = [];

            // Current admin language
            $admin_lang = apply_filters( 'wpml_current_language', '' );
            $checks[]   = [
                'label' => __( 'Current Admin Language', 'f12-floating-menu' ),
                'value' => '<code>' . esc_html( $admin_lang ) . '</code>',
            ];

            // Default language
            $default_lang = apply_filters( 'wpml_default_language', '' );
            $checks[]     = [
                'label' => __( 'Default Language', 'f12-floating-menu' ),
                'value' => '<code>' . esc_html( $default_lang ) . '</code>',
            ];

            // Post type translation mode
            $is_translated = apply_filters( 'wpml_is_translated_post_type', null, 'floating_menu' );
            $checks[]      = [
                'label' => __( 'floating_menu translatable', 'f12-floating-menu' ),
                'ok'    => ! $is_translated,
                'value' => $is_translated
                    ? __( 'Yes — this can cause menus to be filtered by language!', 'f12-floating-menu' )
                    : __( 'No (correct)', 'f12-floating-menu' ),
            ];

            return $checks;
        }

        /**
         * @return array
         */
        private function checkMenus(): array {
            $menus  = FloatingMenuManager::getInstance()->getList();
            $result = [];

            foreach ( $menus as $Menu /** @var FloatingMenu $Menu */ ) {
                $settings = $Menu->getSettings();
                $issues   = [];

                // Check position
                $position = $Menu->getPosition();
                if ( empty( $position ) || 'hidden' === $position ) {
                    $issues[] = __( 'Position is hidden', 'f12-floating-menu' );
                }

                // Check links
                $links = $Menu->getLinks();
                if ( empty( $links ) ) {
                    $issues[] = __( 'No links defined', 'f12-floating-menu' );
                }

                // Check visibility
                $visibility_parts = [];
                if ( ! empty( $settings['pages_all'] ) && 1 == $settings['pages_all'] ) {
                    $visibility_parts[] = __( 'All pages', 'f12-floating-menu' );
                }
                $post_types = $Menu->getPostTypes();
                if ( ! empty( $post_types ) ) {
                    $visibility_parts[] = sprintf( __( 'Post types: %s', 'f12-floating-menu' ), implode( ', ', $post_types ) );
                }
                $pages = $settings['pages'] ?? '';
                if ( ! empty( $pages ) ) {
                    $visibility_parts[] = sprintf( __( 'Page IDs: %s', 'f12-floating-menu' ), $pages );
                }
                if ( empty( $visibility_parts ) ) {
                    $issues[]           = __( 'No visibility rules — menu will not appear', 'f12-floating-menu' );
                    $visibility_parts[] = '—';
                }

                // Language
                $language = $settings['wpml_language'] ?? '';

                $result[] = [
                    'id'         => $Menu->getID(),
                    'title'      => get_the_title( $Menu->getID() ),
                    'position'   => $position,
                    'language'   => $language,
                    'links'      => count( $links ),
                    'visibility' => implode( '<br>', $visibility_parts ),
                    'issues'     => $issues,
                ];
            }

            return $result;
        }
    }
}
