<?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.
          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, "Youdroop Integration", "Youdroop Integration", "manage_options", "youdroop-integration", array( '\YouDroop\YouDroop', 'syncronize_page' ) );
      }

      function youdroop_footer() {
        echo '<p style="text-align:center;"><span>Powered by:</span><br/> <img src="' . YOUDROOP__PLUGIN_STATIC_DIR . 'logo.png" style="max-height: 40px;" /></p>';
      }

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

        // Start building the page

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

        echo '<h2>Youdroop Integration</h2>';
        echo '<pre>' . YOUDROOP__PLUGIN_STATIC_DIR . '</pre>';

        $conf = WC()->integrations->get_integrations()['integration-youdroop'];
        $content = file_get_contents($conf->YOUDROOP_URL . "?clientID=" . $conf->api_key);
        $list = json_decode($content, true);
        $user_id = get_current_user_id();
        
        $lang = explode("_", get_locale())[0];
        
        
        foreach($list as $key => $product) {
          foreach($product as $p_key => $p) {
            if (strpos($p_key, 'YD') === 0) {
              if(array_key_exists("variations", $p)) {
                echo "<p>Inserting variable product: " . $p_key . "</p>";
                if(array_key_exists($lang, $p['languages'])) {
                  $p_name = $p['languages'][$lang]["name"];
                  $p_desc = $p['languages'][$lang]["description"];
                } else {
                  $p_name = array_values($p['languages'])[0]["name"];
                  $p_desc = array_values($p['languages'])[0]["description"];
                }
                
                $post_id = wp_insert_post( array(
                    'post_author' => $user_id,
                    'post_title' => $p_name,
                    'post_content' => $p_desc,
                    'post_status' => 'publish',
                    'post_type' => "product",
                ) );
                wp_set_object_terms( $post_id, 'variable', 'product_type' );
                update_post_meta( $post_id, '_visibility', 'visible' );
                update_post_meta( $post_id, '_stock_status', 'instock');
                update_post_meta( $post_id, 'total_sales', '0' );
                update_post_meta( $post_id, '_downloadable', 'no' );
                update_post_meta( $post_id, '_virtual', 'yes' );
                update_post_meta( $post_id, '_regular_price', '' );
                update_post_meta( $post_id, '_sale_price', '' );
                update_post_meta( $post_id, '_purchase_note', '' );
                update_post_meta( $post_id, '_featured', 'no' );
                update_post_meta( $post_id, '_weight', '' );
                update_post_meta( $post_id, '_length', '' );
                update_post_meta( $post_id, '_width', '' );
                update_post_meta( $post_id, '_height', '' );
                update_post_meta( $post_id, '_sku', $p_key );
                update_post_meta( $post_id, '_product_attributes', array() ); 
                update_post_meta( $post_id, '_sale_price_dates_from', '' );
                update_post_meta( $post_id, '_sale_price_dates_to', '' );
                update_post_meta( $post_id, '_sold_individually', '' );
                update_post_meta( $post_id, '_manage_stock', 'no' );
                update_post_meta( $post_id, '_backorders', 'no' );
                update_post_meta( $post_id, '_stock', '' );
                
                $variation_array = array();
                
                foreach($p['variations'] as $index => $variation) {
                  foreach($variation as $m => $n) {
                    if($m != "totalPricePerVariation") {
                      if( !array_key_exists($m, $variation_array) ) {
                        $variation_array[$m] = array($n);
                      } else {
                        array_push($variation_array[$m], $n);
                      }
                    }
                  }
                }
                foreach($variation_array as $m => $n) {
                  $q = array_unique($n);
                  wp_set_object_terms($post_id, $q, 'pa_' . $m, true);
                }
                
                $product_attributes_data = array(); // Setup array to hold our product attributes data

                foreach ($variation_array as $m => $n) // Loop round each attribute
                {
                  $product_attributes_data['pa_'.$m] = array(
                    'name'         => 'pa_'.$m,
                    'value'        => '',
                    'is_visible'   => '1',
                    'is_variation' => '1',
                    'is_taxonomy'  => '1'
                  );
                }
                update_post_meta($post_id, '_product_attributes', $product_attributes_data);
                
                foreach ($p['variations'] as $index => $variation)
                {
                  $variation_post = array( // Setup the post data for the variation
                    'post_title'  => 'Variation #'.$index.' of '.count($p['variations']).' for product#'. $post_id,
                    'post_name'   => 'product-'.$post_id.'-variation-'.$index,
                    'post_status' => 'publish',
                    'post_parent' => $post_id,
                    'post_type'   => 'product_variation',
                    'guid'        => home_url() . '/?product_variation=product-' . $post_id . '-variation-' . $index
                  );

                  $variation_post_id = wp_insert_post($variation_post); // Insert the variation
                  
                  foreach ($variation as $attribute => $value) // Loop through the variations attributes
                  {  
                    if($attribute == "totalPricePerVariation")
                      continue;
                    $attribute_term = get_term_by('name', $value, 'pa_'.$attribute); 
                    update_post_meta($variation_post_id, 'attribute_pa_'.$attribute, $attribute_term->slug);
                  }

                  update_post_meta($variation_post_id, '_price', $variation['totalPricePerVariation']);
                  update_post_meta($variation_post_id, '_regular_price', $variation['totalPricePerVariation']);
                }
                //Image
                require_once(ABSPATH . 'wp-admin/includes/file.php');
                require_once(ABSPATH . 'wp-admin/includes/media.php');
                $list_id = "";
                foreach($p['images'] as $a => $l) {
                  $thumb_url = $l;

                  // Download file to temp location
                  $tmp = download_url( $thumb_url );

                  // Set variables for storage
                  // fix file name for query strings
                  preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $thumb_url, $matches);
                  $file_array['name'] = basename($matches[0]);
                  $file_array['tmp_name'] = $tmp;

                  // If error storing temporarily, unlink
                  if ( is_wp_error( $tmp ) ) {
                    @unlink($file_array['tmp_name']);
                    $file_array['tmp_name'] = '';
                  }else{

                  }

                  //use media_handle_sideload to upload img:
                  $thumbid = media_handle_sideload( $file_array, $new_post_id, 'gallery desc' );
                  // If error storing permanently, unlink
                  if ( is_wp_error($thumbid) ) {
                    @unlink($file_array['tmp_name']);
                  }else{

                  }
                  if($a == 0) {
                    set_post_thumbnail($post_id, $thumbid);
                    $list_id .= $thumbid;
                  }
                  else
                    $list_id .= "," . $thumbid;
                }
                update_post_meta($post_id,'_product_image_gallery',$list_id);
                
                
              } else {
                echo "<p>Inserting product: " . $p_key . "</p>";
                
                if(array_key_exists($lang, $p['languages'])) {
                  $p_name = $p['languages'][$lang]["name"];
                  $p_desc = $p['languages'][$lang]["description"];
                } else {
                  $p_name = $p['languages'][0]["name"];
                  $p_desc = $p['languages'][0]["description"];
                }
                
                $post_id = wp_insert_post( array(
                    'post_author' => $user_id,
                    'post_title' => $p_name,
                    'post_content' => $p_desc,
                    'post_status' => 'publish',
                    'post_type' => "product",
                ) );
                wp_set_object_terms( $post_id, 'simple', 'product_type' );
                update_post_meta( $post_id, '_visibility', 'visible' );
                update_post_meta( $post_id, '_stock_status', 'instock');
                update_post_meta( $post_id, 'total_sales', '0' );
                update_post_meta( $post_id, '_downloadable', 'no' );
                update_post_meta( $post_id, '_virtual', 'yes' );
                update_post_meta( $post_id, '_regular_price', '' );
                update_post_meta( $post_id, '_sale_price', '' );
                update_post_meta( $post_id, '_purchase_note', '' );
                update_post_meta( $post_id, '_featured', 'no' );
                update_post_meta( $post_id, '_weight', '' );
                update_post_meta( $post_id, '_length', '' );
                update_post_meta( $post_id, '_width', '' );
                update_post_meta( $post_id, '_height', '' );
                update_post_meta( $post_id, '_sku', $p_key );
                update_post_meta( $post_id, '_product_attributes', array() ); 
                update_post_meta( $post_id, '_sale_price_dates_from', '' );
                update_post_meta( $post_id, '_sale_price_dates_to', '' );
                update_post_meta( $post_id, '_price', $product['totalPrice'] );
                update_post_meta( $post_id, '_sold_individually', '' );
                update_post_meta( $post_id, '_manage_stock', 'no' );
                update_post_meta( $post_id, '_backorders', 'no' );
                update_post_meta( $post_id, '_stock', '' );
                
                //Image
                require_once(ABSPATH . 'wp-admin/includes/file.php');
                require_once(ABSPATH . 'wp-admin/includes/media.php');
                $list_id = "";
                foreach($p['images'] as $a => $l) {
                  $thumb_url = $l;

                  // Download file to temp location
                  $tmp = download_url( $thumb_url );

                  // Set variables for storage
                  // fix file name for query strings
                  preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $thumb_url, $matches);
                  $file_array['name'] = basename($matches[0]);
                  $file_array['tmp_name'] = $tmp;

                  // If error storing temporarily, unlink
                  if ( is_wp_error( $tmp ) ) {
                    @unlink($file_array['tmp_name']);
                    $file_array['tmp_name'] = '';
                  }else{

                  }

                  //use media_handle_sideload to upload img:
                  $thumbid = media_handle_sideload( $file_array, $new_post_id, 'gallery desc' );
                  // If error storing permanently, unlink
                  if ( is_wp_error($thumbid) ) {
                    @unlink($file_array['tmp_name']);
                  }else{

                  }
                  if($a == 0) {
                    set_post_thumbnail($post_id, $thumbid);
                    $list_id .= $thumbid;
                  }
                  else
                    $list_id .= "," . $thumbid;
                }
                update_post_meta($post_id,'_product_image_gallery',$list_id);
              }
              break;
            }
          }
        }
        
        /*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['productData']['ydpc'] ) );
          
          if($product_id) {
            echo "<p>Updating product: " . $product['productData']['ydpc'] . "</p>";
            wp_update_post( array(
                'ID' => $product_id,
                'post_title' => $product['productData']['name'],
                'post_content' => $product['productData']['description'],
                'post_status' => 'publish',
                'post_type' => "product",
            ) );
            update_post_meta( $product_id, '_visibility', 'visible' );
            update_post_meta( $product_id, '_stock_status', 'instock');
            update_post_meta( $product_id, 'total_sales', '0' );
            update_post_meta( $product_id, '_downloadable', 'no' );
            update_post_meta( $product_id, '_virtual', 'yes' );
            update_post_meta( $product_id, '_regular_price', '' );
            update_post_meta( $product_id, '_sale_price', '' );
            update_post_meta( $product_id, '_purchase_note', '' );
            update_post_meta( $product_id, '_featured', 'no' );
            update_post_meta( $product_id, '_weight', '' );
            update_post_meta( $product_id, '_length', '' );
            update_post_meta( $product_id, '_width', '' );
            update_post_meta( $product_id, '_height', '' );
            update_post_meta( $product_id, '_sku', $product['productData']['ydpc'] );
            update_post_meta( $product_id, '_product_attributes', array() ); 
            update_post_meta( $product_id, '_sale_price_dates_from', '' );
            update_post_meta( $product_id, '_sale_price_dates_to', '' );
            update_post_meta( $product_id, '_price', $product['totalPrice'] );
            update_post_meta( $product_id, '_sold_individually', '' );
            update_post_meta( $product_id, '_manage_stock', 'no' );
            update_post_meta( $product_id, '_backorders', 'no' );
            update_post_meta( $product_id, '_stock', '' );
            
          } else {
            echo "<p>Inserting product: " . $product['productData']['ydpc'] . "</p>";
            $post_id = wp_insert_post( array(
                'post_author' => $user_id,
                'post_title' => $product['productData']['name'],
                'post_content' => $product['productData']['description'],
                'post_status' => 'publish',
                'post_type' => "product",
            ) );
            wp_set_object_terms( $post_id, 'simple', 'product_type' );
            update_post_meta( $post_id, '_visibility', 'visible' );
            update_post_meta( $post_id, '_stock_status', 'instock');
            update_post_meta( $post_id, 'total_sales', '0' );
            update_post_meta( $post_id, '_downloadable', 'no' );
            update_post_meta( $post_id, '_virtual', 'yes' );
            update_post_meta( $post_id, '_regular_price', '' );
            update_post_meta( $post_id, '_sale_price', '' );
            update_post_meta( $post_id, '_purchase_note', '' );
            update_post_meta( $post_id, '_featured', 'no' );
            update_post_meta( $post_id, '_weight', '' );
            update_post_meta( $post_id, '_length', '' );
            update_post_meta( $post_id, '_width', '' );
            update_post_meta( $post_id, '_height', '' );
            update_post_meta( $post_id, '_sku', $product['productData']['ydpc'] );
            update_post_meta( $post_id, '_product_attributes', array() ); 
            update_post_meta( $post_id, '_sale_price_dates_from', '' );
            update_post_meta( $post_id, '_sale_price_dates_to', '' );
            update_post_meta( $post_id, '_price', $product['totalPrice'] );
            update_post_meta( $post_id, '_sold_individually', '' );
            update_post_meta( $post_id, '_manage_stock', 'no' );
            update_post_meta( $post_id, '_backorders', 'no' );
            update_post_meta( $post_id, '_stock', '' );
            
            //Image
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            require_once(ABSPATH . 'wp-admin/includes/media.php');
            $thumb_url = $product['productData']['image'];

            // Download file to temp location
            $tmp = download_url( $thumb_url );

            // Set variables for storage
            // fix file name for query strings
            preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $thumb_url, $matches);
            $file_array['name'] = basename($matches[0]);
            $file_array['tmp_name'] = $tmp;

            // If error storing temporarily, unlink
            if ( is_wp_error( $tmp ) ) {
              @unlink($file_array['tmp_name']);
              $file_array['tmp_name'] = '';
            }else{

            }

            //use media_handle_sideload to upload img:
            $thumbid = media_handle_sideload( $file_array, $new_post_id, 'gallery desc' );
            // If error storing permanently, unlink
            if ( is_wp_error($thumbid) ) {
              @unlink($file_array['tmp_name']);
            }else{

            }

            set_post_thumbnail($post_id, $thumbid);
          }
        }*/
        
        echo "</div>";
      }

	    public function daily_cron() {
	      $content = file_get_contents(YOUDROOP_URL);
	      $json_content = json_decode($content, true);
	      $user_id = get_current_user_id();
	      error_log($this->api_key);
	      
	      return;
	      foreach($json_content as $key => $product) {
          $post_id = wp_insert_post( array(
              'post_author' => $user_id,
              'post_title' => $item['Name'],
              'post_content' => $item['Description'],
              'post_status' => 'publish',
              'post_type' => "product",
          ) );
          wp_set_object_terms( $post_id, 'simple', 'product_type' );
          update_post_meta( $post_id, '_visibility', 'visible' );
          update_post_meta( $post_id, '_stock_status', 'instock');
          update_post_meta( $post_id, 'total_sales', '0' );
          update_post_meta( $post_id, '_downloadable', 'no' );
          update_post_meta( $post_id, '_virtual', 'yes' );
          update_post_meta( $post_id, '_regular_price', '' );
          update_post_meta( $post_id, '_sale_price', '' );
          update_post_meta( $post_id, '_purchase_note', '' );
          update_post_meta( $post_id, '_featured', 'no' );
          update_post_meta( $post_id, '_weight', '' );
          update_post_meta( $post_id, '_length', '' );
          update_post_meta( $post_id, '_width', '' );
          update_post_meta( $post_id, '_height', '' );
          update_post_meta( $post_id, '_sku', $item['SKU'] );
          update_post_meta( $post_id, '_product_attributes', array() );
          update_post_meta( $post_id, '_sale_price_dates_from', '' );
          update_post_meta( $post_id, '_sale_price_dates_to', '' );
          update_post_meta( $post_id, '_price', '' );
          update_post_meta( $post_id, '_sold_individually', '' );
          update_post_meta( $post_id, '_manage_stock', 'no' );
          update_post_meta( $post_id, '_backorders', 'no' );
          update_post_meta( $post_id, '_stock', '' );
	      }
	    }
    }
    // finally instantiate our plugin class and add it to the set of globals
	  $GLOBALS['youdroop'] = new YouDroop();
   }
}
