<?php

namespace MasterCustomBreakPoint\Inc;

use MasterCustomBreakPoint\JLTMA_Master_Custom_Breakpoint;
use Elementor\Plugin;
defined( 'ABSPATH' ) || exit;
class JLTMA_Master_Custom_Breakpoint_Hooks {
    public function __construct() {
        add_action( 'admin_menu', [$this, 'jltma_mcb_menu'], 55 );
        // Reset Form
        add_action( 'wp_ajax_jltma_mcb_reset_settings', [$this, 'jltma_mcb_reset_settings'] );
        // Save Breakpoint Settings
        add_action( 'wp_ajax_jltma_mcb_save_settings', [$this, 'jltma_mcb_save_settings'] );
        add_action( 'tgmpa_register', [$this, 'jltma_mcb__register_required_plugins'] );
        add_action( 'admin_enqueue_scripts', [$this, 'hooks_scripts'] );
    }

    public function jltma_mcb_menu() {
        if ( !function_exists( 'is_plugin_active' ) ) {
            require_once ABSPATH . '/wp-admin/includes/plugin.php';
        }
        $page_title = esc_html__( 'Custom Breakpoints for Elementor', JLTMA_MCB_TD );
        $menu_title = esc_html__( 'Breakpoints', JLTMA_MCB_TD );
        $capability = 'manage_options';
        $menu_slug = 'custom-breakpoints-for-elementor';
        $callback = array($this, 'jltma_mcb_content');
        if ( is_plugin_active( 'master-addons/master-addons.php' ) || is_plugin_active( 'master-addons-pro/master-addons.php' ) ) {
            return add_submenu_page(
                'master-addons-settings',
                $page_title,
                $menu_title,
                $capability,
                $menu_slug,
                $callback
            );
        }
        add_menu_page(
            $page_title,
            $menu_title,
            $capability,
            $menu_slug,
            $callback,
            'dashicons-desktop',
            57
        );
    }

    public function jltma_mcb_content() {
        ?>

        <div class="jltma-wrap">

            <?php 
        if ( isset( $_POST['updated'] ) && $_POST["updated"] === 'true' ) {
            $this->handle_form();
        }
        ?>

            <form method="POST" class="jlmta-cbp-input-form" id="jlmta-cbp-form">

                <div class="jltma-spinner"></div>

                <?php 
        wp_nonce_field( 'breakpoints_update', 'breakpoints_form' );
        ?>


                <!-- React app renders here -->
                <div id="custom_breakpoints_page"></div>

            </form>

        </div>
        <?php 
    }

    public function jltma_mcb_save_settings() {
        if ( !isset( $_POST['security'] ) || !wp_verify_nonce( $_POST['security'], 'breakpoints_update' ) ) {
            wp_send_json_error( esc_html__( 'Security Error.', JLTMA_MCB_TD ) );
        }
        $form_fields = ( isset( $_POST['form_fields'] ) ? $_POST['form_fields'] : [] );
        $custom_breakpoints = [];
        $free_limit = 1;
        $is_pro = function_exists( 'jltma_cbfe' ) && jltma_cbfe()->can_use_premium_code__premium_only();
        foreach ( $form_fields as $key => $value ) {
            if ( $value['default_value'] < 1 ) {
                continue;
            }
            // Pro users have unlimited breakpoints, free users limited to 1
            if ( !$is_pro ) {
                if ( count( $custom_breakpoints ) >= $free_limit ) {
                    continue;
                }
            }
            $custom_breakpoints["breakpoint{$key}"] = [
                'label'         => sanitize_text_field( $value['label'] ),
                'default_value' => (int) $value['default_value'],
                'direction'     => sanitize_text_field( $value['direction'] ),
            ];
        }
        update_option( 'jltma_mcb', $custom_breakpoints );
        die;
    }

    public function handle_form() {
        // Save Breakpoints
        if ( !isset( $_POST['breakpoints_form'] ) || !wp_verify_nonce( $_POST['breakpoints_form'], 'breakpoints_update' ) ) {
            ?>
            <div class="error">
                <p>
                    <?php 
            echo esc_html__( 'Sorry, your nonce was not correct. Please try again.', JLTMA_MCB_TD );
            ?>
                </p>
            </div>
        <?php 
            exit;
        } else {
            $data_updated = false;
            //CUSTOM BREAKPOINTS FILE SAVE
            $custom_breakpoints = [];
            if ( is_array( $_REQUEST["breakpoint_select1"] ) || is_object( $_REQUEST["breakpoint_select1"] ) ) {
                foreach ( $_REQUEST["breakpoint_select1"] as $key => $select1_value ) {
                    $custom_breakpoints["breakpoint{$key}"] = [
                        'name'        => sanitize_text_field( $_REQUEST["breakpoint_name"][$key] ),
                        'input1'      => $_REQUEST["breakpoint_input1"][$key],
                        'input2'      => $_REQUEST["breakpoint_input2"][$key],
                        'orientation' => sanitize_title( $_REQUEST["orientation"][$key] ),
                    ];
                }
                if ( !empty( $custom_breakpoints ) ) {
                    update_option( 'jltma_mcb', $custom_breakpoints );
                    $data_updated = get_option( 'jltma_mcb', $custom_breakpoints );
                }
                //CUSTOM BREAKPOINTS SAVE END
                if ( $data_updated ) {
                    echo "\n                        <div class='updated'>\n                            <p>Saved Breakpoints</p>\n                        </div>\n                        <script>\n                            jQuery(document).ready(function() {\n                               setTimeout(function() {\n                                    window.location.reload();\n                                }, 2000);\n                            });\n                        </script>\n                    ";
                } else {
                    echo "<div class='error'>\n                            <p>Custom Breakpoints cannot be updated</p>\n                        </div>";
                }
            }
        }
    }

    // Reset Settings
    public function jltma_mcb_reset_settings() {
        if ( !isset( $_POST['security'] ) || !wp_verify_nonce( $_POST['security'], 'breakpoints_reset' ) ) {
            wp_send_json_error( esc_html__( 'Security Error.', JLTMA_MCB_TD ) );
        }
        delete_option( 'jltma_mcb' );
        echo json_encode( 'ok' );
        die;
    }

    public function jltma_mcb__register_required_plugins() {
        /*
         * Array of plugin arrays. Required keys are name and slug.
         * If the source is NOT from the .org repo, then source is also required.
         */
        $plugins = array(array(
            'name'             => esc_html__( 'Elementor', 'custom-breakpoints-for-elementor' ),
            'slug'             => 'elementor',
            'required'         => false,
            'force_activation' => false,
        ));
        /*
         * Array of configuration settings. Amend each line as needed.
         *
         * TGMPA will start providing localized text strings soon. If you already have translations of our standard
         * strings available, please help us make TGMPA even better by giving us access to these translations or by
         * sending in a pull-request with .po file(s) with the translations.
         *
         * Only uncomment the strings in the config array if you want to customize the strings.
         */
        $config = array(
            'id'           => 'custom-breakpoints-for-elementor',
            'default_path' => '',
            'menu'         => 'tgmpa-install-plugins',
            'parent_slug'  => 'plugins.php',
            'capability'   => 'manage_options',
            'has_notices'  => true,
            'dismissable'  => true,
            'dismiss_msg'  => '',
            'is_automatic' => false,
            'message'      => '',
            'strings'      => array(
                'page_title'                      => __( 'Install Required Plugins', 'custom-breakpoints-for-elementor' ),
                'menu_title'                      => __( 'Install Plugins', 'custom-breakpoints-for-elementor' ),
                'installing'                      => __( 'Installing Plugin: %s', 'custom-breakpoints-for-elementor' ),
                'updating'                        => __( 'Updating Plugin: %s', 'custom-breakpoints-for-elementor' ),
                'oops'                            => __( 'Something went wrong with the plugin API.', 'custom-breakpoints-for-elementor' ),
                'notice_can_install_required'     => _n_noop( 'This theme requires the following plugin: %1$s.', 'This theme requires the following plugins: %1$s.', 'custom-breakpoints-for-elementor' ),
                'notice_can_install_recommended'  => _n_noop( 'This theme recommends the following plugin: %1$s.', 'This theme recommends the following plugins: %1$s.', 'custom-breakpoints-for-elementor' ),
                'notice_ask_to_update'            => _n_noop( 'The following plugin needs to be updated to its latest version to ensure maximum compatibility with this theme: %1$s.', 'The following plugins need to be updated to their latest version to ensure maximum compatibility with this theme: %1$s.', 'custom-breakpoints-for-elementor' ),
                'notice_ask_to_update_maybe'      => _n_noop( 'There is an update available for: %1$s.', 'There are updates available for the following plugins: %1$s.', 'custom-breakpoints-for-elementor' ),
                'notice_can_activate_required'    => _n_noop( 'The following required plugin is currently inactive: %1$s.', 'The following required plugins are currently inactive: %1$s.', 'custom-breakpoints-for-elementor' ),
                'notice_can_activate_recommended' => _n_noop( 'The following recommended plugin is currently inactive: %1$s.', 'The following recommended plugins are currently inactive: %1$s.', 'custom-breakpoints-for-elementor' ),
                'install_link'                    => _n_noop( 'Begin installing plugin', 'Begin installing plugins', 'custom-breakpoints-for-elementor' ),
                'update_link'                     => _n_noop( 'Begin updating plugin', 'Begin updating plugins', 'custom-breakpoints-for-elementor' ),
                'activate_link'                   => _n_noop( 'Begin activating plugin', 'Begin activating plugins', 'custom-breakpoints-for-elementor' ),
                'return'                          => __( 'Return to Required Plugins Installer', 'custom-breakpoints-for-elementor' ),
                'plugin_activated'                => __( 'Plugin activated successfully.', 'custom-breakpoints-for-elementor' ),
                'activated_successfully'          => __( 'The following plugin was activated successfully:', 'custom-breakpoints-for-elementor' ),
                'plugin_already_active'           => __( 'No action taken. Plugin %1$s was already active.', 'custom-breakpoints-for-elementor' ),
                'plugin_needs_higher_version'     => __( 'Plugin not activated. A higher version of %s is needed for this theme. Please update the plugin.', 'custom-breakpoints-for-elementor' ),
                'complete'                        => __( 'All plugins installed and activated successfully. %1$s', 'custom-breakpoints-for-elementor' ),
                'dismiss'                         => __( 'Dismiss this notice', 'custom-breakpoints-for-elementor' ),
                'notice_cannot_install_activate'  => __( 'There are one or more required or recommended plugins to install, update or activate.', 'custom-breakpoints-for-elementor' ),
                'contact_admin'                   => __( 'Please contact the administrator of this site for help.', 'custom-breakpoints-for-elementor' ),
                'nag_type'                        => '',
            ),
        );
        tgmpa( $plugins, $config );
    }

    /**
     * Check if Elementor is active and loaded
     *
     * @return bool
     */
    public function is_elementor_active() {
        if ( !function_exists( 'is_plugin_active' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        return is_plugin_active( 'elementor/elementor.php' ) && did_action( 'elementor/loaded' ) && class_exists( '\\Elementor\\Plugin' );
    }

    public function hooks_scripts() {
        // Check for the correct screen ID
        $screen = get_current_screen();
        // Only run on our plugin's admin page
        if ( $screen->id !== 'toplevel_page_custom-breakpoints-for-elementor' && $screen->id !== 'master-addons_page_custom-breakpoints-for-elementor' ) {
            return;
        }
        // Check if Elementor is active before proceeding
        if ( !$this->is_elementor_active() ) {
            return;
        }
        wp_enqueue_style( 'master-cbp-admin', JLTMA_MCB_PLUGIN_URL . 'assets/css/master-cbp-admin.css' );
        // Enqueue React admin script with wp-element dependency
        wp_enqueue_script(
            'jltma-breakpoints-admin',
            JLTMA_MCB_PLUGIN_URL . 'assets/js/breakpoints-admin.js',
            ['wp-element', 'jquery'],
            JLTMA_MCB_VERSION,
            true
        );
        $breakpoints = Plugin::$instance->breakpoints->get_active_breakpoints();
        $breakpoints = array_map( function ( $breakpoint ) {
            return [
                'name' => $breakpoint->get_label(),
                'key'  => $breakpoint->get_name(),
                'max'  => $breakpoint->get_default_value(),
            ];
        }, $breakpoints );
        $default_breakpoints = array_keys( Plugin::$instance->breakpoints->get_default_config() );
        $upgrade_url = jltma_cbfe()->get_upgrade_url();
        $data = [
            'breakpoints'     => array_values( $breakpoints ),
            'default_devices' => $default_breakpoints,
            'ajaxurl'         => admin_url( 'admin-ajax.php' ),
            'upgrade_url'     => $upgrade_url,
            'reset_nonce'     => wp_create_nonce( "breakpoints_reset" ),
        ];
        wp_localize_script( 'jltma-breakpoints-admin', 'jltma_custom_bp_data', $data );
    }

}

new JLTMA_Master_Custom_Breakpoint_Hooks();