<?php
if ( ! defined( 'ABSPATH' ) ) exit;


if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {//if woocommerce is activated
    /**
    * Synchonize products and order with my.meteosales
    *
    * @link       info@meteosales.com
    * @since      1.0.2
    *
    * @package    Meteosales
    * @subpackage Meteosales/includes
    */
    add_action( 'woocommerce_thankyou', 'meteosales_get_products_from_order' );
    function meteosales_get_products_from_order($order_id) {
        
        $sort = get_option("MeteoCommerceProductsSetting");
        $arr_sort = json_decode($sort, true);
        $token = $arr_sort["token"];

        if($token != ""){
            $api_key = 'https://my.meteosales.com/api/sellers';
            $type = 3;
            $server = $_SERVER["SERVER_NAME"];
            $order = new WC_Order( $order_id );    
            $city = $order->get_shipping_city() == "" ? $order->get_billing_city() : $order->get_shipping_city();
            $state = $order->get_shipping_state() == "" ? $order->get_billing_state() : $order->get_shipping_state();
            $country = $order->get_shipping_country() == "" ? $order->get_billing_country() : $order->get_shipping_country();
            $state = WC()->countries->get_states( $country )[$state];
            $country = WC()->countries->countries[ $country ];
            
            $items = $order->get_items();

            $arrp = array();
            $index =0;
            foreach ( $items as $item_id => $item ) {
              
                $product = $item->get_product();
              
                $arrp[$index] = array(
                    "p_id" => $item->get_id(),
                    "p_name" => $item->get_name(),
                    "p_image" => wp_get_attachment_url($product->get_image_id()),
                    "p_q" =>$item->get_quantity(),
                    "p_price" =>$item->get_subtotal()
                );
                $index++;
            }

            $o_first_name = $order->get_shipping_first_name() != "" ? $order->get_shipping_first_name() : $order->get_billing_first_name();
            $o_last_name = $order->get_shipping_last_name() != "" ? $order->get_shipping_last_name() : $order->get_billing_last_name();
            $o_company = $order->get_shipping_company() != "" ? $order->get_shipping_company() : $order->get_billing_company();
            $o_address1 = $order->get_shipping_address_1() != "" ? $order->get_shipping_address_1() : $order->get_billing_address_1();
            $o_address2 = $order->get_shipping_address_2() != "" ? $order->get_shipping_address_2() : $order->get_billing_address_2();
            $o_postcode = $order->get_shipping_postcode() != "" ? $order->get_shipping_postcode() : $order->get_billing_postcode();
            $o_email = $order->get_billing_email();
            $o_phone = $order->get_billing_phone();
            $payment = $order->get_payment_method_title();
            $payment_id = $order->get_payment_method();
            
            $arr_coupon = array();
		    foreach( $order->get_coupon_codes() as $coupon_code ) {
    
                $coupon = new WC_Coupon($coupon_code);
                $discount_type = $coupon->get_discount_type(); // Get coupon discount type
                $coupon_amount = $coupon->get_amount(); // Get coupon amount
	            $arr_coupon[$coupon_code] = array("type" => $discount_type, "amount" => $coupon_amount);
            }
            
            $arr_det = array(
                "first_name" => $o_first_name,
                "last_name" => $o_last_name,
                "company" => $o_company,
                "address1" => $o_address1,
                "address2" => $o_address2,
                "postcode" => $o_postcode,
                "email" =>$o_email,
                "phone"=>$o_phone,
                );
            $det =json_encode($arr_det);     
            $params=json_encode($arrp);
            
            $is_guest = $order->get_user_id() == 0 ? 1 : 0;
            
            $date_created =date('Y-m-d H:i:s', strtotime($order->get_date_created()));
            $date_completed ="";
            $date_paid ="";
            
            $currency = get_woocommerce_currency_symbol();
            //Call API
            if($city != ""){
                $response = wp_remote_post($api_key, array(
                    'body' => array( 
                        'token' => $token, 
                        'server_name' => $server,
                        'order'=>'ok', 
                        'order_id'=>$order_id, 
                        'order_status'=>$order->get_status(),
                        'city'=>$city,
                        'state'=>$state,
                        'country'=>$country,
                        'det'=>$det,
                        'products'=>$params,
                        'subtotal' => $order->get_subtotal(),
                        'discount' => $order->get_total_discount(),
                        'shipping' => $order->get_shipping_total(),
                        'shipping_tax' => $order->get_shipping_tax(),
                        'taxes' => $order->get_taxes(),
                        'fees'=> $order->get_fees(),
                        'total' => $order->get_total(),
                        'currency'=>$currency,
                        't'=>$type,
                        'payment_id' => $payment_id,
                        'payment' => $payment,
                        'date_created' =>$date_created,
                        'date_completed' =>$date_completed,
                        'coupon' => json_encode($arr_coupon),
                        'date_paid' =>$date_paid,
                        'is_guest' => $is_guest,
                    )
                ));
            }
        } 
        
    }
    
   /**
     * Manual synchro function
     *
     * @link       info@meteosales.com
     * @since      1.0.6
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */
     
    add_action('wp_ajax_nopriv_synchroOrders', 'meteosales_ms_synchro_orders_function');
    add_action('wp_ajax_synchroOrders', 'meteosales_ms_synchro_orders_function');
    function meteosales_ms_synchro_orders_function(){
        
        $sort = get_option("MeteoCommerceProductsSetting");
        
        if(!$sort){//if Get_Option does not exist
            exit();
        }
        
        $arr_sort = json_decode($sort, true);
        
        $token = $arr_sort["token"];
        if($token != ""){
            $api_key = 'https://my.meteosales.com/api/sellers';
            $type = 3;
            $server = $_SERVER["SERVER_NAME"];
            
            /*Ordini vecchi */
            $query_args = array(
                'post_type'      => wc_get_order_types()[0],
                'post_status'    => array_keys( wc_get_order_statuses() ),
                'posts_per_page' => 999999999999,
            );

            $all_orders      = get_posts( $query_args );
            
            $err_orders = array();
            $count = 0;
            foreach ( $all_orders as $order ) {

                $order = wc_get_order( $order->ID );
	
    		    $city = $order->get_shipping_city() == "" ? $order->get_billing_city() : $order->get_shipping_city();
                $state = $order->get_shipping_state() == "" ? $order->get_billing_state() : $order->get_shipping_state();
                $country = $order->get_shipping_country() == "" ? $order->get_billing_country() : $order->get_shipping_country();
                $state = WC()->countries->get_states( $country )[$state];
                $country = WC()->countries->countries[ $country ];
                
                $items = $order->get_items();
                
                $arrp = array();
                $index =0;
                foreach ( $items as $item_id => $item ) {
                  
                    $product = $item->get_product();
                    
                    $img_p = "";
                    if(!$product){}
                    else{$img_p = wp_get_attachment_url($product->get_image_id());}
                    $arrp[$index] = array(
                        "p_id" => $item->get_product_id(),
                        "p_name" => $item->get_name(),
                        "p_image" => $img_p,
                        "p_q" =>$item->get_quantity(),
                        "p_price" =>$item->get_subtotal()
                    );
                    $index++;
                }
                
                $o_first_name = $order->get_shipping_first_name() != "" ? $order->get_shipping_first_name() : $order->get_billing_first_name();
                $o_last_name = $order->get_shipping_last_name() != "" ? $order->get_shipping_last_name() : $order->get_billing_last_name();
                $o_company = $order->get_shipping_company() != "" ? $order->get_shipping_company() : $order->get_billing_company();
                $o_address1 = $order->get_shipping_address_1() != "" ? $order->get_shipping_address_1() : $order->get_billing_address_1();
                $o_address2 = $order->get_shipping_address_2() != "" ? $order->get_shipping_address_2() : $order->get_billing_address_2();
                $o_postcode = $order->get_shipping_postcode() != "" ? $order->get_shipping_postcode() : $order->get_billing_postcode();
                $o_email = $order->get_billing_email();
                $o_phone = $order->get_billing_phone();
                $payment = $order->get_payment_method_title();
                $payment_id = $order->get_payment_method();
                
                $arr_det = array(
                    "first_name" => $o_first_name,
                    "last_name" => $o_last_name,
                    "company" => $o_company,
                    "address1" => $o_address1,
                    "address2" => $o_address2,
                    "postcode" => $o_postcode,
                    "email" =>$o_email,
                    "phone"=>$o_phone,
                    );
                $det =json_encode($arr_det);     
                $params=json_encode($arrp);
               
                $arr_coupon = array();
    		    foreach( $order->get_coupon_codes() as $coupon_code ) {
        
                    $coupon = new WC_Coupon($coupon_code);
                    $discount_type = $coupon->get_discount_type(); // Get coupon discount type
                    $coupon_amount = $coupon->get_amount(); // Get coupon amount
    	            $arr_coupon[$coupon_code] = array("type" => $discount_type, "amount" => $coupon_amount);
                }
               
                $date_created =date('Y-m-d H:i:s', strtotime($order->get_date_created()));
                $date_completed ="";
                 $date_paid ="";
                
                $order_status_id=0;
                if($order->get_status()=="cancelled" || $order->get_status()=="failed" || $order->get_status()=="refunded"){
                    $order_status_id = 1;
                }
            
                $currency = get_woocommerce_currency_symbol();
                $is_guest = $order->get_user_id() == 0 ? 1 : 0;
                //Call API
           
                $response = wp_remote_post($api_key, array(
                    'body' => array( 
                        'token' => $token, 
                        'server_name' => $server,
                        'order'=>'synchro', 
                        'order_id'=> $order->ID, 
                        'order_status_id' =>$order_status_id,
                        'order_status' =>$order->get_status(),
                        'city'=>$city,
                        'state'=>$state,
                        'country'=>$country,
                        'det'=>$det,
                        'products'=>$params,
                        'subtotal' => $order->get_subtotal(),
                        'discount' => $order->get_total_discount(),
                        'shipping' => $order->get_shipping_total(),
                        'shipping_tax' => $order->get_shipping_tax(),
                        'taxes' => $order->get_taxes(),
                        'fees'=> $order->get_fees(),
                        'total' => $order->get_total(),
                        'currency'=>$currency,
                        't'=>$type,
                        'payment' => $payment,
                        'payment_id' => $payment_id,
                        'coupon' => json_encode($arr_coupon),
                        'date_created' =>$date_created,
                        'date_completed' =>$date_completed,
                        'date_paid' =>$date_paid,
                        'is_guest' => $is_guest,
                    )
                ));
                
                $data = json_decode($output, true);
                $output     = wp_remote_retrieve_body( $response );
                
                if($data["errors"]){
                     echo "Orders Synchronization Failed! \n";
                    foreach($data["errors"] as $data_errors ){
                        echo $data_errors["title"] . "\n";
                    }
                    exit();
                }
                
                
                $count++;
                if($count > 100){
                    sleep(1);
                    $count = 0;
                }
            }
            
            //echo "Orders Synchronization Successful! \n";
            if(count($err_orders) > 0){
                echo "Cannot synchonize the following Orders:\n";
                foreach($err_orders as $eo){
                    echo "- ".$eo." \n";
                }
            }
        } 
        die();
    }
    
    /**
     * Authomatic synchro function when status order changed
     *
     * @link       info@meteosales.com
     * @since      1.0.14
     *
     * @package    Meteosales
     * @subpackage Meteosales/includes
     */ 
    add_action('woocommerce_order_status_changed', 'meteosales_ms_synchro_order_status_changed', 10, 3);
    function meteosales_ms_synchro_order_status_changed($order_id, $old_status, $new_status){

        $order = wc_get_order($order_id);
    
        $sort = get_option("MeteoCommerceProductsSetting");
            
        if(!$sort){//if Get_Option does not exist
            exit();
        }
        $arr_sort = json_decode($sort, true);
            
        $token = $arr_sort["token"];
        if($token != ""){
            $api_key = 'https://my.meteosales.com/api/sellers';
            $type = 3;
            $server = $_SERVER["SERVER_NAME"];
            
            $order = wc_get_order( $order->ID );
            
    	    $city = $order->get_shipping_city() == "" ? $order->get_billing_city() : $order->get_shipping_city();
            $state = $order->get_shipping_state() == "" ? $order->get_billing_state() : $order->get_shipping_state();
            $country = $order->get_shipping_country() == "" ? $order->get_billing_country() : $order->get_shipping_country();
            $state = WC()->countries->get_states( $country )[$state];
            $country = WC()->countries->countries[ $country ];
                    
            $items = $order->get_items();
                    
            $arrp = array();
            $index =0;
            foreach ( $items as $item_id => $item ) {
              
                $product = $item->get_product();
                
                $img_p = "";
                if(!$product){}
                else{$img_p = wp_get_attachment_url($product->get_image_id());}
                $arrp[$index] = array(
                    "p_id" => $item->get_product_id(),
                    "p_name" => $item->get_name(),
                    "p_image" => $img_p,
                    "p_q" =>$item->get_quantity(),
                    "p_price" =>$item->get_subtotal()
                );
                $index++;
            }
            
            $o_first_name = $order->get_shipping_first_name() != "" ? $order->get_shipping_first_name() : $order->get_billing_first_name();
            $o_last_name = $order->get_shipping_last_name() != "" ? $order->get_shipping_last_name() : $order->get_billing_last_name();
            $o_company = $order->get_shipping_company() != "" ? $order->get_shipping_company() : $order->get_billing_company();
            $o_address1 = $order->get_shipping_address_1() != "" ? $order->get_shipping_address_1() : $order->get_billing_address_1();
            $o_address2 = $order->get_shipping_address_2() != "" ? $order->get_shipping_address_2() : $order->get_billing_address_2();
            $o_postcode = $order->get_shipping_postcode() != "" ? $order->get_shipping_postcode() : $order->get_billing_postcode();
            $o_email = $order->get_billing_email();
            $o_phone = $order->get_billing_phone();
            $payment_id = $order->get_payment_method();
            $payment = $order->get_payment_method_title();
                    
            $arr_det = array(
                "first_name" => $o_first_name,
                "last_name" => $o_last_name,
                "company" => $o_company,
                "address1" => $o_address1,
                "address2" => $o_address2,
                "postcode" => $o_postcode,
                "email" =>$o_email,
                "phone"=>$o_phone,
                );
            $det =json_encode($arr_det);     
            $params=json_encode($arrp);
            
            $arr_coupon = array();
		    foreach( $order->get_coupon_codes() as $coupon_code ) {
    
                $coupon = new WC_Coupon($coupon_code);
                $discount_type = $coupon->get_discount_type(); // Get coupon discount type
                $coupon_amount = $coupon->get_amount(); // Get coupon amount
	            $arr_coupon[$coupon_code] = array("type" => $discount_type, "amount" => $coupon_amount);
            }
                   
            $date_created =date('Y-m-d H:i:s', strtotime($order->get_date_created()));
            $date_completed ="";
            $date_paid ="";
                    
            $order_status_id = 0;
            if($new_status=="cancelled" || $new_status=="failed" || $new_status=="refunded"){
                $order_status_id = 1;
            }
            
            $is_guest = $order->get_user_id() == 0 ? 1 : 0;
            $currency = get_woocommerce_currency_symbol();
            //Call API
       
            $response = wp_remote_post($api_key, array(
                'body' => array( 
                    'token' => $token, 
                    'server_name' => $server,
                    'order'=>'synchro', 
                    'order_id'=> $order->ID, 
                    'order_status_id' =>$order_status_id,
                    'order_status' =>$new_status,
                    'city'=>$city,
                    'state'=>$state,
                    'country'=>$country,
                    'det'=>$det,
                    'products'=>$params,
                    'subtotal' => $order->get_subtotal(),
                    'discount' => $order->get_total_discount(),
                    'shipping' => $order->get_shipping_total(),
                    'shipping_tax' => $order->get_shipping_tax(),
                    'taxes' => $order->get_taxes(),
                    'fees'=> $order->get_fees(),
                    'total' => $order->get_total(),
                    'currency'=>$currency,
                    't'=>$type,
                    'payment_id' => $payment_id,
                    'coupon' => json_encode($arr_coupon),
                    'payment' => $payment,
                    'date_created' =>$date_created,
                    'date_completed' =>$date_completed,
                    'date_paid' =>$date_paid,
                    'is_guest' => $is_guest,
                )
            ));
            
            $data = json_decode($output, true);
            $output     = wp_remote_retrieve_body( $response );
           
        } 
    }
}