<?php

namespace Fab\Controller;

defined( 'WPINC' ) || die;

use Fab\Interfaces\JIT_Interface;
use Fab\View;

/**
 * Initiate plugins
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class BackendPage extends Base implements JIT_Interface {

    /**
     * Adds the settings submenu page for the FAB plugin in the WordPress admin menu.
     *
     * @return void
     */
    public function admin_menu_setting() {
        add_submenu_page(
            'edit.php?post_type=fab',
            __( 'Settings', 'floating-awesome-button' ),
            __( 'Settings', 'floating-awesome-button' ),
            'manage_options',
            'floating-awesome-button-setting',
            array( $this, 'page_setting' ),
            9
        );
    }

    /**
     * Page Setting
     *
     * @backend @submenu setting
     * @return  void
     */
    public function page_setting() {
        // Add custom thank you page.
        add_filter( 'admin_footer_text', array( \Fab\Controller\Custom_Footer::get_instance(), 'get_admin_footer_text' ) );

        // Grab Data.
        $features = $this->page_setting_features();

        // Handle form submission.
        $this->page_setting_submission( 'floating-awesome-button-setting', $features );

        // Get options.
        $options = \Fab\Plugin\Config::getInstance()->getConfig()->options;

        // Section.
        $sections = array();

        // Set View.
        View::RenderStatic( 'Backend.setting' );

        // Data Normalization Before Send to Component.
        // Section.
        $sections['Backend.setting']     = array(
            'name'   => __( 'Setting', 'floating-awesome-button' ),
            'active' => true,
        );
        $sections['Backend.integration'] = array( 'name' => __( 'Integration', 'floating-awesome-button' ) );
        $sections['Backend.about']       = array( 'name' => __( 'About', 'floating-awesome-button' ) );
        $nav                             = array();
        foreach ( $sections as $key => $section ) {
            $section['slug'] = str_replace( 'Backend.', '', $key );
            $nav[]           = $section;
        }

        // TODO: AFAB-326 Migrate all modules to metabox setting
        // Modules
        $modules = \FAB()->load_modules_hooks();
        foreach ( $modules as &$module ) {
            $module = $module->getVars();
        }

        // Features.
        foreach ( $features['features'] as &$feature ) {
            if ( method_exists( $feature, 'init_options' ) ) {
                $feature->init_options();
                $feature->load_options();
            }
            $feature = $feature->getVars();
        }
        // Get FAB for JS Manipulation.
        $args      = array( 'validateLocation' => false ); // We set location to false because the ordering fab shouldn't include location check.
        $fab_lists = \Fab\Model\Fab::getInstance();
        $fab_lists = $fab_lists->get_lists_of_fab( $args );
        foreach ( $fab_lists['items'] as &$fab ) {
            $fab = $fab->getVars();
        }

        // Localize Script.
        \FAB()->Helper->wp_enqueue_script( 'fab-local', 'local/fab.js', array(), FAB_VERSION, true );
        wp_localize_script(
            'fab-local',
            'FAB_SETTING',
            array(
                'status'    => false,
                'config'    => \FAB()->getConfig(),
                'sections'  => $nav,
                'modules'   => $modules,
                'fab_lists' => $fab_lists,
                'features'  => $features['features'],
                'nonce'     => array(
                    'clear'          => wp_create_nonce( 'clear-config' ),
                    'module'         => wp_create_nonce( 'module-config' ),
                    'setting'        => wp_create_nonce( 'wp_rest' ),
                    'plugin_manager' => wp_create_nonce( 'plugin_manager' ),
                ),
                'url'       => array(
                    'upgrade' => \FAB()->Helper->getUpgradeURL(),
                ),
                'labels'    => array(
                    'add'       => __( 'Add Integration', 'floating-awesome-button' ),
                    'remove'    => __( 'Remove Integration', 'floating-awesome-button' ),
                    'blog'      => __( 'Blog', 'floating-awesome-button' ),
                    'affiliate' => __( 'Affiliate Program', 'floating-awesome-button' ),
                ),
            )
        );

        // Load Component.
        \FAB()->Helper->wp_enqueue_style( 'fab-setting-component', 'build/components/setting/bundle.css' );
        \FAB()->Helper->wp_enqueue_script( 'fab-setting-component', 'build/components/setting/bundle.js', array(), FAB_VERSION, true );
    }

    /**
     * Handle Page Submission
     *
     * @param string $slug     The slug of the page.
     * @param array  $features The features of the page.
     * @return void
     */
    public function page_setting_submission( $slug, $features ) {
        if ( isset( $_GET['page'] ) && $_GET['page'] == $slug && $_POST ) {
            if ( isset( $_POST['clear-config'] ) ) { /** Clear Config */
                $this->page_setting_submission_clearconfig();
            } elseif ( isset( $_POST['module-config'] ) ) { /** Module Config */
                $this->page_setting_submission_module();
            } else { /** Save Setting */
                $this->page_setting_submission_setting( $features );
            }
        }
    }

    /**
     * Clear Config
     *
     * @return void
     */
    public function page_setting_submission_clearconfig() {
        $modules = \FAB()->getModules();
        delete_option( 'fab_config' );
        update_option( 'fab_config', \FAB()->getConfig()->default );
        foreach ( $modules as $module ) {
            delete_option( sprintf( 'fab_%s', $module->getKey() ) );
        }
        $features = $this->page_setting_features()['features'];
        foreach ( $features as $feature ) {
            delete_option( sprintf( 'fab_%s', $feature->getKey() ) );
        }
    }

    /**
     * Save Module Config
     *
     * @return void
     */
    public function page_setting_submission_module() {
        $params = $_POST;
        foreach ( $params as $key => $options ) {
            if ( strpos( $key, 'fab_' ) === false ) {
                continue; }
            update_option( $key, $options );
        }
    }

    /**
     * Save Plugin Setting
     *
     * @param array $features The features of the page.
     * @param array $params   The params of the page.
     * @return void
     */
    public function page_setting_submission_setting( $features, $params = array() ) {
        $default = \FAB()->getConfig()->default;
        $options = \FAB()->getConfig()->options;

        // Use POST data if provided, otherwise use the provided $params.
        $params = ! empty( $params ) ? $params : $_POST;

        // Sanitize & Transform Animation.
        if ( isset( $params['fab_animation'] ) ) {
            $feature = $features['features']['core_animation'];
            $feature->sanitize();
            $featureOption = ( isset( $options->fab_animation ) ) ? $options->fab_animation : $default->fab_animation;
            $feature->setOptions( $featureOption );
            $options->fab_animation = $feature->transform();
        }

        // Sanitize & Transform Order.
        if ( isset( $params['fab_design'] ) ) {
            $feature       = $features['features']['core_design'];
            $featureOption = ( isset( $options->fab_design ) ) ? $options->fab_design : $default->fab_design;
            $feature->setOptions( $featureOption );
            $feature->sanitize();
            // merge with default template to prevent error on frontend.
            $options->fab_design = json_decode( json_encode( array_replace_recursive( json_decode( json_encode( $default->fab_design ), true ), $params['fab_design'] ) ) );
        }

        // Sanitize & Transform Order.
        if ( isset( $params['fab_order'] ) ) {
            $feature = $features['features']['core_order'];
            $feature->sanitize();
            $options->fab_order = $feature->transform();
        }

        // Sanitize & Transform Feature.
        if ( isset( $params['fab_hooks'] ) ) {
            $feature = $features['features']['core_hooks'];
            $feature->sanitize();
            $options->fab_hooks = $feature->transform();
        }

        // Save config.
        update_option( 'fab_config', $options );

        /**
         * Modular Configuration Features Update
         */

        // Trigger action after settings updated.
        do_action( 'fab_settings_updated', $params );

        return wp_send_json_success(
            array(
                'status'  => 'success',
                'message' => __( 'Settings updated successfully.', 'floating-awesome-button' ),
            )
        );
    }

    /**
     * Get Lists of registered features, controller, & APIs
     *
     * @return array
     */
    public function page_setting_features() {
        return array(
            'features' => \FAB()->getFeatures(),
        );
    }

    /*
    |--------------------------------------------------------------------------
    | Fulfill implemented interface contracts
    |--------------------------------------------------------------------------
     */

    /**
     * JIT method.
     *
     * @return void
     */
    public static function jit() {
        // Add custom admin page under settings.
        add_action( 'admin_menu', array( __CLASS__, 'jit_admin_menu_setting' ) );
    }
}
