<?php

namespace Dracula;

defined( 'ABSPATH' ) || exit;

class Admin {

    private static $instance = null;

    public $admin_pages = array(
            'toggle_builder' => '',
    );

    public function __construct() {
        add_action( 'admin_head', [ $this, 'remove_admin_notices' ] );
        add_action( 'admin_menu', array( $this, 'add_admin_menu' ) );

        $admin_dark_mode          = dracula_get_settings( 'adminDarkMode', true );
        $classic_editor_dark_mode = dracula_get_settings( 'classicEditorDarkMode', false );
        $block_editor_dark_mode   = dracula_get_settings( 'blockEditorDarkMode', false );

        if ( $admin_dark_mode || $classic_editor_dark_mode || $block_editor_dark_mode ) {
            add_action( 'admin_head', array( $this, 'header_scripts' ) );
        }

        if ( $admin_dark_mode ) {

            if ( 'adminbar' === dracula_get_settings( 'adminDarkModePosition', 'adminbar' ) ) {
                add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_menu' ), 9999 );
            }

            add_action( 'admin_init', array( $this, 'add_admin_color_scheme' ) );
            add_action( 'admin_color_scheme_picker', array( $this, 'add_user_profile_fields' ), 11 );
            add_action( 'personal_options_update', array( $this, 'save_user_profile_fields' ) );

            if ( 'floating' === dracula_get_settings( 'adminDarkModePosition' ) ) {
                add_action( 'admin_footer', array( $this, 'render_admin_toggle' ) );
            }
        }

        add_action( 'admin_init', array( $this, 'includes' ) );
        add_action( 'in_admin_header', array( $this, 'remove_admin_notices' ) );

        // Menu Metabox
        if ( dracula_get_settings( 'displayInMenu' ) ) {
            add_action( 'admin_head-nav-menus.php', array( $this, 'switch_meta_box' ) );

            // Menu Custom Fields
            add_action( 'wp_nav_menu_item_custom_fields', array( $this, 'edit_switch_item' ), 10, 5 );

            // Save Menu Custom Fields
            add_action( 'wp_update_nav_menu_item', array( $this, 'save_switch_item' ), 10, 3 );
        }

        // Update
        add_action( 'admin_init', array( $this, 'init_update' ) );

    }

    public function remove_admin_notices() {
        global $current_screen;

        if ( ! empty( $current_screen ) && ! in_array( $current_screen->id, [
                        'dracula_page_dracula-getting-started',
                        'dracula_page_dracula-toggle-builder',
                        'toplevel_page_dracula',
                ] ) ) {
            return;
        }

        remove_all_actions( 'admin_notices' );
        remove_all_actions( 'all_admin_notices' );

        add_filter( 'admin_footer_text', '__return_empty_string' );
        add_filter( 'update_footer', '__return_empty_string' );
    }

    public function add_user_profile_fields( $user_id ) {
        if ( ! dracula_is_user_dark_mode() ) {
            return;
        }

        $profile_user = get_userdata( $user_id );

        ?>
        <tr class="show-admin-bar user-admin-bar-front-wrap">
            <th scope="row"><?php esc_html_e( 'Show Dark Mode Toggle', 'dracula-dark-mode' ); ?></th>
            <td>
                <label for="admin_bar_toggle">
                    <input name="admin_bar_toggle" type="checkbox" id="admin_bar_toggle"
                           value="on" <?php checked( 'off' != $profile_user->admin_bar_toggle ); ?> />
                    <?php esc_html_e( 'Show dark mode toggle in the top admin bar.', 'dracula-dark-mode' ); ?>
                </label><br/>
            </td>
        </tr>
    <?php }

    public function save_user_profile_fields( $user_id ) {
        if ( ! dracula_is_user_dark_mode() ) {
            return;
        }

        if ( ! current_user_can( 'edit_user', $user_id ) ) {
            return;
        }

        $admin_bar_toggle = isset( $_POST['admin_bar_toggle'] ) ? 'on' : 'off';

        update_user_meta( $user_id, 'admin_bar_toggle', $admin_bar_toggle );
    }

    public function includes() {
        $is_user_dark_mode        = dracula_is_user_dark_mode();
        $dashboard_dark_mode      = dracula_get_settings( 'adminDarkMode', true );
        $classic_editor_dark_mode = dracula_get_settings( 'classicEditorDarkMode', true );

        if ( $is_user_dark_mode && $dashboard_dark_mode && $classic_editor_dark_mode ) {
            include_once DRACULA_INCLUDES . '/class-tinymce.php';
        }
    }

    public function header_scripts() { ?>

        <script>
            const savedMode = localStorage.getItem('dracula_mode_admin');

            if (savedMode) {
                window.draculaMode = savedMode;
            }

            if ('dark' === window.draculaMode) {
                window.draculaDarkMode.enable();
            } else if ('auto' === window.draculaMode) {
                window.draculaDarkMode.auto();
            }
        </script>
        <?php
    }

    public function add_admin_color_scheme() {
        if ( ! dracula_is_user_dark_mode() ) {
            return;
        }

        $admin_background_color = dracula_get_settings( 'adminBackgroundColor', '#181a1b' );
        $admin_text_color       = dracula_get_settings( 'adminTextColor', '#e8e6e3' );

        wp_admin_css_color( 'z_dracula', esc_html__( 'Dark Mode', 'dracula-dark-mode' ), '', [
                $admin_background_color,
                $admin_text_color
        ], '' );
    }

    public function add_admin_bar_menu( $wp_admin_bar ) {

        if ( $this->should_exclude_darkmode() ) {
            return;
        }

        $user_id = get_current_user_id();

        if ( ! $user_id ) {
            return;
        }

        $admin_bar_toggle = get_user_meta( $user_id, 'admin_bar_toggle', true );
        if ( $admin_bar_toggle == 'off' ) {
            return;
        }

        $button_html = '
    <button
        class="dracula-toggle admin-menu-item dracula-ignore style-14"
        onclick="draculaDarkMode.toggle()"
        type="button"
    >
        <i class="dracula-toggle-icon"></i>
    </button>
';

        $args = [
                'parent' => 'top-secondary',
                'id'     => 'dracula',
                'title'  => wp_kses(
                        $button_html,
                        [
                                'button' => [
                                        'class'   => true,
                                        'onclick' => true,
                                        'type'    => true,
                                ],
                                'i'      => [
                                        'class' => true,
                                ],
                        ]
                ),
        ];

        $wp_admin_bar->add_node( $args );
    }

    public function render_admin_toggle() {
        if ( $this->should_exclude_darkmode() ) {
            return;
        }

        $button_html =

                /* translators: 1: Light, 2: Dark */
                sprintf( '
                    <div class="dracula-toggle-wrap floating position-right">
                        <button
                            class="dracula-toggle dracula-ignore style-2"
                            onclick="draculaDarkMode.toggle()"
                            type="button"
                        >
                            <div class="dracula-toggle-icon-wrap">
                                <div class="dracula-toggle-icon"></div>
                            </div>
                            <div class="dracula-toggle-label">
                                <span class="--light">%1$s</span>
                                <span class="--dark">%2$s</span>
                            </div>
                        </button>
                    </div>
                    ', esc_html__( 'Light', 'dracula-dark-mode' ), esc_html__( 'Dark', 'dracula-dark-mode' ) );

        // Output the HTML safely, allowing only required tags/attributes
        echo wp_kses(
                $button_html,
                [
                        'div'    => [
                                'class' => true,
                        ],
                        'button' => [
                                'class'   => true,
                                'onclick' => true,
                                'type'    => true,
                        ],
                        'span'   => [
                                'class' => true,
                        ],
                ]
        );
    }

    public function add_admin_menu() {
        $this->admin_pages['dracula'] = add_menu_page( 'Dracula Dark Mode', 'Dark Mode', 'manage_options', 'dracula', array(
                $this,
                'admin_page'
        ), DRACULA_ASSETS . '/images/dracula-icon.svg', 50 );

        // Settings Page
        $this->admin_pages['settings'] = add_submenu_page( 'dracula', esc_html__( 'Settings - Dracula', 'dracula-dark-mode' ), esc_html__( 'Settings', 'dracula-dark-mode' ), 'manage_options', 'dracula' );

        // Toggle Builder Page
        $this->admin_pages['toggle_builder'] = add_submenu_page(
                'dracula',
                esc_html__( 'Toggle Builder - Dracula', 'dracula-dark-mode' ),
                esc_html__( 'Toggle Builder', 'dracula-dark-mode' ),
                'manage_options',
                'dracula-toggle-builder',
                array( $this, 'render_toggle_builder_page' )
        );

        // Getting Started Page
        $this->admin_pages['getting_started'] = add_submenu_page( 'dracula', esc_html__( 'Getting Started - Dracula', 'dracula-dark-mode' ), esc_html__( 'Getting Started', 'dracula-dark-mode' ), 'manage_options', 'dracula-getting-started', array(
                $this,
                'render_getting_started_page'
        ) );

        // Analytics Page
        if ( ! dracula()->is_pro_active() || dracula_get_settings( 'enableAnalytics' ) ) {
            $this->admin_pages['analytics'] = add_submenu_page( 'dracula', esc_html__( 'Analytics - Dracula Dark Mode', 'dracula-dark-mode' ), esc_html__( 'Analytics', 'dracula-dark-mode' ), 'manage_options', 'dracula-analytics', array(
                    $this,
                    'render_analytics_page'
            ) );
        }

        // Upgrade Menu Page - Only if Pro is not active
        if ( ! dracula()->is_pro_active() ) {
            $this->admin_pages['upgrade_page'] = add_submenu_page(
                    'dracula',
                    esc_html__( 'Upgrade to Pro - Dracula Dark Mode', 'dracula-dark-mode' ),
                    '<i class="dracula-icon icon-pro"></i>' . esc_html__( 'Upgrade', 'dracula-dark-mode' ),
                    'manage_options',
                    'https://softlabbd.com/dracula-dark-mode-pricing/?utm_source=free_plugin&utm_medium=admin_menu&utm_campaign=dracula_dark_mode_upgrade',
                    '',
                    '99'
            );
        }

    }

    public function render_getting_started_page() {
        if ( isset( $_GET['setup_complete'] ) ) {
            update_option( 'dracula_setup_complete', true );
        }

        if ( get_option( 'dracula_setup_complete' ) ) {
            include_once DRACULA_INCLUDES . '/views/getting-started/index.php';
        } else {
            include_once DRACULA_INCLUDES . '/views/setup.php';
        }
    }

    public function admin_page() { ?>
        <div id="dracula-settings-app"></div>
    <?php }

    public function render_toggle_builder_page() { ?>
        <div id="dracula-toggle-builder"></div>
    <?php }

    public function render_analytics_page() { ?>
        <div id="dracula-analytics"></div>
    <?php }

    public function get_admin_pages() {
        return $this->admin_pages;
    }

    /**
     * Whether Dark Mode should be excluded (e.g., during onboarding).
     */
    public function should_exclude_darkmode() {
        // Only relevant in wp-admin with screens available.
        if ( ! is_admin() || ! function_exists( 'get_current_screen' ) ) {
            return false;
        }

        $screen = get_current_screen();
        if ( ! $screen || empty( $screen->id ) ) {
            return false;
        }

        if ( $screen->id === 'dark-mode_page_dracula-getting-started' ) {
            // Exclude until setup is complete.
            return ! get_option( 'dracula_setup_complete', false );
        }

        return false;
    }

    public function switch_meta_box() {

        // Add meta box.
        add_meta_box(
                'dracula_dark_mode_nav_link',
                esc_html__( 'Dark Mode Switcher', 'dracula-dark-mode' ),
                [ $this, 'render_menu_switch' ],
                'nav-menus',
                'side',
                'low'
        );

    }

    public function render_menu_switch() {
        ?>
        <div id="posttype-dracula-dark-mode-switcher" class="posttypediv">
            <div id="tabs-panel-darkmode-switcher-endpoints" class="tabs-panel tabs-panel-active">
                <ul id="darkmode-switcher-endpoints-checklist" class="categorychecklist form-no-clear">
                    <li>
                        <label class="menu-item-title">
                            <input type="checkbox" class="menu-item-checkbox" name="menu-item[-1][menu-item-object-id]"
                                   checked value="-1"/>
                            <?php esc_html_e( 'Dark Mode Switcher', 'dracula-dark-mode' ); ?>
                        </label>

                        <input type="hidden" class="menu-item-object" name="menu-item[-1][menu-item-object]"
                               value="dracula-dark-mode-switch"/>
                        <input type="hidden" class="menu-item-type" name="menu-item[-1][menu-item-type]"
                               value="dracula-dark-mode-switch"/>
                        <input type="hidden" class="menu-item-title" name="menu-item[-1][menu-item-title]"
                               value="Dark Mode Switcher"/>
                        <input type="hidden" class="menu-item-description" name="menu-item[-1][menu-item-description]"
                               value="Dark Mode Switcher"/>
                        <input type="hidden" class="menu-item-type" name="menu-item[-1][menu-item-style]" value="1"/>
                    </li>
                </ul>
            </div>

            <p class="button-controls">
                <span class="add-to-menu">
                    <button type="submit" class="button-secondary submit-add-to-menu right"
                            name="add-post-type-menu-item" id="submit-posttype-dracula-dark-mode-switcher">
                        <?php esc_attr_e( 'Add to Menu', 'dracula-dark-mode' ); ?>
                    </button>
                    <span class="spinner"></span>
                </span>
            </p>
        </div>
        <?php
    }

    public function edit_switch_item( $item_id = null, $menu_item = null, $depth = null, $args = null, $current_object_id = null ) {

        // return if menu_item, item_id is null
        if ( ! $menu_item || ! $item_id ) {
            return;
        }

        // return if object not dracula-dark-mode-switch
        if ( $menu_item->object !== 'dracula-dark-mode-switch' ) {
            return;
        }

        $style_id = get_post_meta( $item_id, 'dracula_dark_mode_switch', true ) ?? 1;

        ?>
        <div class="dracula-dark-mode-switches-panel">
            <h3 class="label"><?php echo esc_html__( 'Switch Style', 'dracula-dark-mode' ) ?></h3>

            <div class="dracula-dark-mode-switches" id="dracula-dark-mode-switches"
                 data-style="<?php echo esc_attr( $style_id ) ?>"></div>

            <input type="hidden" name="menu-item[<?php echo esc_attr( $item_id ) ?>][menu-item-style]"
                   value="<?php echo esc_attr( $style_id ) ?>">
        </div>
        <?php
    }

    public function save_switch_item( $menu_id = null, $menu_item_db_id = null, $args = null ) {
        // return if args is empty
        if ( ! $args || empty( $args ) ) {
            return;
        }

        // return if menu-item-object is not dracula-dark-mode-switch
        if ( $args['menu-item-object'] !== 'dracula-dark-mode-switch' ) {
            return;
        }

        // get style id
        $style_id = isset( $_REQUEST['menu-item'][ $menu_item_db_id ]['menu-item-style'] ) ? intval( $_REQUEST['menu-item'][ $menu_item_db_id ]['menu-item-style'] ) : 1;

        // update post meta
        update_post_meta( $menu_item_db_id, 'dracula_dark_mode_switch', $style_id );
    }

    /**
     * Run update
     *
     * @since 1.3.3
     */
    public function init_update() {
        require_once DRACULA_INCLUDES . '/class-update.php';

        $updater = new Update();

        if ( $updater->needs_update() ) {
            $updater->perform_updates();
        }

        // do redirect
        if ( get_option( 'dracula_do_activation_redirect' ) ) {
            delete_option( 'dracula_do_activation_redirect' );
            wp_safe_redirect( admin_url( 'admin.php?page=dracula-getting-started' ) );
            exit;
        }
    }

    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self;
        }

        return self::$instance;
    }
}

Admin::instance();
