<?php


namespace YouDroop;

/**
 * Check if WooCommerce is active
 */
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
	
	if ( ! class_exists( 'YouDroop' ) ) {
	
    class YouDroop {

      const YOUDROOP_URL = "https://www.youdroop.com/api/v1/export/list";
      private static $initiated = false;

      
      public function __construct() {
        // called only after woocommerce has finished loading
	      add_action( 'woocommerce_init', array( &$this, 'woocommerce_loaded' ) );
	
	      // called after all plugins have loaded
	      add_action( 'plugins_loaded', array( &$this, 'plugins_loaded' ) );
      }

      /**
	     * Take care of anything that needs woocommerce to be loaded.  
	     * For instance, if you need access to the $woocommerce global
	     */
	    public function woocommerce_loaded() {
		    // ...
	    }
	
	    /**
	     * Take care of anything that needs all plugins to be loaded
	     */
	    public function plugins_loaded() {
    		if ( class_exists( 'WC_Integration' ) ) {
          // Include our integration class.
          include_once YOUDROOP__PLUGIN_DIR . 'class-wc-integration-youdroop-integration.php';
          // Register the integration.
          $plugin_dir = basename(dirname(__FILE__)) . "/languages/";
          load_plugin_textdomain( 'woocommerce-integration-youdroop', false, $plugin_dir );
          add_filter( 'woocommerce_integrations', array( $this, 'add_integration' ) );
        }
	    }
	    
	    public function add_integration( $integrations ) {
		    $integrations[] = 'WC_Integration_YouDroop_Integration';
		    return $integrations;
	    }
	    
	    public function plugin_activation() {
	      if (! wp_next_scheduled ( 'youdroop_daily_event' )) {
          wp_schedule_event(time(), 'daily', 'youdroop_daily_event');
        }
	    }
	    
	    function plugin_deactivation() {
	      wp_clear_scheduled_hook('youdroop_daily_event');
      }
      
      function integration_menu_page() {
        add_submenu_page( null, __("Integrazione YouDroop", 'woocommerce-integration-youdroop'), __("Integrazione YouDroop", 'woocommerce-integration-youdroop'), "manage_options", "youdroop-integration", array( '\YouDroop\YouDroop', 'syncronize_page' ) );
      }

      function youdroop_footer() {
        $conf = WC()->integrations->get_integrations()['integration-youdroop'];
        var_dump($conf->enabled_powered_by);
        if($conf->enabled_powered_by == "yes")
          echo '<p style="text-align:center;"><a href="https://www.youdroop.com/" title="YouDroop Platform"><span>Powered by:</span><br/> <img src="' . YOUDROOP__PLUGIN_STATIC_DIR . 'logo.png" style="max-height: 40px;" /></a></p>';
      }

      function syncronize_page() {
        global $wpdb;
        
        // General check for user permissions.
        if (!current_user_can('manage_options'))  {
          wp_die( __('You do not have sufficient permissions to access this page.', 'woocommerce-integration-youdroop')    );
        }

        // Start building the page

        echo '<div class="wrap">';

        echo '<h2>' .  __("Integrazione YouDroop", 'woocommerce-integration-youdroop') . '</h2>';
        
        require_once(plugin_dir_path( __FILE__ ) . "includes/YouDroopProduct.php");
        
        $conf = WC()->integrations->get_integrations()['integration-youdroop'];
        $content = wp_remote_get($conf->YOUDROOP_URL . "?clientID=" . $conf->api_key);
        $list = json_decode(wp_remote_retrieve_body($content), true);
        $user_id = get_current_user_id();
        
        $lang = explode("_", get_locale())[0];
        
        $inserted = array();
        
        foreach($list as $key => $product) {
          $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT posts.ID
                        FROM $wpdb->posts AS posts
                        LEFT JOIN $wpdb->postmeta AS postmeta ON ( posts.ID = postmeta.post_id )
                        WHERE posts.post_type IN ( 'product', 'product_variation' )
                        AND postmeta.meta_key = '_sku' AND postmeta.meta_value = '%s'
                        AND posts.post_status = 'publish'
                        LIMIT 1", $product['product']['YDPC'] ) );
          $p = new \YouDroop\includes\YouDroopProduct($product, $user_id, $lang, $wpdb);   
          if($product_id) {
            $p->update_product($product_id);  
          }
          else {
            $p->insert_product();
          }
          
          $inserted[] = $product['product']['YDPC'];
        }
        
        
        $all_products = $wpdb->get_col( "SELECT postmeta.meta_value
                        FROM $wpdb->postmeta AS postmeta, $wpdb->posts as posts
                        WHERE postmeta.post_id = posts.ID AND posts.post_status = 'publish'
                        AND postmeta.meta_key = '_sku' AND postmeta.post_id IN ( SELECT postmeta_1.post_id FROM $wpdb->postmeta AS postmeta_1
                        WHERE postmeta_1.meta_key = '_youdroop_product' AND postmeta_1.meta_value = 'yes')" );
        
        
        foreach(array_diff($all_products, $inserted) as $key => $ydpc) {
          $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT posts.ID
                        FROM $wpdb->posts AS posts
                        LEFT JOIN $wpdb->postmeta AS postmeta ON ( posts.ID = postmeta.post_id )
                        WHERE posts.post_type IN ( 'product', 'product_variation' )
                        AND postmeta.meta_key = '_sku' AND postmeta.meta_value = '%s'
                        AND posts.post_status = 'publish'
                        LIMIT 1", $ydpc ) );
          wp_trash_post($product_id);
        }
        
        $order_id_sql = "SELECT order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta woim
          LEFT JOIN {$wpdb->prefix}woocommerce_order_items oi
          ON woim.order_item_id = oi.order_item_id
          WHERE meta_key = '_product_id' AND meta_value IN
          (SELECT DISTINCT post_id FROM {$wpdb->prefix}postmeta wpm WHERE wpm.meta_key = '_youdroop_product' AND wpm.meta_value='yes')
          GROUP BY order_id;";
        $order_ids = $wpdb->get_col( $order_id_sql );
        
        $json_orders = array();
        
        foreach($order_ids as $key => $order_id) {
          $order = wc_get_order($order_id); 
          
          $json_order = array();
          
          $order_data = array();
          $order_data['order_id'] = $order->id;
          $order_data['order_title'] = $order->post->post_title;
          $order_data['order_date'] = $order->order_date;
          $order_data['order_currency'] = $order->order_currency;
          $order_data['order_discount'] = $order->order_discount;
          $order_data['order_key'] = $order->order_key;
          $order_data['order_shipping'] = $order->order_shipping;
          $order_data['order_tax'] = $order->order_tax;
          $order_data['order_total'] = $order->order_total;
          $order_data['payment_method_title'] = $order->payment_method_title;
          
          $json_order['order_data'] = $order_data;
          
          $billing_data = array( 'first_name' => $order->billing_first_name,
                                 'last_name' => $order->billing_last_name,
                                 'company' => $order->billing_company,
                                 'address1' => $order->billing_address_1,
                                 'address2' => $order->billing_address_2,
                                 'city' => $order->billing_city,
                                 'postcode' => $order->billing_postcode,
                                 'state' => $order->billing_state,
                                 'country' => $order->billing_country,
                                 'email' => $order->billing_email,
                                 'phone' => $order->billing_phone);
          
          $json_order['billing'] = $billing_data;
          
          $shipping_data = array( 'first_name' => $order->shipping_first_name,
                                 'last_name' => $order->shipping_last_name,
                                 'company' => $order->shipping_company,
                                 'address1' => $order->shipping_address_1,
                                 'address2' => $order->shipping_address_2,
                                 'city' => $order->shipping_city,
                                 'postcode' => $order->shipping_postcode,
                                 'state' => $order->shipping_state,
                                 'country' => $order->shipping_country);
          
          $json_order['shipping'] = $shipping_data;
          
          $order_item = $order->get_items();
          $products = array();
          foreach( $order_item as $product ) {
              $product_variation_id = $product['variation_id'];
              if($product_variation_id == 0)
                $p = wc_get_product($product['product_id']);
              else
                $p = wc_get_product($product['variation_id']);
              $products[] = array('sku' => $p->get_sku(), 'price' => $product['line_total'], 'tax' => $product['line_tax'], 'qty' => $product['qty']); 
          }
          
          $json_order['products'] = $products;
          
          $json_orders[] = $json_order;
        }
        
        $hash = hash('sha256', json_encode($json_orders) . $conf->api_secret);
        
        $to_send = array("data" => $json_orders, "clientID" => $conf->api_key, "checksum" => $hash);
        
        $payload = json_encode( $to_send );
        $post_url = $conf->YOUDROOP_URL_SEND . "?clientID=" . $conf->api_key ;
        $post_args = array(
                        'body' => $to_send,
                        'timeout' => '5',
                        'redirection' => '5',
                        'httpversion' => '1.0',
                        'blocking' => true,
                        'headers' => array('Content-Type:application/json'),
                        'cookies' => array()
                    );
        $response = wp_remote_post($post_url, $post_args);
        
        echo "</div>";
      }

	    public function daily_cron() {
	      global $wpdb;
	      require_once(plugin_dir_path( __FILE__ ) . "includes/YouDroopProduct.php");

        $conf = WC()->integrations->get_integrations()['integration-youdroop'];
        if(!$conf->enabled == "yes") 
          return; 
        $content = wp_remote_get($conf->YOUDROOP_URL . "?clientID=" . $conf->api_key);
        $list = json_decode(wp_remote_retrieve_body($content), true);
        $user_id = "1";
        
        $lang = explode("_", get_locale())[0];
        
        foreach($list as $key => $product) {
          $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT posts.ID
                        FROM $wpdb->posts AS posts
                        LEFT JOIN $wpdb->postmeta AS postmeta ON ( posts.ID = postmeta.post_id )
                        WHERE posts.post_type IN ( 'product', 'product_variation' )
                        AND postmeta.meta_key = '_sku' AND postmeta.meta_value = '%s'
                        AND posts.post_status = 'publish'
                        LIMIT 1", $product['product']['YDPC'] ) );
          $p = new \YouDroop\includes\YouDroopProduct($product, $user_id, $lang, $wpdb);   
          if($product_id) {
            $p->update_product($product_id);  
          }
          else {
            $p->insert_product();
          }
          
          
        }

        $order_id_sql = "SELECT order_id FROM {$wpdb->prefix}woocommerce_order_itemmeta woim
          LEFT JOIN {$wpdb->prefix}woocommerce_order_items oi
          ON woim.order_item_id = oi.order_item_id
          WHERE meta_key = '_product_id' AND meta_value IN
          (SELECT DISTINCT post_id FROM {$wpdb->prefix}postmeta wpm WHERE wpm.meta_key = '_youdroop_product' AND wpm.meta_value='yes')
          GROUP BY order_id;";
        $order_ids = $wpdb->get_col( $order_id_sql );
        
        $json_orders = array();
        
        foreach($order_ids as $order_id) {
          $order = wc_get_order($order_id); 
          
          $json_order = array();
          
          $order_data = array();
          $order_data['order_id'] = $order->id;
          $order_data['order_title'] = $order->post->post_title;
          $order_data['order_date'] = $order->order_date;
          $order_data['order_currency'] = $order->order_currency;
          $order_data['order_discount'] = $order->order_discount;
          $order_data['order_key'] = $order->order_key;
          $order_data['order_shipping'] = $order->order_shipping;
          $order_data['order_tax'] = $order->order_tax;
          $order_data['order_total'] = $order->order_total;
          $order_data['payment_method_title'] = $order->payment_method_title;
          
          $json_order['order_data'] = $order_data;
          
          $billing_data = array( 'first_name' => $order->billing_first_name,
                                 'last_name' => $order->billing_last_name,
                                 'company' => $order->billing_company,
                                 'address1' => $order->billing_address_1,
                                 'address2' => $order->billing_address_2,
                                 'city' => $order->billing_city,
                                 'postcode' => $order->billing_postcode,
                                 'state' => $order->billing_state,
                                 'country' => $order->billing_country,
                                 'email' => $order->billing_email,
                                 'phone' => $order->billing_phone);
          
          $json_order['billing'] = $billing_data;
          
          $shipping_data = array( 'first_name' => $order->shipping_first_name,
                                 'last_name' => $order->shipping_last_name,
                                 'company' => $order->shipping_company,
                                 'address1' => $order->shipping_address_1,
                                 'address2' => $order->shipping_address_2,
                                 'city' => $order->shipping_city,
                                 'postcode' => $order->shipping_postcode,
                                 'state' => $order->shipping_state,
                                 'country' => $order->shipping_country);
          
          $json_order['shipping'] = $shipping_data;
          
          $order_item = $order->get_items();
          $products = array();
          foreach( $order_item as $product ) {
              $product_variation_id = $product['variation_id'];
              if($product_variation_id == 0)
                $p = wc_get_product($product['product_id']);
              else
                $p = wc_get_product($product['variation_id']);
              $products[] = array('sku' => $p->get_sku(), 'price' => $product['line_total'], 'tax' => $product['line_tax'], 'qty' => $product['qty']); 
          }
          
          $json_order['products'] = $products;
          
          $json_orders[] = $json_order;
        }
        
        $hash = hash('sha256', json_encode($json_orders) . $conf->api_secret);
        
        $to_send = array("data" => $json_orders, "clientID" => $conf->api_key, "checksum" => $hash);
        $payload = json_encode( $to_send );
        $post_url = $conf->YOUDROOP_URL_SEND . "?clientID=" . $conf->api_key ;
        $post_args = array(
                        'body' => $to_send,
                        'timeout' => '5',
                        'redirection' => '5',
                        'httpversion' => '1.0',
                        'blocking' => true,
                        'headers' => array('Content-Type:application/json'),
                        'cookies' => array()
                    );
        $response = wp_remote_post($post_url, $post_args);
	    }
    }
    // finally instantiate our plugin class and add it to the set of globals
	  $GLOBALS['youdroop'] = new YouDroop();
   }
}
