<?php
/**
 * Setup menus in emc admin.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

if ( ! class_exists( 'emc_admin_menus' ) ) :

/**
 * emc_admin_menus Class
 */
class emc_admin_menus {
    
    private $tabs;   
    public $settings = array();
    private $display_additional_output = false;
    
    /**
     * @var The single instance of the class
     */
    protected static $_instance = null;
    
    /**
     * Instance
     *
     * Ensures only one instance of emc_admin_menus is loaded or can be loaded.
     * Used for launching emc_admin_menus only after woocommerce is loaded
     * @static
     * @return envoimoinscher - Main instance
     */
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

	/**
	 * Hook in tabs.
	 */
	public function __construct() {

		// Add menus
		add_action( 'admin_menu', array( &$this, 'emc_menu' ), 30 );
		
		// Add styles
		add_action( 'admin_enqueue_scripts', array( &$this, 'admin_styles' ) );
        
        // update user options
        add_action( 'admin_init', array( &$this, 'update_user_options' ), 9 );

        // load settings
		add_action( 'admin_init', array( &$this, 'load_settings' ), 10 );

        // process form submission
        add_action('admin_init', array(&$this, 'process_request'), 11 );
	}
    
    /**
	 * Load settings
	 */
	public function load_settings() {
        include_once( 'class-emc-admin-settings.php' );
        
        include_once( 'settings/class-emc-settings-account.php' );
		include_once( 'settings/class-emc-settings-shipping-description.php' );
		include_once( 'settings/class-emc-settings-carriers.php' );
		include_once( 'settings/class-emc-settings-simulator.php' );
		include_once( 'settings/class-emc-settings-help.php' );
        
		$this->settings['account'] = new emc_settings_account();
		$this->settings['shipping-description'] = new emc_settings_shipping_description();
		$this->settings['carriers'] = new emc_settings_carriers();
		$this->settings['simulator'] = new emc_settings_simulator();
		$this->settings['help'] = new emc_settings_help();
    }
	
	/**
	 * Enqueue styles
	 */
	public function admin_styles( $hook ) {
		global $wp_scripts;
        global $post_type;

		$screen = get_current_screen();
        $current_tab = ( empty( $_GET['tab'] ) ) ? 'account' : urldecode( $_GET['tab'] );
        
        // notices css & js is on all pages
        wp_enqueue_style( 'emc_notices_css', plugins_url( '/assets/css/notices.css', EMC_PLUGIN_FILE ), array(), EMC_VERSION );
        wp_enqueue_script( 'emc_notices_script', plugins_url( '/assets/js/admin/emc_admin_notices.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), EMC_VERSION );
        $ajax_nonce = wp_create_nonce( 'boxtale_emc' );
        wp_localize_script( 'emc_notices_script', 'ajax_nonce', $ajax_nonce );

        // add assets to carrier edition pages
        if ( 'woocommerce_page_wc-settings' == $hook && $current_tab == 'shipping' ){
            wp_enqueue_style( 'emc_colorbox_styles', plugins_url( '/assets/css/colorbox.css', EMC_PLUGIN_FILE ), array(), '1.6.3' );
            wp_enqueue_script( 'emc_colorbox_script', plugins_url( '/assets/js/admin/jquery.colorbox-min.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), '1.6.3' );
            wp_enqueue_script( 'emc_settings', plugins_url( '/assets/js/admin/emc_settings.js', EMC_PLUGIN_FILE ), array( 'jquery' ), EMC_VERSION );
            wp_enqueue_style( 'multiple_select_css', plugins_url( '/assets/css/multiple-select.css', EMC_PLUGIN_FILE ), array(), '1.2.1' );
            wp_enqueue_script( 'multiple_select_js', plugins_url( '/assets/js/admin/multiple-select.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), '1.2.1' );
            
            // add nonce for security
            $ajax_nonce = wp_create_nonce( 'boxtale_emc' );
            wp_localize_script( 'emc_settings', 'ajax_nonce', $ajax_nonce );
            
            // add translation
            $translations = array(
                'selectAll' => __('Select all', 'envoimoinscher'),
                'allSelected' => __('All selected', 'envoimoinscher')
            );
            wp_localize_script( 'emc_settings', 'translations', $translations );
            
            // add admin css
            wp_enqueue_style( 'emc_admin_styles', plugins_url( '/assets/css/admin.css', EMC_PLUGIN_FILE ), array(), EMC_VERSION );
        }
        
        // add assets to emc settings pages
        if ( 'woocommerce_page_envoimoinscher-settings' == $hook ){
            wp_enqueue_script( 'woocommerce_admin', WC()->plugin_url() . '/assets/js/admin/woocommerce_admin.js', array( 'jquery', 'jquery-blockui', 'jquery-ui-sortable', 'jquery-ui-widget', 'jquery-ui-core', 'jquery-tiptip' ), WC_VERSION );
            wp_enqueue_script( 'woocommerce_settings', WC()->plugin_url() . '/assets/js/admin/settings.min.js', array( 'jquery', 'jquery-ui-datepicker', 'jquery-ui-sortable', 'iris', 'chosen', 'jquery-tiptip' ), WC()->version, true );

            wp_enqueue_style( 'emc_colorbox_styles', plugins_url( '/assets/css/colorbox.css', EMC_PLUGIN_FILE ), array(), '1.6.3' );
            wp_enqueue_script( 'emc_colorbox_script', plugins_url( '/assets/js/admin/jquery.colorbox-min.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), '1.6.3' );
            wp_enqueue_script( 'emc_settings', plugins_url( '/assets/js/admin/emc_settings.js', EMC_PLUGIN_FILE ), array( 'jquery' ), EMC_VERSION ); 
            wp_localize_script( 'emc_settings', 'img_folder', plugins_url( '/assets/img/', EMC_PLUGIN_FILE ) );
            wp_localize_script( 'woocommerce_settings', 'woocommerce_settings_params', array(
                'i18n_nav_warning' => __( 'The changes you made will be lost if you navigate away from this page.', 'envoimoinscher' )
            ) );
            
            wp_enqueue_style( 'woocommerce_admin_styles', WC()->plugin_url() . '/assets/css/admin.css', array(), WC_VERSION );
             
            // add nonce for security
            $ajax_nonce = wp_create_nonce( 'boxtale_emc' );
            wp_localize_script( 'emc_settings', 'ajax_nonce', $ajax_nonce );
            
            // add admin css
            wp_enqueue_style( 'emc_admin_styles', plugins_url( '/assets/css/admin.css', EMC_PLUGIN_FILE ), array(), EMC_VERSION );
            
            $translations = array();
            
            // add assets to account settings page
            if ($current_tab == 'account') {
                wp_enqueue_style( 'multiple_select_css', plugins_url( '/assets/css/multiple-select.css', EMC_PLUGIN_FILE ), array(), '1.2.1' );
                wp_enqueue_script( 'multiple_select_js', plugins_url( '/assets/js/admin/multiple-select.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), '1.2.1' );

                
                $translations = array(
                    'edit_popup_title' => __( 'Edit default address', 'envoimoinscher' ),
                    'edit_button' => __('Edit address', 'envoimoinscher'),
                    'new_button' => __('Add address', 'envoimoinscher'),
                    'no_shipping_class' => __('You must first setup shipping classes', 'envoimoinscher'),
                    'add_address_fail' => __('Could not add address', 'envoimoinscher'),
                    'edit_address_fail' => __('Could not edit address', 'envoimoinscher'),
                    'remove_address_fail' => __('Could not remove address', 'envoimoinscher'),
                    'selectAll' => __('Select all', 'envoimoinscher'),
                    'allSelected' => __('All selected', 'envoimoinscher'),
                );
                wp_localize_script( 'emc_settings', 'translations', $translations );
                
                // add default shipping class
                $shipping_classes = EMC()->get_shipping_classes();
                wp_localize_script( 'emc_settings', 'shippingClasses', $shipping_classes);
            }
            
            // add translations
            $translations['decimalOnly'] = __('Please enter in decimal (.) format without thousand separators.', 'envoimoinscher');
            $translations['integerOnly'] = __('Please enter an integer.', 'envoimoinscher');
            wp_localize_script( 'emc_settings', 'translations', $translations );
        }

        // order edition page
        if( 'post.php' == $hook ){
            wp_enqueue_style( 'emc_colorbox_styles', plugins_url( '/assets/css/colorbox.css', EMC_PLUGIN_FILE ), array(), '1.6.3' );
            wp_enqueue_script( 'emc_colorbox_script', plugins_url( '/assets/js/admin/jquery.colorbox-min.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), '1.6.3' );
            wp_enqueue_script( 'emc_admin_post_script', plugins_url( '/assets/js/admin/emc_admin_post.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), EMC_VERSION );	
            
            // add nonce for security
            $ajax_nonce = wp_create_nonce( 'boxtale_emc' );
            wp_localize_script( 'emc_admin_post_script', 'ajax_nonce', $ajax_nonce );
            
            // add translations
            $translations = array(
                'remove' => __( 'remove', 'envoimoinscher' ),
            );
            wp_localize_script( 'emc_admin_post_script', 'translations', $translations );
            
            // add admin css
            wp_enqueue_style( 'emc_admin_styles', plugins_url( '/assets/css/admin.css', EMC_PLUGIN_FILE ), array(), EMC_VERSION );
        }
        
        // orders page
        if( 'edit.php' == $hook ){
            wp_enqueue_script( 'emc_admin_edit_script', plugins_url( '/assets/js/admin/emc_admin_edit.js', EMC_PLUGIN_FILE ),  array( 'jquery' ), EMC_VERSION );
            
            // add translations
            $translations = array(
                'shipment' => __( 'Shipment', 'envoimoinscher' ),
                'order' => __('Order', 'envoimoinscher'),
            );
            wp_localize_script( 'emc_admin_edit_script', 'translations', $translations );
                
            // add nonce for security
            $ajax_nonce = wp_create_nonce( 'boxtale_emc' );
            wp_localize_script( 'emc_admin_edit_script', 'ajax_nonce', $ajax_nonce );
            
            // add admin css
            wp_enqueue_style( 'emc_admin_styles', plugins_url( '/assets/css/admin.css', EMC_PLUGIN_FILE ), array(), EMC_VERSION );
        }
	}

	/**
	 * Add menu item
	 */
	public function emc_menu() {
		$emc_page = add_submenu_page( 'woocommerce', __( 'Boxtal', 'envoimoinscher' ),  __( 'Boxtal', 'envoimoinscher' ) , 'manage_woocommerce', 'envoimoinscher-settings', array( $this, 'settings_page' ) );
	}
	
	/**
	 * Init the settings page
	 */
	public function settings_page() {
        $current_tab = isset($_GET['tab']) ? $_GET['tab']:'account';
        ?>
        <div class="wrap">
            <div id="icon-options-general" class="icon32"></div>
            <?php
                $this->output_header();
            ?>
            <h2 class="nav-tab-wrapper">
                <?php   
                    // Get tabs for the settings page
                    $tabs = apply_filters( 'emc_settings_tabs_array', array() );
                    
                    foreach ( $tabs as $name => $label ) {
                        echo '<a href="' . admin_url( 'admin.php?page=envoimoinscher-settings&tab=' . $name ) . '" class="nav-tab ' . ( $current_tab == $name ? 'nav-tab-active' : '' ) . '">' . $label . '</a>';
                    }
                ?>
            </h2>
            <form method="post" id="mainform" action="">
                <?php 
                    // display sub-tabs if there are some
                    if (method_exists($this->settings[$current_tab], 'get_subtabs')) {
                        call_user_func(array($this->settings[$current_tab], 'output_subtabs'));
                    }
                    
                    call_user_func(array($this->settings[$current_tab], 'output'));
                    call_user_func(array($this->settings[$current_tab], 'action_buttons'));
                    wp_nonce_field( 'envoimoinscher-settings' ); 
                ?>
            </form>
        </div>
		<?php
        if ($this->display_additional_output === true 
            && method_exists($this->settings[$current_tab], 'additional_output')) {
            call_user_func(array($this->settings[$current_tab], 'additional_output'));
        }
	}
    
    /**
     * Adds EMC header in EMC settings
     */
    public function output_header() {
        global $pagenow;
        if ($pagenow == 'admin.php' && ($_GET['page'] == 'envoimoinscher-settings')) {
            
            // rates link is displayed according to user branding
            if (get_option('EMC_COUNTRY') == "ES") {
                $rates_link = "//ecommerce.boxtal.es/tarifas/?utm_source=woocommerce&utm_campaign=161109_TarifasWoocommerce&utm_medium=referral";
            } else {
                $rates_link = "//ecommerce.envoimoinscher.com/tarifs/?utm_source=WooCommerce&utm_medium=Referral&utm_campaign=20160412_TarifsWooCommerce";
            }

            // get logo and other links, according to language
            $language = get_locale();
            if (strtolower(substr($language, 0, 2)) == 'fr') {
                $site_link = 'http://www.envoimoinscher.com/colis/?utm_source=woocommerce&utm_campaign=161109_woocommerce_fr&utm_medium=referral';
                $img = '/assets/img/logo_fr.png';
                $configuration_guide_link = "https://resource.boxtal.com/documents/module-boxtal-woocommerce-guide-configuration.pdf";
                $shipping_guide_link = "//ecommerce.envoimoinscher.com/wp-content/uploads/2016/08/Module-Boxtal-pour-WooCommerce_Guide-dexp%C3%A9dition-1.pdf";
            } elseif (strtolower(substr($language, 0, 2)) == 'es') {
                $site_link = 'http://www.boxtal.es/paquete/?utm_source=woocommerce&utm_campaign=161108_woocommerce&utm_medium=referral';
                $img = '/assets/img/logo_oth.png';
                $configuration_guide_link = "//ecommerce.boxtal.es/wp-content/uploads/sites/3/2016/10/Gu%C3%ADa-de-Configuraci%C3%B3n-WooCommerce-1.pdf";
                $shipping_guide_link = "//ecommerce.boxtal.es/wp-content/uploads/sites/3/2016/10/Gu%C3%ADa-de-Expedici%C3%B3n-WooCommerce-1.pdf";
            } else {
                $site_link = 'http://www.boxtal.com/colis/?utm_source=woocommerce&utm_campaign=161109_woocommerce_com&utm_medium=referral';
                $img = '/assets/img/logo_oth.png';
                $configuration_guide_link = "https://resource.boxtal.com/documents/module-boxtal-woocommerce-guide-configuration.pdf";
                $shipping_guide_link = "//ecommerce.envoimoinscher.com/wp-content/uploads/2016/08/Module-Boxtal-pour-WooCommerce_Guide-dexp%C3%A9dition-1.pdf";
            }
            
            ?>
                <div class="emc-logo">
                    <a href="<?php echo $site_link; ?>" target="_blank">
                        <img src="<?php echo plugins_url( $img , EMC_PLUGIN_FILE );?>" alt="<?php _e('Boxtal', 'envoimoinscher'); ?>" />
                    </a>
                </div>
                <div class="emc-sub-logo">
                    <a class="button" href="<?php echo $rates_link; ?>" target="_blank"><?php _e('Rates', 'envoimoinscher'); ?></a>
                    <a class="button" href="<?php echo $configuration_guide_link; ?>" target="_blank"><?php _e('Configuration guide', 'envoimoinscher'); ?></a>
                    <a class="button" href="<?php echo $shipping_guide_link; ?>" target="_blank"><?php _e('Shipping guide', 'envoimoinscher'); ?></a>
                </div>
            <?php
        }
    }
    
    /**
	 * Processes request
	 */
	public function process_request() {

        // exit if nonce is not correct
        if (! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'envoimoinscher-settings' )) {
           return;
        }
        $current_tab = isset($_GET['tab']) ? $_GET['tab']:'account';

        // save fields
        if (isset($_POST['save'])) {
            call_user_func(array($this->settings[$current_tab], 'save'));
        }

        // validate additional output
        if (method_exists($this->settings[$current_tab], 'validate_additional_output')) {
            $this->display_additional_output = call_user_func(array($this->settings[$current_tab], 'validate_additional_output'));
        }
    }
    
    /**
     * Centralize user options update.
     * Update options : mail, shipping country.
     * 
     * @return Void
     */
    public function update_user_options() {
        $user_class = new Emc\User();
        $user_class->setPlatformParams(EMC_PLATFORM, WC_VERSION, EMC_VERSION);
        $user_class->setEnv('prod');
        $language = get_locale();
        $user_class->setLocale(str_replace('_', '-', $language));
        $upload_dir = wp_upload_dir();
        $user_class->setUploadDir($upload_dir['basedir']);
        
        $user_details_last_update = get_option('EMC_USER_DETAILS_UPDATE');
        if (false === $user_details_last_update || time() > ($user_details_last_update+(10 * 60))) {
            $user_class->getUserDetails();
            
            // if there is an error, stop there
            if ($user_class->curl_error || $user_class->resp_error) return;

            // update API keys
            if (isset($user_class->user_configuration['api_key_test']) && $user_class->user_configuration['api_key_test'] != "") {
                update_option('EMC_KEY_TEST', $user_class->user_configuration['api_key_test']);
            } 
            if (isset($user_class->user_configuration['api_key_prod']) && $user_class->user_configuration['api_key_prod'] != "") {
                update_option('EMC_KEY_PROD', $user_class->user_configuration['api_key_prod']);
            }

            // if no API keys, stop there
            if (!get_option('EMC_KEY_PROD') || !get_option('EMC_KEY_TEST')) return;

            // update email params
            $emails_params = array();
            if (isset($user_class->user_configuration['mails'])) {
                $emails_params = $user_class->user_configuration['mails'];
            }
            
            if( !empty($emails_params) ){
                $emails_params['label'] == 'true' ? $label = 'yes' : $label = 'no';
                $emails_params['notification'] == 'true' ? $notification = 'yes' : $notification = 'no';
                $emails_params['bill'] == 'true' ? $bill = 'yes' : $bill = 'no';  

                update_option( 'EMC_mail_label', $label );
                update_option( 'EMC_mail_notif', $notification );
                update_option( 'EMC_mail_bill', $bill );
            }

            // get shipping country from user data
            if (isset($user_class->user_configuration['default_shipping_country'])) {
                $default_shipping_country = $user_class->user_configuration['default_shipping_country'];
            } else {
                $default_shipping_country = 'FR';
            }

            // if branding has changed, reload carriers, reinitialize selected carriers and reload categories
            if ($default_shipping_country != get_option('EMC_COUNTRY', 'FR')) {
                $return = envoimoinscher_model::load_carrier_list_api(false, true);
                update_option( 'EMC_SERVICES' , array ( 1 => array(), 2 => array() ) );
                if ($return != true) {
                    echo $return;
                }
                
                // reload categories
                $return = envoimoinscher_model::update_categories();
                if ($return != true) {
                    echo $return;
                }
            }
            update_option( 'EMC_COUNTRY', $default_shipping_country );
            
            update_option('EMC_USER_DETAILS_UPDATE', time());
        }
        
        // get partnership
        $partnership_last_update = get_option('EMC_PARTNERSHIP_UPDATE');
        if (false === $partnership_last_update || time() > ($partnership_last_update+(24 * 60 * 60))) {
            // if no API keys, stop there
            if (!get_option('EMC_KEY_PROD') || !get_option('EMC_KEY_TEST')) return;
            
            $user_class->setKey(get_option('EMC_KEY_PROD'));
            $user_class->getPartnership();
            $partnership = $user_class->partnership;
            update_option('EMC_PARTNERSHIP', $partnership);
            
            update_option('EMC_PARTNERSHIP_UPDATE', time());
        }
    }
}

endif;

add_action('woocommerce_loaded', function() {
    emc_admin_menus::instance();
});
