<?php
if ( ! defined( 'ABSPATH' ) ) exit;
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {//if woocommerce is activated
    /* manual synchro functions */
    add_action('wp_ajax_nopriv_synchro', 'meteosales_ms_synchro_function');
    add_action('wp_ajax_synchro', 'meteosales_ms_synchro_function');
    /* automatic synchro functions */
    add_action( 'save_post', 'meteosales_ms_synchro_product_automatic', 20, 1 );
    add_action( 'delete_post', 'meteosales_ms_synchro_delete_product_automatic' );
    
    add_action( 'edit_terms', 'meteosales_ms_synchro_category_automatic', 10, 2 );
    add_action( 'delete_product_cat', 'meteosales_ms_synchro_delete_category_automatic', 10, 2 ); 
    add_action( 'create_product_cat', 'meteosales_ms_synchro_create_category_automatic', 10, 2 );
    
    add_action( 'woocommerce_updated_product_stock', 'meteosales_ms_synchro_product_stocks' );//TODO: fare solo quando sono un automatico o sempre?
    /**
     * Manual synchro function
     *
     * @link       info@meteosales.com
     * @since      1.0.0
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */
    function meteosales_ms_synchro_function(){
        
        $sort = get_option("MeteoCommerceProductsSetting");
        
        if(!$sort){//if Get_Option does not exist
            exit();
        }
        
        $arr_sort = json_decode($sort, true);
        $token = $arr_sort["token"];
        $syncro_type = $arr_sort["syncro_type"];
        $n = $arr_sort["n"];
        
        if($syncro_type == "automatic" && $n == 0){
            $array = array("token"=>$token,"syncro_type"=>$syncro_type, "n"=>1);
            update_option( "MeteoCommerceProductsSetting", json_encode($array) );
        }
        
        $server = $_SERVER["SERVER_NAME"];
        $api_key = 'https://my.meteosales.com/api/synchro';
        
        $orderby = 'name';
        $order = 'asc';
        $cat_args = array(
            'orderby'    => $orderby,
            'order'      => $order,
        );
	
        $product_categories = get_terms( 'product_cat', $cat_args );
        $exit = false;
        $error_cat = array();
        $error_prod = array();
        $current_datetime = date("Y-m-d h:i:s");
        $count = 0;
        foreach($product_categories as $category){
            
            $cat_id =  $category->term_id;
            $cat_name = addslashes($category->name);
            
            $response = wp_remote_post($api_key, array(
                'body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"category", 'cat_id'=>$cat_id, 'cat_name'=>$cat_name, 'date'=> $current_datetime, "type"=>'1')
            ));
            $output     = wp_remote_retrieve_body( $response );
            $data = json_decode($output, true);
           
            if($data["errors"]){
                 echo "Synchronization Failed! \n";
                foreach($data["errors"] as $data_errors ){
                    echo $data_errors["title"] . "\n";
                }
                exit();
            }
            
            if(!$data["data"]){
                $error_cat[$cat_id] = $cat_name;
            }
            
            $args = array(
                'post_type'           => 'product',
                'post_status'         => 'publish',
                'ignore_sticky_posts' => 1,
                'tax_query'           => array(
                    array(
                        'taxonomy'    => 'product_cat',
                        'field'       => 'term_id',
                        'terms'       =>  $cat_id,
                        'operator'    => 'IN' 
                    )
                )
            );
            $products = new WP_Query($args);
            foreach($products->posts as $post){
                $p_id = $post->ID;
                $p_name = addslashes($post->post_title);
                $p_descr= addslashes($post->post_content);
                $p = wc_get_product( $p_id );
                $p_image = wp_get_attachment_url( $p->get_image_id() );
                $price = $p->get_price();
                $permalink = get_permalink( $p_id );
                 $qty=$p->get_stock_quantity();
                $s_status= $p->get_stock_status() == 'instock' ? 1 : 0;
                
                $response = wp_remote_post($api_key, array(
                    'body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"product",'p_id'=>$p_id, 'cat_id'=>$cat_id,'p_name'=>$p_name,'p_descr'=>$p_descr,'p_image'=>$p_image,'p_price'=>$price,'quantity'=>$qty,'stock_status'=>$s_status,'p_permalink' =>$permalink, 'date'=> $current_datetime)
                ));
                $output  = wp_remote_retrieve_body( $response );
                $datap = json_decode($output, true);
               
               if($datap["errors"]){
                 echo "Synchronization Failed! \n";
                foreach($datap["errors"] as $datap_errors ){
                    echo $datap_errors["title"] . "\n";
                }
                exit();
            }
               
                if(!$datap["data"]){
                    $error_prod[$p_id] = $p_name;
                }
                $count++;
                if($count > 60){
                    sleep(1);
                    $count =0;
                }
                
                if ( $p->is_type( 'variable' ) ) {
                    $pc=      $p->get_children();
                	foreach($pc as $prc){
                		$p_c = wc_get_product( $prc );
                		$pc_name = $p_c->get_name();
                		$pc_descr= addslashes($p_c->get_description());
                        $pc_image = wp_get_attachment_url( $p_c->get_image_id() );
                        $pc_price = $p_c->get_price();
                        $pc_permalink = get_permalink( $prc );
                        $pc_qty=$p_c->get_stock_quantity();
                        $pc_s_status= $p_c->get_stock_status() == 'instock' ? 1 : 0;
                	
                	    $response = wp_remote_post($api_key, array(
                            'body' => array( 
                                'token' => $token, 
                                'server_name' => $server , 
                                'synchro'=>"product",
                                'p_id'=>$prc, 
                                'cat_id'=>$cat_id,
                                'p_name'=>$pc_name,
                                'p_descr'=>$pc_descr,
                                'p_image'=>$pc_image,
                                'p_price'=>$pc_price,
                                'quantity'=>$pc_qty,
                                'stock_status'=>$pc_s_status,
                                'p_permalink' =>$pc_permalink, 
                                'date'=> $current_datetime,
                                'parent_id'=>$p_id
                            )
                        ));
                        
                        $output  = wp_remote_retrieve_body( $response );
                        $datap = json_decode($output, true);
                
                        if($datap["errors"]){
                            echo "Synchronization Failed! \n";
                            foreach($datap["errors"] as $datap_errors ){
                                echo $datap_errors["title"] . "\n";
                            }
                            exit();
                        }
               
                        if(!$datap["data"]){
                            $error_prod[$p_id] = $p_name;
                        }
                        $count++;
                        if($count > 60){
                            sleep(1);
                            $count =0;
                        }
                	}
                } 
            }
            
        }
        
        $response = wp_remote_post($api_key, array('body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"check", 'date'=> $current_datetime, )));
        
        $output     = wp_remote_retrieve_body( $response );
        $data = json_decode($output, true);
       
        //echo "Products Synchronization Successful! \n";
        if(count($error_cat) > 0){
            echo "Cannot synchonize the following Categories:\n";
            foreach($error_cat as $ct){
                echo "- ".$ct." \n";
            }
        }
        
        if(count($error_prod) > 0){
            echo "Cannot synchonize the following Products:\n";
            foreach($error_prod as $pr){
                echo "- ".$pr." \n";
            }
        }
        die();
    }
    
    /**
     * Automatic synchro function when update product
     *
     * @link       info@meteosales.com
     * @since      1.0.3
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */
    function meteosales_ms_synchro_product_automatic($post_id){
        $sort = get_option("MeteoCommerceProductsSetting");
        if(!$sort){//if Get_Option does not exist
           
        }
        else{
            $arr_sort = json_decode($sort, true);
            $token = $arr_sort["token"];
            $syncro_type = $arr_sort["syncro_type"];
            $n = $arr_sort["n"];
            
            if($syncro_type == "automatic"){
                $server = $_SERVER["SERVER_NAME"];
                $api_key = 'https://my.meteosales.com/api/synchro';
               
                if (!$product = wc_get_product( $post_id )) {
                    return;
                }
                $current_datetime = date("Y-m-d h:i:s");
                if ($product->get_status() != 'publish') {
                    $d=strtotime("00:00 January 1 2000");
                    $current_datetime = date("Y-m-d h:i:s", $d);
                }
          
                
                $p_name = addslashes($product->get_name());
                $p_descr= addslashes($product->get_description());
                $p_image = wp_get_attachment_url( $product->get_image_id() );
                $price = $product->get_price();
                $permalink = get_permalink( $post_id );  
                $cat_ids = $product->get_category_ids();
                 $qty=$product->get_stock_quantity();
                $s_status= $product->get_stock_status() == 'instock' ? 1 : 0;
                foreach ( (array) $cat_ids as $cat_id) {
                    $response = wp_remote_post($api_key, array(
                        'body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"product",'p_id'=>$post_id, 'cat_id'=>$cat_id,'p_name'=>$p_name,'p_descr'=>$p_descr,'p_image'=>$p_image,'p_price'=>$price,'quantity'=>$qty,'stock_status'=>$s_status,'p_permalink' =>$permalink, 'date'=> $current_datetime)
                    ));
                    $output  = wp_remote_retrieve_body( $response );
                    $datap = json_decode($output, true);
                    
                    if($datap["errors"]){
                       
                        foreach($datap["errors"] as $datap_errors ){
                           
                        }
                   }
                }
                
            }
        }
    }
    
    /**
     * Automatic synchro function when delete product
     *
     * @link       info@meteosales.com
     * @since      1.0.3
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */
    function meteosales_ms_synchro_delete_product_automatic($post_id){
        $sort = get_option("MeteoCommerceProductsSetting");
        if(!$sort){//if Get_Option does not exist
           
        }
        else{
            $arr_sort = json_decode($sort, true);
            $token = $arr_sort["token"];
            $syncro_type = $arr_sort["syncro_type"];
            $n = $arr_sort["n"];
            
            if($syncro_type == "automatic"){
                $server = $_SERVER["SERVER_NAME"];
                $api_key = 'https://my.meteosales.com/api/synchro';
               
                if (!$product = wc_get_product( $post_id )) {
                    return;
                }
                $d=strtotime("00:00 January 1 2000");
                $current_datetime = date("Y-m-d h:i:s", $d);
                
                $p_name = addslashes($product->get_name());
                $p_descr= addslashes($product->get_description());
                $p_image = wp_get_attachment_url( $product->get_image_id() );
                $price = $product->get_price();
                $permalink = get_permalink( $post_id );  
                $cat_ids = $product->get_category_ids();
                $qty=$product->get_stock_quantity();
               $s_status= $product->get_stock_status() == 'instock' ? 1 : 0;
                
                foreach ( (array) $cat_ids as $cat_id) {
                    $response = wp_remote_post($api_key, array(
                        'body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"product",'p_id'=>$post_id, 'cat_id'=>$cat_id,'p_name'=>$p_name,'p_descr'=>$p_descr,'p_image'=>$p_image,'p_price'=>$price,'quantity'=>$qty,'stock_status'=>$s_status,'p_permalink' =>$permalink, 'date'=> $current_datetime)
                    ));
                    $output  = wp_remote_retrieve_body( $response );
                    $datap = json_decode($output, true);
                    
                    if($datap["errors"]){
                       
                        foreach($datap["errors"] as $datap_errors ){
                           
                        }
                   }
                }
                
            }
        }
    }
    
    /**
     * Automatic synchro function when update category
     *
     * @link       info@meteosales.com
     * @since      1.0.3
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */
    function meteosales_ms_synchro_category_automatic($term_id, $taxonomy){
        $sort = get_option("MeteoCommerceProductsSetting");
        if(!$sort){//if Get_Option does not exist
           
        }
        else{
            $arr_sort = json_decode($sort, true);
            $token = $arr_sort["token"];
            $syncro_type = $arr_sort["syncro_type"];
            $n = $arr_sort["n"];
            
            if($syncro_type == "automatic"){
                $server = $_SERVER["SERVER_NAME"];
                $api_key = 'https://my.meteosales.com/api/synchro';
               
                if($taxonomy !='product_cat'){
                    return;
                }
                $term = get_term_by( 'id', $term_id, 'product_cat', 'ARRAY_A' );
    
                $cat_name = addslashes($term['name']);
                $current_datetime = date("Y-m-d h:i:s");
                
                $response = wp_remote_post($api_key, array(
                    'body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"category", 'cat_id'=>$term_id, 'cat_name'=>$cat_name, 'date'=> $current_datetime, "type"=>'1')
                ));
                $output     = wp_remote_retrieve_body( $response );
                $data = json_decode($output, true);
           
                if($data["errors"]){
                }
            
                if(!$data["data"]){
                }
            }
        }
    }
    
    /**
     * Automatic synchro function when delete category
     *
     * @link       info@meteosales.com
     * @since      1.0.3
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */
    function meteosales_ms_synchro_delete_category_automatic($term_id){
        $sort = get_option("MeteoCommerceProductsSetting");
        if(!$sort){//if Get_Option does not exist
           
        }
        else{
            $arr_sort = json_decode($sort, true);
            $token = $arr_sort["token"];
            $syncro_type = $arr_sort["syncro_type"];
            $n = $arr_sort["n"];
            
            if($syncro_type == "automatic"){
                $server = $_SERVER["SERVER_NAME"];
                $api_key = 'https://my.meteosales.com/api/synchro';
               
                $term = get_term_by( 'id', $term_id, 'product_cat', 'ARRAY_A' );
    
                $cat_name = addslashes($term['name']);
                $d=strtotime("00:00 January 1 2000");
                $current_datetime = date("Y-m-d h:i:s", $d);
                
                $response = wp_remote_post($api_key, array(
                    'body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"category", 'cat_id'=>$term_id, 'cat_name'=>$cat_name, 'date'=> $current_datetime, "type"=>'1')
                ));
                $output  = wp_remote_retrieve_body( $response );
                $data = json_decode($output, true);
                
                if($data["errors"]){
                }
            
                if(!$data["data"]){
                }
            }
        }
    }
    /**
     * Automatic synchro function when create category
     *
     * @link       info@meteosales.com
     * @since      1.0.3
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */
    function meteosales_ms_synchro_create_category_automatic( $term_id){
    	$sort = get_option("MeteoCommerceProductsSetting");
        if(!$sort){//if Get_Option does not exist
           
        }
        else{
            $arr_sort = json_decode($sort, true);
            $token = $arr_sort["token"];
            $syncro_type = $arr_sort["syncro_type"];
            $n = $arr_sort["n"];
            
            if($syncro_type == "automatic"){
                $server = $_SERVER["SERVER_NAME"];
                $api_key = 'https://my.meteosales.com/api/synchro';
               
                
                $term = get_term_by( 'id', $term_id, 'product_cat', 'ARRAY_A' );
    
                $cat_name = addslashes($term['name']);
                $current_datetime = date("Y-m-d h:i:s");
                
                $response = wp_remote_post($api_key, array(
                    'body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"category", 'cat_id'=>$term_id, 'cat_name'=>$cat_name, 'date'=> $current_datetime, "type"=>'1')
                ));
                $output     = wp_remote_retrieve_body( $response );
                $data = json_decode($output, true);
           
                if($data["errors"]){
                }
            
                if(!$data["data"]){
                }
            }
        }
    }  
    
    
    /**
     * Automatic synchro function when update stock status product
     *
     * @link       info@meteosales.com
     * @since      1.1.0
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */
    function meteosales_ms_synchro_product_stocks($post_id){
        $sort = get_option("MeteoCommerceProductsSetting");
        if(!$sort){//if Get_Option does not exist
           
        }
        else{
            $arr_sort = json_decode($sort, true);
            $token = $arr_sort["token"];
            $syncro_type = $arr_sort["syncro_type"];
            $n = $arr_sort["n"];
            
            //if($syncro_type == "automatic"){//this case synchro anytime
                $server = $_SERVER["SERVER_NAME"];
                $api_key = 'https://my.meteosales.com/api/synchro';
               
                if (!$product = wc_get_product( $post_id )) {
                    return;
                }
                $current_datetime = date("Y-m-d h:i:s");
                if ($product->get_status() != 'publish') {
                    $d=strtotime("00:00 January 1 2000");
                    $current_datetime = date("Y-m-d h:i:s", $d);
                }
          
                
                $p_name = addslashes($product->get_name());
                $p_descr= addslashes($product->get_description());
                $p_image = wp_get_attachment_url( $product->get_image_id() );
                $price = $product->get_price();
                $permalink = get_permalink( $post_id );  
                $cat_ids = $product->get_category_ids();
                $qty=$product->get_stock_quantity();
                $s_status= $product->get_stock_status() == 'instock' ? 1 : 0;
               
                foreach ( (array) $cat_ids as $cat_id) {
                    $response = wp_remote_post($api_key, array(
                        'body' => array( 'token' => $token, 'server_name' => $server , 'synchro'=>"product",'p_id'=>$post_id, 'cat_id'=>$cat_id,'p_name'=>$p_name,'p_descr'=>$p_descr,'p_image'=>$p_image,'p_price'=>$price,'quantity'=>$qty,'stock_status'=>$s_status,'p_permalink' =>$permalink, 'date'=> $current_datetime)
                    ));
                    $output  = wp_remote_retrieve_body( $response );
                    $datap = json_decode($output, true);
                    
                    if($datap["errors"]){
                       
                        foreach($datap["errors"] as $datap_errors ){
                           
                        }
                   }
                }
                
           // }
        }
    }
}