<?php
/*
  Plugin Name: NBT Currency Switcher
  Plugin URI: http://abc.com/woocommerce-price-matrix
  Description: Change the default behavior of WooCommerce Cart page, making AJAX requests when quantity field changes
  Version: 1.1.0
  Author: Katori
  Author URI: https://cmsmart.net/wordpress-plugins/nbt-woocommerce-price-matrix
 */
define('NBT_MCS_PATH', plugin_dir_path( __FILE__ ));
define('NBT_MCS_URL', plugin_dir_url( __FILE__ ));

class NBT_Solutions_Currency_Switcher {
    static $plugin_id = 'currency-switcher';
    /**
     * Variable to hold the initialization state.
     *
     * @var  boolean
     */
    protected static $initialized = false;

    public static $types = array();
    
    /**
     * Initialize functions.
     *
     * @return  void
     */
    public static function initialize() {


        // Do nothing if pluggable functions already initialized.
        if ( self::$initialized ) {
            return;
        }

        include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
        if ( ! is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
            add_action( 'admin_notices', 'install_woocommerce_admin_notice' );
        }else{
            // add_filter( 'cron_schedules', array( __CLASS__, 'cron_add_minutes') );
            add_action ('update_rates_currency', array( __CLASS__, 'run_cron'));
            add_action('wp', array( __CLASS__, 'add_cron'));


            if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
                require_once 'inc/ajax.php';
                NBT_MCS_Ajax::initialize();
            }
            if(is_admin()){
                require_once 'inc/admin.php';
            }

            require_once 'inc/frontend.php';

            if( ! defined('PREFIX_NBT_SOL') && !class_exists('NBT_Plugins') ){
                require_once 'inc/plugins.php';
            }

            if( ! defined('PREFIX_NBT_SOL') ){
                require_once 'inc/widgets.php';
                 add_action( 'widgets_init', array(__CLASS__, 'register_widgets') );
            }



            


        }
        // State that initialization completed.
        self::$initialized = true;
    }

    public static function symbol_position(){
        return array(
            'left' => 'left',
            'right' => 'right',
            'left_space' => 'left space',
            'right_space' => 'right space'
        );
    }

    public static function show_image($value){
        $image = $value ? wp_get_attachment_image_src( $value ) : '';
        $image = $image ? $image[0] : WC()->plugin_url() . '/assets/images/placeholder.png';
        ?>
        <div class="nbtmcs-wrap-image">
            <div class="nbtmcs-term-image-thumbnail" style="float:left;margin-right:10px;">
                <img src="<?php echo esc_url( $image ) ?>" width="60px" height="60px" />
            </div>
            <div class="right-button-term" style="line-height:60px;">
                <input type="hidden" class="nbtmcs-term-image" name="image" value="<?php echo esc_attr( $value ) ?>" />
                <button type="button" class="nbtmcs-upload-image-button button"><?php esc_html_e( 'Upload/Add image', 'wcvs' ); ?></button>
                <button type="button" class="nbtmcs-remove-image-button button <?php echo $value ? '' : 'hidden' ?>"><?php esc_html_e( 'Remove image', 'wcvs' ); ?></button>
            </div>
        </div>
        <?php
    }

    public static function get_woocommerce_price_format($currency_pos) {
        $format = '%1$s%2$s';
        switch ( $currency_pos ) {
            case 'left' :
                $format = '%1$s%2$s';
            break;
            case 'right' :
                $format = '%2$s%1$s';
            break;
            case 'left_space' :
                $format = '%1$s&nbsp;%2$s';
            break;
            case 'right_space' :
                $format = '%2$s&nbsp;%1$s';
            break;
        }

        return apply_filters( 'cs_price_format', $format, $currency_pos );
    }

    public static function show_position($key, $position = false, $symbol){
        if($position){
            switch ($position) {
                case 'left':
                    $k = '<span class="symbol">'.$symbol.'</span>'.$key;
                    break;
                case 'right':
                    $k = $key.'<span class="symbol">'.$symbol.'</span>';
                    break; 
                case 'left_space':
                    $k = '<span class="symbol">'.$symbol.'</span> '.$key;
                    break;
                case 'right_space':
                    $k = $key.' <span class="symbol">'.$symbol.'</span>';
                    break; 
                default:
                    # code...
                    break;
            }


            if($key == strip_tags(html_entity_decode($symbol))){
                return $key;
            }else{
                return $k; 
            }
            
        }else{
            return $key;
        }
    }

    public static function cron_add_minutes( $schedules ) {
        if(!isset($schedules['minutely'])){
            $schedules['minutely'] = array(
                'interval' => 60,
                'display' => __( 'Minutely' )
            );
        }
        return $schedules;
    }


    public static function get_rate($from, $to){
        
        $url = "https://finance.google.com/finance/converter?a=1&from=".$from."&to=".$to;


        $ch = curl_init();
        $timeout = 0;

        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $rawdata = curl_exec($ch);

        curl_close($ch);

        if(preg_match("/<span class=bld>(.*)<\/span>/", $rawdata,  $converted)){
            $converted = preg_replace("/[^0-9.]/", "", $converted);
            return round($converted[0], 3);
        }

    }

    public static function run_cron() {
        $settings_mcs = get_option('settings_mcs' );
        if($settings_mcs){
            $from = get_woocommerce_currency();
            foreach ($settings_mcs as $currency => $value) {

                $settings_mcs[$currency]['rates'] = self::get_rate($from, $currency);
            }
        }
        update_option('settings_mcs', $settings_mcs);
        
    }

    public static function add_cron() {
        wp_clear_scheduled_hook( 'update_rates_currency' );  
        if( !wp_next_scheduled( 'update_rates_currency' ) ) {
           wp_schedule_event( time(), 'hourly', 'update_rates_currency' );  
        }
    }

    public static function register_widgets(){
        register_widget( 'NBT_Currency_Switcher_Widget' );
        
    }

}


function cron_update_rate_deactivate() { 
    $timestamp = wp_next_scheduled ('update_rates_currency');
    wp_unschedule_event ($timestamp, 'update_rates_currency');
} 
register_deactivation_hook (__FILE__, 'cron_update_rate_deactivate');


if( ! function_exists( 'install_woocommerce_admin_notice' ) ) {
    function install_woocommerce_admin_notice() {
        ?>
        <div class="error">
            <p><?php _e( 'WooCommerce plugin is not activated. Please install and activate it to use for plugin <strong>NBT Order Upload</strong>.', 'yith-woocommerce-wishlist' ); ?></p>
        </div>
    <?php
    }
}

if( ! defined('PREFIX_NBT_SOL')){
    NBT_Solutions_Currency_Switcher::initialize();
}