<?php
use WC_Product;
$path = $_SERVER['DOCUMENT_ROOT'];
 
include_once $path . '/wp-config.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';

global $wpdb;
global $wp_rewrite; 

$table = $wpdb->prefix."edara_config";
$wpdb->query('Drop TABLE '.$table.'');
$wpdb->query('Drop TABLE '.$wpdb->prefix.'edara_products');
$wpdb->query('Drop TABLE '.$wpdb->prefix.'edara_customers');
$wpdb->query('Drop TABLE '.$wpdb->prefix.'edara_orders');

$edara_accsess_token = $_POST["edara_accsess_token"];//"5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
$edara_domain = $_POST['edara_domain'];
$edara_email = $_POST['edara_email'];
$products_selection = $_POST['products_selection'];
$customers_selection = $_POST['customers_selection'];
$orders_selection = $_POST['orders_selection'];
$from_date = $_POST['from_date'];
$warehouses_selection = $_POST['warehouses_selection'];
$sale_price = $_POST['sale_price'];

// set the default character set and collation for the table
$charset_collate = $wpdb->get_charset_collate();
// Check that the table does not already exist before continuing
$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_config (
id bigint(50) NOT NULL AUTO_INCREMENT,
edara_email varchar(255),
edara_domain varchar(255),
products_selection varchar(255),
customers_selection varchar(255),
orders_selection varchar(255),
from_date varchar(255),
warehouses_selection varchar(255),
sale_price varchar(255),
edara_accsess_token varchar(255),
PRIMARY KEY (id)
) $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
$is_error = empty( $wpdb->last_error );

$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_customers (
id bigint(50) NOT NULL AUTO_INCREMENT,
wp_customer varchar(255),
edara_customer varchar(255),
status varchar(255),
PRIMARY KEY (id)
) $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
if ($is_error) {
     // WHERE edara_email = ".$edara_email." AND edara_domain = ".$edara_domain."
    $rows = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."edara_config");

    if (count($rows) == 0) {
        if ($orders_selection == "all_orders") {
            $result = $wpdb->insert($wpdb->prefix.'edara_config', array(
              'edara_email' => $edara_email,
              'edara_domain' => $edara_domain,
              'products_selection' => $products_selection,
              'customers_selection' => $customers_selection,
              'orders_selection' => $orders_selection,
              'from_date' => $from_date,
              'warehouses_selection' => $warehouses_selection,
              'sale_price' => $sale_price,
              'edara_accsess_token' => $edara_accsess_token
            ));
            $is_error = empty( $wpdb->last_error );
            if (!$is_error) {
                var_dump($wpdb->last_error);die();
            }
        }else{
            $result = $wpdb->insert($wpdb->prefix.'edara_config', array(
              'edara_email' => $edara_email,
              'edara_domain' => $edara_domain,
              'products_selection' => $products_selection,
              'customers_selection' => $customers_selection,
              'orders_selection' => $orders_selection,
              'warehouses_selection' => $warehouses_selection,
              'sale_price' => $sale_price,
              'edara_accsess_token' => $edara_accsess_token
            ));
            $is_error = empty( $wpdb->last_error );
            if (!$is_error) {
                var_dump($wpdb->last_error);die();
            }
        }
        if ($products_selection == "wp_to_edara") {
            $products = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts WHERE post_type = 'product'");

            $url = "https://api.edara.io/v2.0/stockItems";
            foreach ($products as $product) {
                $postmeta = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."postmeta WHERE post_id = ".$product->ID." AND meta_key = '_regular_price'");
                $price = count($postmeta) > 0 ? (double)$postmeta[0]->meta_value : 0;
                //--------------- check if exsist link it --------------
                $skuProduct = get_post_meta( $product->ID, '_sku', true );
                $ckeckUrl = "https://api.edara.io/v2.0/stockItems/Find?sku=".$skuProduct;
                $curl = curl_init($ckeckUrl);
                curl_setopt($curl, CURLOPT_URL, $ckeckUrl);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

                $headers = array(
                   "Accept: application/json",
                   "Authorization:".$edara_accsess_token."",
                );
                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
                //for debug only!
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

                $resp = curl_exec($curl);
                curl_close($curl);
                $result = json_decode($resp, true);
                
                if ($result != null) {
                    if ($result['status_code'] == 200) {
                        $charset_collate = $wpdb->get_charset_collate();
                        // Check that the table does not already exist before continuing
                        $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_products (
                        id bigint(50) NOT NULL AUTO_INCREMENT,
                        wp_product varchar(255),
                        edara_product varchar(255),
                        status varchar(255),
                        PRIMARY KEY (id)
                        ) $charset_collate;";
                        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                        dbDelta( $sql );
                        $is_error = empty( $wpdb->last_error );
                        if ($is_error) {
                          $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                            'wp_product' => $product->ID,
                            'edara_product' => $result['result']['id'],
                            'status' => "linked"
                          ));
                        }
                    } else{
                        if ($sale_price == "sale_price") {
                            $data = array('description' => $product->post_title, 'sku' =>$skuProduct,'price' => $price);
                        }else if ($sale_price == "dealer_price") {
                            $data = array('description' => $product->post_title, 'sku' =>$skuProduct,'dealer_price' => $price);
                        }else{
                            $data = array('description' => $product->post_title, 'sku' =>$skuProduct,'supper_dealer_price' => $price);
                        }
                        $options = array(
                            'http' => array(
                                'header'  => "Authorization:".$edara_accsess_token."",
                                'method'  => 'POST',
                                'content' => http_build_query($data),
                            )
                        );
                        $context  = stream_context_create($options);
                        $result = file_get_contents($url, false, $context);
                        $result = json_decode($result, true);
                        if ($result['status_code'] == 200) {
                            $charset_collate = $wpdb->get_charset_collate();
                            // Check that the table does not already exist before continuing
                            $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_products (
                            id bigint(50) NOT NULL AUTO_INCREMENT,
                            wp_product varchar(255),
                            edara_product varchar(255),
                            status varchar(255),
                            PRIMARY KEY (id)
                            ) $charset_collate;";
                            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                            dbDelta( $sql );
                            $is_error = empty( $wpdb->last_error );
                            if ($is_error) {
                              $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                'wp_product' => $product->ID,
                                'edara_product' => $result['result'],
                                'status' => "linked"
                              ));
                            }
                        }else{
                            $charset_collate = $wpdb->get_charset_collate();
                            // Check that the table does not already exist before continuing
                            $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_products (
                            id bigint(50) NOT NULL AUTO_INCREMENT,
                            wp_product varchar(255),
                            edara_product varchar(255),
                            status varchar(255),
                            PRIMARY KEY (id)
                            ) $charset_collate;";
                            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                            dbDelta( $sql );
                            $is_error = empty( $wpdb->last_error );
                            if ($is_error) {
                              $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_products WHERE wp_product = ".$product->ID."");
                                if ($dataSelected != NULL)  {
                                    $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                                    'wp_product' => $product->ID,
                                    'edara_product' => "0",
                                    'status' => $result['error_message']
                                  ), array('wp_product' => $product->ID));
                                }else{
                                    $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                        'wp_product' => $product->ID,
                                        'edara_product' => 0,
                                        'status' => $result['error_message']
                                      ));
                                }
                            }
                        }
                    }
                }
                //-----------------------------------------------------
            }
        }else if ($products_selection == "edara_to_wp") {

            //Write the rule
            $wp_rewrite->set_permalink_structure('/%post_id%/'); 

            //Set the option
            update_option( "rewrite_rules", FALSE ); 

            //Flush the rules and tell it to write htaccess
            $wp_rewrite->flush_rules( true );

            $url = "https://api.edara.io/v2.0/stockItems?limit=10000000&offset=0";

            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

            $headers = array(
               "Accept: application/json",
               "Authorization:".$edara_accsess_token."",
            );
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            //for debug only!
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

            $resp = curl_exec($curl);
            curl_close($curl);
            $result = json_decode($resp, true);
            
            if ($result != null) {
                if ($result['status_code'] == 200) {
                    foreach ($result['result'] as $product) {
                        //check if this product exsists or not
                        $checkIfExists = $wpdb->get_var("SELECT wp_product FROM ".$wpdb->prefix."edara_products WHERE edara_product = '".$product['id']."'");
                        if ($checkIfExists == NULL) {

                            $date = date('Y-m-d H:i:s');

                            $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM ".$wpdb->prefix."postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $product['sku'] ) );

                            if ($product_id) {
                                $charset_collate = $wpdb->get_charset_collate();
                                // Check that the table does not already exist before continuing
                                $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_products (
                                id bigint(50) NOT NULL AUTO_INCREMENT,
                                wp_product varchar(255),
                                edara_product varchar(255),
                                status varchar(255),
                                PRIMARY KEY (id)
                                ) $charset_collate;";
                                require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                                dbDelta( $sql );
                                $is_error = empty( $wpdb->last_error );
                                if ($is_error) {
                                  $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                    'wp_product' => $product_id,
                                    'edara_product' => $product['id'],
                                    'status' => "linked"
                                  ));
                                }
                            }else{

                                if ($sale_price == "sale_price") {
                                    $price = $product['price'];
                                }else if ($sale_price == "dealer_price") {
                                    $price = $product['dealer_price'];
                                }else{
                                    $price = $product['supper_dealer_price'];
                                }
                                $productw = new WC_Product();
                                $productw->set_name($product['description']);
                                // $product->set_title($product['description']);
                                $productw->set_status( 'publish' ); 
                                $productw->set_catalog_visibility( 'visible' );
                                $productw->set_price( $price );
                                $productw->set_regular_price( $price );
                                $productw->set_sold_individually( true );
                                $productw->set_downloadable( true );
                                $productw->set_virtual( true );      
                                $productw->save();
                                $savedProduct = $wpdb->update($wpdb->prefix.'posts', array(
                                  'menu_order' => $product['code']
                                ), array('ID'=>$productw->id));
                                $is_error = empty( $wpdb->last_error );
                                if (!$is_error) {
                                    var_dump($wpdb->last_error);die();
                                }
                                // $my_post = array(
                                //   'to_ping'    => $product['code'],
                                //   'ID'  => $productw->id
                                // );
                                 
                                // // Insert the post into the database
                                // wp_insert_post( $my_post );
                                // $savedProduct = $wpdb->insert($wpdb->prefix.'posts', array(
                                //   'post_title' => $product['description'], 
                                //   'post_name' => $product['description'],
                                //   'post_content' => $product['description'],
                                //   'post_excerpt' => $product['description'], 
                                //   'to_ping' => $product['code'],
                                //   'pinged' => $product['description'],
                                //   'post_content_filtered' => $product['description'], 
                                //   'post_name' => $product['description'],
                                //   'post_content' => $product['description'],
                                //   'post_type' => 'product',

                                //   'post_date' => $date,
                                //   'post_date_gmt' => $date,
                                //   'post_modified' => $date,
                                //   'post_modified_gmt' => $date
                                // ));
                                // $lastid = $wpdb->insert_id;

                                // if ($lastid) {
                                $lastid = $productw->id;
                                if ($lastid) {
                                   

                                    // if ($sale_price == "sale_price") {
                                    //     $price = $product['price'];
                                    // }else if ($sale_price == "dealer_price") {
                                    //     $price = $product['dealer_price'];
                                    // }else{
                                    //     $price = $product['supper_dealer_price'];
                                    // }
                                    // $savedLocup = $wpdb->insert($wpdb->prefix.'wc_product_meta_lookup', array(
                                    //     'product_id' => $lastid,
                                    //     'sku' => $product['sku'],
                                    //     'downloadable' => 1,
                                    //     'min_price' => $price,
                                    //     'max_price' => $price,
                                    //     'onsale' => 1,
                                    //     'stock_quantity' => 1,
                                    //     'stock_status' => 'instock',
                                    //     'rating_count' => 0,
                                    //     'average_rating' => 0.00,
                                    //     'total_sales' => 0,
                                    //     'tax_status' => 'taxable',
                                    //     'tax_class' => '' 
                                    // ));
                                    // $savedMeta = $wpdb->insert($wpdb->prefix.'postmeta', array(
                                    //   'post_id' => $lastid, 
                                    //   'meta_key' => '_regular_price',
                                    //   'meta_value' => $price
                                    // ));

                                    // $savedMeta2 = $wpdb->insert($wpdb->prefix.'postmeta', array(
                                    //   'post_id' => $lastid, 
                                    //   'meta_key' => '_sale_price',
                                    //   'meta_value' => $price
                                    // ));

                                    $charset_collate = $wpdb->get_charset_collate();
                                    // Check that the table does not already exist before continuing
                                    $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_products (
                                    id bigint(50) NOT NULL AUTO_INCREMENT,
                                    wp_product varchar(255),
                                    edara_product varchar(255),
                                    status varchar(255),
                                    PRIMARY KEY (id)
                                    ) $charset_collate;";
                                    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                                    dbDelta( $sql );
                                    $is_error = empty( $wpdb->last_error );
                                    if ($is_error) {
                                        update_post_meta( $lastid, '_sku', $product['sku'] );
                                      $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                        'wp_product' => $lastid,
                                        'edara_product' => $product['id'],
                                        'status' => "linked"
                                      ));
                                    }
                                }
                            }
                        }else{
                            $date = date('Y-m-d H:i:s');
                            $savedProduct = $wpdb->update($wpdb->prefix.'posts', array(
                                  'post_title' => $product['description'], 
                                  'post_name' => $product['description'],
                                  'post_content' => $product['description'],
                                  'post_excerpt' => $product['description'], 
                                  'menu_order' => $product['code'],
                                  'pinged' => $product['description'],
                                  'post_content_filtered' => $product['description'], 
                                  'post_name' => $product['description'],
                                  'post_content' => $product['description'],
                                  'post_type' => 'product',

                                  'post_date' => $date,
                                  'post_date_gmt' => $date,
                                  'post_modified' => $date,
                                  'post_modified_gmt' => $date
                                ), array('ID'=>$checkIfExists));
                            if ($savedProduct) {
                                if ($sale_price == "sale_price") {
                                    $price = $product['price'];
                                }else if ($sale_price == "dealer_price") {
                                    $price = $product['dealer_price'];
                                }else{
                                    $price = $product['supper_dealer_price'];
                                }

                                $savedLocup = $wpdb->update($wpdb->prefix.'wc_product_meta_lookup', array(
                                        // 'product_id' => $checkIfExists,
                                        'sku' => $product['sku'],
                                        'downloadable' => 1,
                                        'min_price' => $price,
                                        'max_price' => $price,
                                        'onsale' => 1,
                                        'stock_quantity' => 1,
                                        'stock_status' => 'instock',
                                        'rating_count' => 0,
                                        'average_rating' => 0.00,
                                        'total_sales' => 0,
                                        'tax_status' => 'taxable',
                                        'tax_class' => '' 
                                    ),array('product_id'=>$checkIfExists));
                                $savedMeta = $wpdb->update($wpdb->prefix.'postmeta', array(
                                      'meta_value' => $price
                                ), array('post_id'=>$checkIfExists,'meta_key'=>'_regular_price'));
                                if (!$savedMeta) {
                                    $savedMeta = $wpdb->insert($wpdb->prefix.'postmeta', array(
                                      'post_id' => $checkIfExists, 
                                      'meta_key' => '_regular_price',
                                      'meta_value' => $price + 1
                                    ));
                                }
                                // $savedMeta2 = $wpdb->update($wpdb->prefix.'postmeta', array(
                                //   'meta_value' => $price
                                // ), array('post_id'=>$checkIfExists,'meta_key'=>'_sale_price'));
                                // if (!$savedMeta2) {
                                //     $savedMeta2 = $wpdb->insert($wpdb->prefix.'postmeta', array(
                                //       'post_id' => $checkIfExists, 
                                //       'meta_key' => '_sale_price',
                                //       'meta_value' => $price
                                //     ));
                                // }

                                // Check that the table does not already exist before continuing
                                $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_products (
                                id bigint(50) NOT NULL AUTO_INCREMENT,
                                wp_product varchar(255),
                                edara_product varchar(255),
                                status varchar(255),
                                PRIMARY KEY (id)
                                ) $charset_collate;";
                                require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                                dbDelta( $sql );
                                $is_error = empty( $wpdb->last_error );
                                if ($is_error) {
                                    update_post_meta( $checkIfExists, '_sku', $product['sku'] );
                                  $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                    'wp_product' => $checkIfExists,
                                    'edara_product' => $product['id'],
                                    'status' => "linked"
                                  ));
                                }
                                
                            }
                        }
                    }
                }
                
            }else{
            }
        }
        if ($customers_selection == "all_customers") {
            $customers = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."users WHERE ID <> 1");
            $url = "https://api.edara.io/v2.0/customers";
            foreach ($customers as $customer) {

                //--------------- check if exsist link it --------------
                $ckeckUrl = "https://api.edara.io/v2.0/customers/FindByEmail/".$customer->user_email;
                $curl = curl_init($ckeckUrl);
                curl_setopt($curl, CURLOPT_URL, $ckeckUrl);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

                $headers = array(
                   "Accept: application/json",
                   "Authorization:".$edara_accsess_token."",
                );
                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
                //for debug only!
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

                $resp = curl_exec($curl);
                curl_close($curl);
                $result = json_decode($resp, true);
                
                if ($result != null) {
                    if ($result['status_code'] == 200) {
                        $charset_collate = $wpdb->get_charset_collate();
                        $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_customers (
                        id bigint(50) NOT NULL AUTO_INCREMENT,
                        wp_customer varchar(255),
                        edara_customer varchar(255),
                        status varchar(255),
                        PRIMARY KEY (id)
                        ) $charset_collate;";
                        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                        dbDelta( $sql );
                        $is_error = empty( $wpdb->last_error );
                        if ($is_error) {
                            $result = $wpdb->insert($wpdb->prefix.'edara_customers', array(
                                'wp_customer' => $customer->ID,
                                'edara_customer' => $result['result']['id'],
                                'status' => "linked"
                            ));
                        }else{
                            var_dump($wpdb->last_error);die();
                        }
                    } else{
                        $data = array('name' => $customer->user_login, 'email' =>$customer->user_email,'payment_type' => 'Credit');

                        $options = array(
                            'http' => array(
                                'header'  => "Authorization:".$edara_accsess_token."",
                                'method'  => 'POST',
                                'content' => http_build_query($data),
                            )
                        );
                        $context  = stream_context_create($options);
                        $result = file_get_contents($url, false, $context);
                        $result = json_decode($result, true);
                        if ($result['status_code'] == 200) {
                            $charset_collate = $wpdb->get_charset_collate();
                            $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_customers (
                            id bigint(50) NOT NULL AUTO_INCREMENT,
                            wp_customer varchar(255),
                            edara_customer varchar(255),
                            status varchar(255),
                            PRIMARY KEY (id)
                            ) $charset_collate;";
                            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                            dbDelta( $sql );
                            $is_error = empty( $wpdb->last_error );
                            if ($is_error) {
                                $result = $wpdb->insert($wpdb->prefix.'edara_customers', array(
                                    'wp_customer' => $customer->ID,
                                    'edara_customer' => $result['result'],
                                    'status' => "linked"
                                ));
                            }else{
                                var_dump($wpdb->last_error);die();
                            }
                        }else{
                            $charset_collate = $wpdb->get_charset_collate();
                            // Check that the table does not already exist before continuing
                            $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_customers (
                            id bigint(50) NOT NULL AUTO_INCREMENT,
                            wp_customer varchar(255),
                            edara_customer varchar(255),
                            status varchar(255),
                            PRIMARY KEY (id)
                            ) $charset_collate;";
                            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                            dbDelta( $sql );
                            $is_error = empty( $wpdb->last_error );
                            if ($is_error) {
                                $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$customer->ID."");
                                if ($dataSelected != NULL)  {
                                    $row = $wpdb->update($wpdb->prefix.'edara_customers', array(
                                    'wp_customer' => $customer->ID,
                                    'edara_customer' => "0",
                                    'status' => $result['error_message']
                                  ), array('wp_customer' => $customer->ID));
                                }else{
                                $result = $wpdb->insert($wpdb->prefix.'edara_customers', array(
                                    'wp_customer' => $customer->ID,
                                    'edara_customer' => 0,
                                    'status' => $result['error_message']
                                  ));
                                }
                            }
                        }
                    }
                }
                //----------------------------------------------
            }
        }
        if ($orders_selection == "all_orders") {
            $url = "https://api.edara.io/v2.0/salesOrders";
            $date = strtotime($from_date);
            $from_date = date('Y-m-d 00:00:00', $date);
            $orders = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."posts WHERE post_type = 'shop_order' AND post_status <> 'trash' AND post_status <> 'auto-draft' AND post_date >= '".$from_date."'");
            
            foreach ($orders as $order) {
                $orderMeta = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."postmeta WHERE meta_key = '_customer_user' AND post_id =".$order->ID);

                $orderItemIDs = $wpdb->get_results("SELECT order_item_id FROM ".$wpdb->prefix."woocommerce_order_items WHERE order_item_type = 'line_item' AND order_id = '".$order->ID."'");

                $customerMetaID = $wpdb->get_var("SELECT meta_value FROM ".$wpdb->prefix."postmeta WHERE meta_key = '_customer_user' AND post_id = '".$order->ID."'");

                // $customerID = $customerMetaID;
                $customerID = $wpdb->get_var("SELECT edara_customer FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$customerMetaID);

                $total = 0;
                $saleOrderLine = []; 
                foreach ($orderItemIDs as $orderItemID) {
                    $sub_total = $wpdb->get_var("SELECT meta_value FROM ".$wpdb->prefix."woocommerce_order_itemmeta WHERE meta_key = '_line_total' AND order_item_id = '".$orderItemID->order_item_id."'");

                    $quantity = $wpdb->get_var("SELECT meta_value FROM ".$wpdb->prefix."woocommerce_order_itemmeta WHERE meta_key = '_qty' AND order_item_id = '".$orderItemID->order_item_id."'");

                    $productMetaID = $wpdb->get_var("SELECT meta_value FROM ".$wpdb->prefix."woocommerce_order_itemmeta WHERE meta_key = '_product_id' AND order_item_id = '".$orderItemID->order_item_id."'");

                    $productID = $wpdb->get_var("SELECT edara_product FROM ".$wpdb->prefix."edara_products WHERE wp_product = '".$productMetaID."'");
                    // var_dump($orderItemID->order_item_id,(double)$sub_total,$quantity,$productMetaID,$productID);die();
                    if ($productID) {
                        array_push($saleOrderLine, array('quantity' => $quantity,'price' => $sub_total,'stock_item_id' => $productID));
                        $total+=(double)$sub_total;
                    }
                }
                // var_dump($customerID,$total,$saleOrderLine);die();
                
                if (count($saleOrderLine) >= 0 || $customerID != NULL) {
                        $orderOb = new WC_Order( (int)$order->ID );
                        $data = array('customer_id' => $customerID, 'order_status' =>$order->post_status,'document_date' => $order->post_date,'sub_total' => $orderOb->get_total(),'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'warehouse_id' => $warehouses_selection, 'salesOrder_details' => $saleOrderLine);

                        $ch = curl_init( $url );
                        # Setup request to send json via POST.
                        $payload = json_encode($data);
                        // var_dump($payload);
                        $headers = array(
                           "Content-Type: application/json",
                           "Authorization:".$edara_accsess_token."",
                        );
                        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                        curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
                        // curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                        # Return response instead of printing.
                        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
                        # Send request.
                        $result = curl_exec($ch);
                        curl_close($ch);
                        $result = json_decode($result, true);
                        
                        if ($result['status_code'] == 200) {
                            $charset_collate = $wpdb->get_charset_collate();
                            $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_orders (
                            id bigint(50) NOT NULL AUTO_INCREMENT,
                            wp_order varchar(255),
                            edara_order varchar(255),
                            status varchar(255),
                            PRIMARY KEY (id)
                            ) $charset_collate;";
                            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                            dbDelta( $sql );
                            $is_error = empty( $wpdb->last_error );
                            if ($is_error) {
                                $result = $wpdb->insert($wpdb->prefix.'edara_orders', array(
                                    'wp_order' => $order->ID,
                                    'edara_order' => $result['result'],
                                    'status' => "linked"
                                ));
                            }
                    }else if ($result['status_code'] == 500 && $result['error_message'] == "the specified Documents_Warehouse not exist." || $result['status_code'] == 400 && $result['error_message'] == "Bad Request. DupplicatedCode: Exception of type 'Edara.EdaraBusinessSuite.CommonBusinessLogicLayer.BusinessLogicException' was thrown.") {
                    $data = array('paper_number' => $order->ID,'customer_id' => $customerID, 'order_status' =>$order->post_status,'document_date' => $order->post_date,'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'salesstore_id' => $warehouses_selection, 'salesOrder_details' => $saleOrderLine);
                    $order_id = $order->ID;
                    $ch = curl_init( $url );
                    # Setup request to send json via POST.
                    $payload = json_encode($data);
                    //var_dump($data);die();
                    $headers = array(
                       "Content-Type: application/json",
                       "Authorization:".$edara_accsess_token."",
                    );
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
                    // curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                    # Return response instead of printing.
                    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
                    # Send request.
                    $result = curl_exec($ch);
                    curl_close($ch);
                    $result = json_decode($result, true);
                    if ($result['status_code'] == 200) {
                        $charset_collate = $wpdb->get_charset_collate();
                        $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_orders (
                        id bigint(50) NOT NULL AUTO_INCREMENT,
                        wp_order varchar(255),
                        edara_order varchar(255),
                        status varchar(255),
                        PRIMARY KEY (id)
                        ) $charset_collate;";
                        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                        dbDelta( $sql );
                        $is_error = empty( $wpdb->last_error );
                        if ($is_error) {
                            $dataSelected = $wpdb->get_var("SELECT edara_order FROM ".$wpdb->prefix."edara_orders WHERE wp_order = ".$order_id."");
                            if ($dataSelected) {
                                if ($dataSelected == 0) {
                                    $row = $wpdb->update($wpdb->prefix.'edara_orders', array(
                                        'edara_order' => $result['result'],
                                        'status' => $result['error_message']
                                      ), array('wp_order' => $order_id));
                                }else{
                                    $row = $wpdb->update($wpdb->prefix.'edara_orders', array(
                                        'status' => "linked"
                                      ), array('wp_order' => $order_id));
                                }
                            }else{
                                $result = $wpdb->insert($wpdb->prefix.'edara_orders', array(
                                    'wp_order' => $order_id,
                                    'edara_order' => $result['result'],
                                    'status' => "linked"
                                ));
                            }
                        }
                    }else{
                        $charset_collate = $wpdb->get_charset_collate();
                        // Check that the table does not already exist before continuing
                        $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_orders (
                        id bigint(50) NOT NULL AUTO_INCREMENT,
                        wp_order varchar(255),
                        edara_order varchar(255),
                        status varchar(255),
                        PRIMARY KEY (id)
                        ) $charset_collate;";
                        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                        dbDelta( $sql );
                        $is_error = empty( $wpdb->last_error );
                        if ($is_error) {
                            $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_orders WHERE wp_order = ".$order_id."");
                            if ($dataSelected != NULL)  {
                                $row = $wpdb->update($wpdb->prefix.'edara_orders', array(
                                'wp_order' => $order_id,
                                'edara_order' => "0",
                                'status' => $result['error_message']
                              ), array('wp_order' => $order_id));
                            }else{
                            $result = $wpdb->insert($wpdb->prefix.'edara_orders', array(
                                'wp_order' => $order_id,
                                'edara_order' => 0,
                                'status' => $result['error_message']
                              ));
                            }
                        }
                    }
                }else{
                        $charset_collate = $wpdb->get_charset_collate();
                        // Check that the table does not already exist before continuing
                        $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_orders (
                        id bigint(50) NOT NULL AUTO_INCREMENT,
                        wp_order varchar(255),
                        edara_order varchar(255),
                        status varchar(255),
                        PRIMARY KEY (id)
                        ) $charset_collate;";
                        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
                        dbDelta( $sql );
                        $is_error = empty( $wpdb->last_error );
                        if ($is_error) {
                            $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_orders WHERE wp_order = ".$order->ID."");
                            if ($dataSelected != NULL)  {
                                $row = $wpdb->update($wpdb->prefix.'edara_orders', array(
                                'wp_order' => $order->ID,
                                'edara_order' => "0",
                                'status' => $result['error_message']
                              ), array('wp_order' => $order->ID));
                            }else{
                            $result = $wpdb->insert($wpdb->prefix.'edara_orders', array(
                                'wp_order' => $order->ID,
                                'edara_order' => 0,
                                'status' => $result['error_message']
                              ));
                            }
                        }
                    }
                }
                

            }
        }
        if ($orders_selection == "new_orders") {
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."edara_orders (
            id bigint(50) NOT NULL AUTO_INCREMENT,
            wp_order varchar(255),
            edara_order varchar(255),
            status varchar(255),
            PRIMARY KEY (id)
            ) $charset_collate;";
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta( $sql );
            $is_error = empty( $wpdb->last_error );
        }
        return true;
    }else{
        if ($orders_selection == "all_orders") {
            $result = $wpdb->update($wpdb->prefix.'edara_config', array(
                  'edara_email' => $edara_email,
                  'edara_domain' => $edara_domain,
                  'products_selection' => $products_selection,
                  'customers_selection' => $customers_selection,
                  'orders_selection' => $orders_selection,
                  'from_date' => $from_date,
                  'warehouses_selection' => $warehouses_selection,
                  'sale_price' => $sale_price,
                    'edara_accsess_token' => $edara_accsess_token
                ), array('id'=>1));
        }else{
            $result = $wpdb->update($wpdb->prefix.'edara_config', array(
                  'edara_email' => $edara_email,
                  'edara_domain' => $edara_domain,
                  'products_selection' => $products_selection,
                  'customers_selection' => $customers_selection,
                  'orders_selection' => $orders_selection,
                  'warehouses_selection' => $warehouses_selection,
                  'sale_price' => $sale_price,
                    'edara_accsess_token' => $edara_accsess_token
                ), array('id'=>1));
        }
    }
    return true;
}else{
    var_dump($wpdb->last_error);die();
}
