<?php
declare(strict_types=1);
 
namespace Edara\Includes;

use Automattic\WooCommerce\Admin\Overrides\Order;

class EdaraCore
{
    public function init(): void
    {
        (new EdaraEndpoint())->addHooks();
        $this->addHooks();
    }

    private function addHooks()
    {
        $this->logFunction("addHooks");
        add_action( 'save_post_product', array( __CLASS__, 'my_product_insert' ) );
        add_action( 'user_register', array( __CLASS__, 'my_user_register' ) );
        add_action( 'profile_update', array( __CLASS__, 'my_user_update' ), 10, 2 );
        add_action( 'woocommerce_thankyou', array( __CLASS__, 'my_orders_hooks' ) );
        add_action( 'woocommerce_resume_order', array( __CLASS__, 'my_orders_hooks' ) );
        add_action( 'woocommerce_new_order', array( __CLASS__, 'my_orders_hooks' ) );
        add_action( 'woocommerce_update_order', array( __CLASS__, 'my_update_order' ) );
        
        
        // phpcs:disable
        add_action('edara_sync_categories_callback', [new ProductService(), 'syncCategories']);
        add_action('edara_sync_products_from_wp_to_edara_callback', [new ProductService(), 'syncProductsNamesFromWPToEdara']);
        add_action('edara_sync_stock_balance_callback', [new ProductService(), 'dailyBalanceChecker']);
        add_action('edara_bundle_seeder_callback', [new ProductService(), 'bundleSeeder']);
        add_action('edara_product_seeder_callback', [new ProductService(), 'seedProducts']);
        add_action('edara_create_product_callback', [new ProductService(), 'createProduct']);
        add_action('edara_update_product_callback', [new ProductService(), 'updateProduct']);
        add_action('edara_stock_balance_changes_callback', [new StockService(), 'updateProductStockBalance']);
        add_action('edara_reserved_balance_changed_callback', [new StockService(), 'updateProductStockBalance']);
        add_action('woocommerce_order_status_processing', [new OrderService(), 'updateOrCreateExternalOrder'], 50);
        add_action('trash_shop_order', [new OrderService(), 'orderMovedToTrash'], 10);
        add_action('untrashed_post', [new OrderService(), 'restoreOrderFromTrash']);
        add_action('woocommerce_order_edit_status', [new OrderService(), 'editOrderStatusWorkflow'], 1, 2);
        add_action('edara_order_status_changed_callback', [new OrderService(), 'orderStatusChangedToShippedCallback']);
        // add_action('registered_post_type', [$this, 'disableAddingNewProduct'], 50, 2);
        add_action('add_meta_boxes', [$this, 'addEdaraQuickLinks']);
        add_action('add_meta_boxes', [$this, 'addEdaraProductQuickLinks']);
        add_filter('cron_schedules', [$this ,'registerNewCronSchedules'] );
        add_action('every_six_hours_checker', [new ProductService(), 'bundleSeeder']);
        add_filter('wc_order_statuses', [$this ,'registerNewOrderStatus']);
        add_filter('woocommerce_my_account_my_orders_actions', [$this ,'validateOrderTransitionForMyAccount'],20, 10);
        add_filter('woocommerce_valid_order_statuses_for_cancel', [new OrderService(), 'validToCancelFromFrontEnd'], 50 ,2);
        add_action('woocommerce_cancelled_order', [new OrderService(), 'cancelOrderFromFrontend'], 50 ,2);
        add_filter('manage_edit-shop_order_columns', [$this, 'registerNewOrderColInHeader']);
        add_action('manage_shop_order_posts_custom_column', [$this, 'addOrderAdditionalInfoContent']);
        add_filter('woocommerce_product_data_tabs', [$this, 'hideInventoryTabInProductPage'], 10, 1);
        add_filter('woocommerce_inventory_settings', [$this, 'addAdditionalOptionForInventorySettings'], 10, 1);
        add_filter('woocommerce_get_availability_text', [$this, 'changeProductAvailabilityText'], 10, 2);
        add_action('edara_check_product_discount_due_dates', [new ProductService(), 'checkProductDiscountDueDates']);

        // Register this action on development mode only
        if(false === EDARA_INTEGRATION_PLUGIN_IS_PRODUCTION)
        {
            add_action('edara_reset_sales_order_callback', [new OrderService(), 'resetSalesOrderOnEdara'], 50 ,2);
            add_action('edara_reset_products_callback', [new ProductService(), 'resetProducts'], 50 ,2);
            add_action('edara_reset_local_products_callback', [new ProductService(), 'resetLocalProducts'], 50 ,2);
        }

        //Schedule an action if it's not already scheduled
        if ( ! wp_next_scheduled( 'edara_check_product_discount_due_dates' ) ) {
            wp_schedule_event( time(), 'daily', 'edara_check_product_discount_due_dates' );
        }


        if ( ! wp_next_scheduled( 'every_six_hours_checker' ) ) {
            wp_schedule_event( time(), 'every_six_hours_edara_checker', 'every_six_hours_checker' );
        }

        // Check if the scheduled event is already set then nothing to do
        // Fix the pending payment issue
        if ( ! wp_get_scheduled_event( 'woocommerce_cancel_unpaid_orders' ) ) {
            $held_duration = get_option( 'woocommerce_hold_stock_minutes', '60' );

            if ( '' !== $held_duration ) {
                wp_schedule_single_event( time() + ( absint( $held_duration ) * 60 ), 'woocommerce_cancel_unpaid_orders' );
            }
        }

        // Register daily cron to check the scheduled Start|End discounts
//        if ( ! wp_next_scheduled( 'edara_daily_product_discount_checker_callback' ) ) {
//            wp_clear_scheduled_hook('edara_daily_product_discount_checker_callback');
//            wp_schedule_event( time(), 'daily', 'edara_daily_product_discount_checker_callback' );
//        }
        // phpcs:enable

        add_action( 'admin_enqueue_scripts', [new ProductTaxRate(), 'enqueueScripts'] );
        add_action( 'wp_ajax_nopriv_sync_products_tax_rate', [new ProductTaxRate(), 'startSyncProductsTaxRate'] );
        add_action( 'wp_ajax_sync_products_tax_rate', [new ProductTaxRate(), 'startSyncProductsTaxRate'] );

        if (1 == array_get($_REQUEST,ProductTaxRate::SYNC_PRODUCT_TAX_RATE)){
            if ( false == get_transient( ProductTaxRate::SYNC_PRODUCT_TAX_RATE ) ) {
                set_transient( ProductTaxRate::SYNC_PRODUCT_TAX_RATE, [
                    'limit' => 0,
                    'offset' => 0,
                    'total_count' => 100
                ] );
                $_SERVER['PHP_SELF'];
            }
        }
    }

    /**
     * Schedule this import if the post is an order or refund.
     *
     * @param int $post_id Post ID.
     */
    public static function my_product_insert( $post_id ) {
        EdaraCore::logFunctionStatic("my_product_insert");
        global $wpdb;
        // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->base_prefix.'edara_config';
        $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );
        

        if ( ! $wpdb->get_var( $query ) == $table_name ) {
            $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 );
            if ($is_error) {

            }
        }
        
        $products_selection = $wpdb->get_var("SELECT products_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");
        $edara_accsess_token = $wpdb->get_var("SELECT edara_accsess_token FROM ".$wpdb->prefix."edara_config WHERE id = 1");

        if ($products_selection == "wp_to_edara" || $products_selection == "edara_to_wp" ) {
            $products_table = $wpdb->base_prefix.'edara_products';
            $queryProducts = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $products_table ) );
            if ($products_table == $wpdb->get_var( $queryProducts )) {
                $productExsists = $wpdb->get_var("SELECT edara_product FROM ".$wpdb->prefix."edara_products WHERE wp_product = ".$_POST['post_ID']);
                if ($productExsists) {
                    $productExsistsID = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_products WHERE wp_product = ".$_POST['post_ID']);
                    if ($productExsists == 0) {
                        // update status
                        $skuProduct = get_post_meta( $_POST['post_ID'], '_sku', true );
                        $url = "https://api.edara.io/v2.0/stockItems";
                        $price = $_POST['_regular_price'] != "" ? (double)$_POST['_regular_price'] : 0;
                        $data = array('description' => $_POST['post_title'], 'sku' =>$skuProduct,'price' => $price);

                        // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
                        $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);
                        // var_dump($result['status_code']);die();
                        if ($result['status_code'] == 200) {
                              $result = $wpdb->update($wpdb->prefix.'edara_products', array(
                                'edara_product' => $result['result'],
                                'status' => "linked"
                              ), array('id'=>$productExsistsID));
                        }else{
                            $post_id = $_POST['post_ID'];
                            $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_products WHERE wp_product = ".$post_id."");
                            if ($dataSelected != NULL)  {
                                $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                                'wp_product' => $post_id,
                                'edara_product' => "0",
                                'status' => $result['error_message']
                              ), array('wp_product' => $post_id));
                            }else{
                                $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                    'wp_product' => $post_id,
                                    'edara_product' => 0,
                                    'status' => $result['error_message']
                                  ));
                            }
                        }
                    }else{
                        // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
                        $product = $wpdb->get_var( "SELECT menu_order FROM ".$wpdb->prefix."posts WHERE ID = ".$_POST['post_ID']." AND post_type = 'product'");
                        //var_dump($product);die();
                        $url = "https://api.edara.io/v2.0/stockItems/UpdateByCode/".$product;
                        $price = $_POST['_regular_price'] != "" ? (double)$_POST['_regular_price'] : 0;
                        $skuProduct = get_post_meta( $_POST['post_ID'], '_sku', true );
                        
                        $sale_price = $wpdb->get_var("SELECT sale_price FROM ".$wpdb->prefix."edara_config WHERE id = 1");

                        if ($sale_price == "sale_price") {
                            $data = array('description' => $_POST['post_title'], 'code' =>$product,'price' => $price);
                        }else if ($sale_price == "dealer_price") {
                            $data = array('description' => $_POST['post_title'], 'code' =>$product,'dealer_price' => $price);
                        }else{
                            $data = array('description' => $_POST['post_title'], 'code' =>$product,'supper_dealer_price' => $price);
                        }

                        // $data = array('description' => $_POST['post_title'], 'sku' =>$skuProduct,'price' => $price,'code' => $product);

                        $options = array(
                            'http' => array(
                                'header'  => "Authorization:".$edara_accsess_token."",
                                'method'  => 'PUT',
                                '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) {
                              $result = $wpdb->update($wpdb->prefix.'edara_products', array(
                                'status' => "linked"
                              ), array('id'=>$productExsistsID));
                        }else{
                            $post_id = $_POST['post_ID'];
                            $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_products WHERE wp_product = ".$post_id."");
                            if ($dataSelected != NULL)  {
                                $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                                'wp_product' => $post_id,
                                'edara_product' => "0",
                                'status' => $result['error_message']
                              ), array('wp_product' => $post_id));
                            }else{
                                $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                    'wp_product' => $post_id,
                                    'edara_product' => 0,
                                    'status' => $result['error_message']
                                  ));
                            }
                        }
                    }
                }else{
                    $url = "https://api.edara.io/v2.0/stockItems";
                    $price = $_POST['_regular_price'] != "" ? (double)$_POST['_regular_price'] : 0;
                    $skuProduct = get_post_meta( $_POST['post_ID'], '_sku', true );
                    if ($skuProduct == "") {
                        $skuProduct = $_POST['_sku'];
                    }
                    $sale_price = $wpdb->get_var("SELECT sale_price FROM ".$wpdb->prefix."edara_config WHERE id = 1");
                        
                    if ($sale_price == "sale_price") {
                        $data = array('description' => $_POST['post_title'], 'sku' =>$skuProduct,'price' => $price);
                    }else if ($sale_price == "dealer_price") {
                        $data = array('description' => $_POST['post_title'], 'sku' =>$skuProduct,'dealer_price' => $price);
                    }else{
                        $data = array('description' => $_POST['post_title'], 'sku' =>$skuProduct,'supper_dealer_price' => $price);
                    }

                    // $data = array('description' => $_POST['post_title'], 'sku' =>$skuProduct,'price' => $price);

                    // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
                    $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);
                    // var_dump($result['status_code']);die();
                    if ($result['status_code'] == 200) {
                          $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                'wp_product' => $post_id,
                                'edara_product' => $result['result'],
                                'status' => "linked"
                          ));
                    }else{
                        $post_id = $_POST['post_ID'];
                        $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_products WHERE wp_product = ".$post_id."");
                        if ($dataSelected != NULL)  {
                            $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                            'wp_product' => $post_id,
                            'edara_product' => "0",
                            'status' => $result['error_message']
                          ), array('wp_product' => $post_id));
                        }else{
                            $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                'wp_product' => $post_id,
                                'edara_product' => $result['result'],
                                'status' => "linked"
                              ));
                        }
                    }
                }

            }
            
        }
             
        return true;
    }
    /**
     * Schedule this import if the post is an order or refund.
     *
     * @param int $post_id Post ID.
     */
    public static function my_user_register( $user_id ) {
        EdaraCore::logFunctionStatic("my_user_register");
        global $wpdb;
        // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->base_prefix.'edara_config';
        $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );

        if ( ! $wpdb->get_var( $query ) == $table_name ) {
            $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 );
            if ($is_error) {

            }
        }

        $edara_accsess_token = $wpdb->get_var("SELECT edara_accsess_token FROM ".$wpdb->prefix."edara_config WHERE id = 1");
        $customers_table = $wpdb->base_prefix.'edara_customers';
        $queryCustomers = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $customers_table ) );
        if ($customers_table == $wpdb->get_var( $queryCustomers )) {
            $customerExsists = $wpdb->get_var("SELECT edara_customer FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$user_id);
            if ($customerExsists) {
                $customerExsistsID = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$user_id);
                // if ($customerExsists == 0) {
                    // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
                    $customers_selection = $wpdb->get_var("SELECT customers_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");
                    $url = "https://api.edara.io/v2.0/customers";

                    $customer_data = $wpdb->get_var( "SELECT * FROM ".$wpdb->prefix."users WHERE ID = ".$user_id."");

                    $data = array('name' => $_POST['user_login'], 'email' =>$_POST['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' => $user_id,
                                'edara_customer' => $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_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 = ".$user_id."");
                            if ($dataSelected != NULL)  {
                                $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                                'wp_customer' => $user_id,
                                'edara_customer' => "0",
                                'status' => $result['error_message']
                              ), array('wp_customer' => $user_id));
                            }else{
                            $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                'wp_customer' => $user_id,
                                'edara_customer' => 0,
                                'status' => $result['error_message']
                              ));
                            }
                        }
                    }
                // }else{

                // }
                
                
            }else{
                $customerExsistsID = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$user_id);
                
                // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
                $customers_selection = $wpdb->get_var("SELECT customers_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");
                $url = "https://api.edara.io/v2.0/customers";

                $customer_data = $wpdb->get_var( "SELECT * FROM ".$wpdb->prefix."users WHERE ID = ".$user_id."");

                $data = array('name' => $_POST['user_login'], 'email' =>$_POST['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) {
                      $result = $wpdb->insert($wpdb->prefix.'edara_customers', array(
                        'wp_customer' => $user_id,
                        'edara_customer' => $result['result'],
                        'status' => "linked"
                      ));
                }else{
                    $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$user_id."");
                    if ($dataSelected != NULL)  {
                        $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                        'wp_customer' => $user_id,
                        'edara_customer' => "0",
                        'status' => $result['error_message']
                      ), array('wp_customer' => $user_id));
                    }else{
                    $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                        'wp_customer' => $user_id,
                        'edara_customer' => 0,
                        'status' => $result['error_message']
                      ));
                    }
                }
            }
        }

        
             
        return true;
    }

    public static function my_user_update( $user_id ) {
        EdaraCore::logFunctionStatic("my_user_update");
        global $wpdb;
        // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->base_prefix.'edara_config';
        $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );

        if ( ! $wpdb->get_var( $query ) == $table_name ) {
            $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),
            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 );
            if ($is_error) {

            }
        }
        $edara_accsess_token = $wpdb->get_var("SELECT edara_accsess_token FROM ".$wpdb->prefix."edara_config WHERE id = 1");

        $customers_table = $wpdb->base_prefix.'edara_customers';
        $queryCustomers = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $customers_table ) );
        if ($customers_table == $wpdb->get_var( $queryCustomers )) {
            $customerExsists = $wpdb->get_var("SELECT edara_customer FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$user_id);
            if ($customerExsists) {
                $customerExsistsID = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$user_id);
                if ($customerExsists == 0) {
                    // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
                    
                    $url = "https://api.edara.io/v2.0/customers";
                    $nameC = isset($_POST['nickname']) ? $_POST['nickname'] : $_POST['user_login'];
                    $data = array('name' => $nameC, 'email' =>$_POST['email'],'phone' => $_POST['billing_phone'],'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->update($wpdb->prefix.'edara_customers', array(
                                'wp_customer' => $user_id,
                                'edara_customer' => $customerExsists,
                                'status' => "linked"
                              ), array('wp_customer' => $user_id));
                            }
                    }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 = ".$user_id."");
                            if ($dataSelected != NULL)  {
                                $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                                'wp_customer' => $user_id,
                                'edara_customer' => "0",
                                'status' => $result['error_message']
                              ), array('wp_customer' => $user_id));
                            }else{
                            $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                'wp_customer' => $user_id,
                                'edara_customer' => 0,
                                'status' => $result['error_message']
                              ));
                            }
                        }
                    }
                    

                }else{
                    // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
                    $url = "https://api.edara.io/v2.0/customers";
                    $nameC = isset($_POST['nickname']) ? $_POST['nickname'] : $_POST['user_login'];
                    $data = array('id' => $customerExsists,'name' => $nameC, 'email' =>$_POST['email'],'phone' => $_POST['billing_phone'],'payment_type' => 'Credit');
                    
                    $options = array(
                        'http' => array(
                            'header'  => "Authorization:".$edara_accsess_token."",
                            'method'  => 'PUT',
                            '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->update($wpdb->prefix.'edara_customers', array(
                                'status' => "linked"
                              ), array('wp_customer' => $user_id));
                            }
                    }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 = ".$user_id."");
                            if ($dataSelected != NULL)  {
                                $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                                'wp_customer' => $user_id,
                                'edara_customer' => "0",
                                'status' => $result['error_message']
                              ), array('wp_customer' => $user_id));
                            }else{
                            $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                                'wp_customer' => $user_id,
                                'edara_customer' => 0,
                                'status' => $result['error_message']
                              ));
                            }
                        }
                    }
                }
            }else{
                // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
                    
                $url = "https://api.edara.io/v2.0/customers";
                $nameC = isset($_POST['nickname']) ? $_POST['nickname'] : $_POST['user_login'];
                $data = array('name' => $nameC, 'email' =>$_POST['email'],'phone' => $_POST['billing_phone'],'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->update($wpdb->prefix.'edara_customers', array(
                            'wp_customer' => $user_id,
                            'edara_customer' => $result['result'],
                            'status' => "linked"
                          ), array('wp_customer' => $user_id));
                        }
                }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 = ".$user_id."");
                        if ($dataSelected != NULL)  {
                            $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                            'wp_customer' => $user_id,
                            'edara_customer' => "0",
                            'status' => $result['error_message']
                          ), array('wp_customer' => $user_id));
                        }else{
                        $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                            'wp_customer' => $user_id,
                            'edara_customer' => 0,
                            'status' => $result['error_message']
                          ));
                        }
                    }
                }
            }
        }
        
             
        return true;
    }
    /**
     * Schedule this import if the post is an order or refund.
     *
     * @param int $post_id Post ID.
     */
    public static function my_orders_hooks( $order_id ) {
        EdaraCore::logFunctionStatic("my_orders_hooks");
        global $wpdb;
        // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";

        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->base_prefix.'edara_config';
        $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );

        if ( ! $wpdb->get_var( $query ) == $table_name ) {
            $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 );
            if ($is_error) {

            }
        }
        $edara_accsess_token = $wpdb->get_var("SELECT edara_accsess_token FROM ".$wpdb->prefix."edara_config WHERE id = 1");

        $orders_table = $wpdb->base_prefix.'edara_orders';
        $queryOrders = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $orders_table ) );
        if ($orders_table == $wpdb->get_var( $queryOrders )) {
            // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
            $order = wc_get_order( $order_id );
            $orders_selection = $wpdb->get_var("SELECT orders_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");
            $from_date = $wpdb->get_var("SELECT from_date FROM ".$wpdb->prefix."edara_config WHERE id = 1");
            $url = "https://api.edara.io/v2.0/salesOrders";

            // if ($orders_selection == "all_orders") {

            //     $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->get_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->get_id()."'");

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

            //         $customerID = $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_subtotal' 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 sku FROM ".$wpdb->prefix."wc_product_meta_lookup WHERE product_id = '".$productMetaID."'");
            //             if ($productID) {
            //                 array_push($saleOrderLine, array('quantity' => $quantity,'price' => $sub_total,'stock_item_id' => $productID));
            //                 $total+=(double)$sub_total;
            //             }
            //         }
            //         if (count($saleOrderLine) >= 0 || $customerID != NULL) {
            //                 $data = array('customer_id' => $customerID, 'order_status' =>$order->get_status(),'document_date' => $order->post_date,'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'warehouse_id' => 1, '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: Bearer ".$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{
            //                 $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{
            $order = wc_get_order( $order_id );
            
            $orderData = $order->get_data();
            $userName = $orderData['billing']['first_name'] . " " . $orderData['billing']['last_name'];
            $userEmail = $orderData['billing']['email'];
            $wooCustomerId = $order->get_user_id();

            $orderMeta = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."postmeta WHERE meta_key = '_customer_user' AND post_id =".$order->get_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->get_id()."'");

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

            // $customerID = $wpdb->get_var("SELECT edara_id FROM ".$wpdb->prefix."usermeta WHERE meta_key = 'edara_id' AND meta_value = '".$customerMetaID."'");
            // $customerID = $wpdb->get_var("SELECT edara_customer FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = " . $wooCustomerId);
            
            $customerID = NULL;
            $findCustomerUrl = "https://api.edara.io/v2.0/customers/FindByEmail/" . $orderData['billing']['email'];
            $options = array(
                    'http' => array(
                        'header'  => "Authorization:".$edara_accsess_token."",
                        'method'  => 'GET',
                    )
                );
                $context  = stream_context_create($options);
                $result = file_get_contents($findCustomerUrl, false, $context);
                
                $result = json_decode($result, true);
                if($result['status_code'] == 200){
                    $customerID = $result['result']['id'];
                }

            if ($customerID == NULL) {
                $url = "https://api.edara.io/v2.0/customers";

                // $customer_data_user_login = $wpdb->get_var( "SELECT user_login FROM ".$wpdb->prefix."users WHERE ID = ".$customerMetaID."");
                // $customer_data_user_email = $wpdb->get_var( "SELECT user_email FROM ".$wpdb->prefix."users WHERE ID = ".$customerMetaID."");
                $customer_data_user_login = $userName;
                $customer_data_user_email = $userEmail;

                $data = array('name' => $customer_data_user_login, 'email' =>$customer_data_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);
                EdaraCore::logRequest("Post if customerId equals null",$url,$options,$result);
                if ($result['status_code'] == 200) {
                    echo "<script>console.log('Debug Objects: " . $result . "' );</script>";
                    $customerID = $result['result'];
                      $result = $wpdb->insert($wpdb->prefix.'edara_customers', array(
                        'wp_customer' => $customerMetaID,
                        'edara_customer' => $result['result'],
                        'status' => "linked"
                      ));
                      
                }else{
                    $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$customerMetaID."");
                    if ($dataSelected != NULL)  {
                        $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                        'wp_customer' => $customerMetaID,
                        'edara_customer' => "0",
                        'status' => $result['error_message']
                      ), array('wp_customer' => $customerMetaID));
                    }else{
                    $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                        'wp_customer' => $customerMetaID,
                        'edara_customer' => 0,
                        'status' => $result['error_message']
                      ));
                    }
                }
            }

            $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_subtotal' 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 sku FROM ".$wpdb->prefix."wc_product_meta_lookup WHERE product_id = '".$productMetaID."'");
                $productID = $wpdb->get_var("SELECT edara_product FROM ".$wpdb->prefix."edara_products WHERE wp_product = '".$productMetaID."'");
                if ($productID) {
                    array_push($saleOrderLine, array('quantity' => $quantity,'price' => $sub_total,'stock_item_id' => $productID));
                    $total+=(double)$sub_total;
                }
            }
            
            $saleOrderInstallmentsLine = [];
            foreach ($orderItemIDs as $orderItemID) {
                $sub_total = $wpdb->get_var("SELECT meta_value FROM ".$wpdb->prefix."woocommerce_order_itemmeta WHERE meta_key = '_line_subtotal' 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 sku FROM ".$wpdb->prefix."wc_product_meta_lookup WHERE product_id = '".$productMetaID."'");
                $productID = $wpdb->get_var("SELECT edara_product FROM ".$wpdb->prefix."edara_products WHERE wp_product = '".$productMetaID."'");
                if ($productID) {
                    array_push($saleOrderInstallmentsLine, array('due_date' => date("y-M-d H:i:s"),'amount' => $sub_total,'days_limit' => 0));
                    //$total+=(double)$sub_total;
                }
            }

            $warehouseID = $wpdb->get_var("SELECT warehouses_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");

            if (count($saleOrderLine) > 0 && $customerID != NULL) {
                EdaraCore::logGeneral("First if count salesOrderLine = " . count($saleOrderLine) ." and Customer id is " . $customerID);
                $url = "https://api.edara.io/v2.0/salesOrders";
                $orderDate = $order->get_date_created();
                $orderStatus = $order->get_status();
                if($orderStatus == 'processing'){
                    $orderStatus = 'pending';
                }
                // $data = array('paper_number' => $order->get_id(),'customer_id' => $customerID, 'order_status' =>$order->get_status(),'document_date' => $orderDate->date("Y-m-d H:i:s"),'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'warehouse_id' => $warehouseID, 'salesOrder_details' => $saleOrderLine, 'salesOrder_installments' => $saleOrderInstallmentsLine);
                $data = array('paper_number' => $order->get_id(),'customer_id' => $customerID, 'order_status' => $orderStatus,'document_date' => $orderDate->date("Y-m-d H:i:s"),'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'warehouse_id' => $warehouseID, 'salesOrder_details' => $saleOrderLine, 'salesOrder_installments' => $saleOrderInstallmentsLine);

                $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);
                EdaraCore::logRequest("Post if customerId not null",$url,$payload,$result);
                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 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->get_id(),'customer_id' => $customerID, 'order_status' =>$order->get_status(),'document_date' => $orderDate->date("Y-m-d H:i:s"),'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'salesstore_id' => $warehouseID, 'salesOrder_details' => $saleOrderLine);

                    $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']
                          ));
                        }
                    }
                }
                
            }
        }
        
            
        // }
             
        return true;
    }

    public static function my_update_order($order_id){
        EdaraCore::logFunctionStatic("my_update_order");
        // var_dump($order_id);die();https://api.edara.io/v2.0/salesOrders/UpdateByCode/SO-1-274

        global $wpdb;
        // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";

        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->base_prefix.'edara_config';
        $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );

        if ( ! $wpdb->get_var( $query ) == $table_name ) {
            $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 );
            if ($is_error) {

            }
        }
        $edara_accsess_token = $wpdb->get_var("SELECT edara_accsess_token FROM ".$wpdb->prefix."edara_config WHERE id = 1");

        $orders_table = $wpdb->base_prefix.'edara_orders';
        $queryOrders = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $orders_table ) );
        if ($orders_table == $wpdb->get_var( $queryOrders )) {
            // $edara_accsess_token = "5ivhDvWwFzgB9nljbwKajWC7BDelZPcZ0odfIfW4hzs=";
            $order = wc_get_order( $order_id );
            $orders_selection = $wpdb->get_var("SELECT orders_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");
            $from_date = $wpdb->get_var("SELECT from_date FROM ".$wpdb->prefix."edara_config WHERE id = 1");

            $order_code = $wpdb->get_var("SELECT edara_order FROM ".$wpdb->prefix."edara_orders WHERE wp_order = ".$order_id."");
            if ($order_code == NULL) {
                return true;
            }
            if ($order_code == 0 || $order_code == '0') {
                $sql = "DELETE FROM ".$wpdb->prefix."edara_orders WHERE wp_order = ".$order_id."";
                // var_dump("die");die();
                $wpdb->delete( $wpdb->prefix."edara_orders", array( 'wp_order' => $order_id ) );

                $order = wc_get_order( $order_id );
                $orders_selection = $wpdb->get_var("SELECT orders_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");
                $from_date = $wpdb->get_var("SELECT from_date FROM ".$wpdb->prefix."edara_config WHERE id = 1");
                $url = "https://api.edara.io/v2.0/salesOrders";

                $orderMeta = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."postmeta WHERE meta_key = '_customer_user' AND post_id =".$order->get_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->get_id()."'");

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

                // $customerID = $wpdb->get_var("SELECT edara_id FROM ".$wpdb->prefix."usermeta WHERE meta_key = 'edara_id' AND meta_value = '".$customerMetaID."'");
                $customerID = $wpdb->get_var("SELECT edara_customer FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$customerMetaID);

                if ($customerID == NULL) {
                    $url = "https://api.edara.io/v2.0/customers";

                    $customer_data_user_login = $wpdb->get_var( "SELECT user_login FROM ".$wpdb->prefix."users WHERE ID = ".$customerMetaID."");
                    $customer_data_user_email = $wpdb->get_var( "SELECT user_email FROM ".$wpdb->prefix."users WHERE ID = ".$customerMetaID."");

                    $data = array('name' => $customer_data_user_login, 'email' =>$customer_data_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) {
                          $result = $wpdb->insert($wpdb->prefix.'edara_customers', array(
                            'wp_customer' => $customerMetaID,
                            'edara_customer' => $result['result'],
                            'status' => "linked"
                          ));
                    }else{
                        $dataSelected = $wpdb->get_var("SELECT id FROM ".$wpdb->prefix."edara_customers WHERE wp_customer = ".$customerMetaID."");
                        if ($dataSelected != NULL)  {
                            $row = $wpdb->update($wpdb->prefix.'edara_products', array(
                            'wp_customer' => $customerMetaID,
                            'edara_customer' => "0",
                            'status' => $result['error_message']
                          ), array('wp_customer' => $customerMetaID));
                        }else{
                        $result = $wpdb->insert($wpdb->prefix.'edara_products', array(
                            'wp_customer' => $customerMetaID,
                            'edara_customer' => 0,
                            'status' => $result['error_message']
                          ));
                        }
                    }
                }

                $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_subtotal' 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 sku FROM ".$wpdb->prefix."wc_product_meta_lookup WHERE product_id = '".$productMetaID."'");
                    $productID = $wpdb->get_var("SELECT edara_product FROM ".$wpdb->prefix."edara_products WHERE wp_product = '".$productMetaID."'");
                    if ($productID) {
                        array_push($saleOrderLine, array('quantity' => $quantity,'price' => $sub_total,'stock_item_id' => $productID));
                        $total+=(double)$sub_total;
                    }
                }

                $warehouseID = $wpdb->get_var("SELECT warehouses_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");

                if (count($orderItemIDs) > 0 && $customerID != NULL) {
                    $orderDate = $order->get_date_created();
                    $data = array('paper_number' => $order->get_id(),'customer_id' => $customerID, 'order_status' =>$order->get_status(),'document_date' => $orderDate->date("Y-m-d H:i:s"),'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'warehouse_id' => $warehouseID, 'salesOrder_details' => $saleOrderLine);

                    $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 if ($result['status_code'] == 500 || $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->get_id(),'customer_id' => $customerID, 'order_status' =>$order->get_status(),'document_date' => $orderDate->date("Y-m-d H:i:s"),'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'salesstore_id' => $warehouseID, 'salesOrder_details' => $saleOrderLine);

                        $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']
                              ));
                            }
                        }
                    }
                    
                }
            }
            $url = "https://api.edara.io/v2.0/salesOrders/UpdateByCode/".$order_code;

            
            $order = wc_get_order( $order_id );

            $orderMeta = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."postmeta WHERE meta_key = '_customer_user' AND post_id =".$order->get_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->get_id()."'");

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

            // $customerID = $wpdb->get_var("SELECT edara_id FROM ".$wpdb->prefix."usermeta WHERE meta_key = 'edara_id' AND meta_value = '".$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_subtotal' 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 sku FROM ".$wpdb->prefix."wc_product_meta_lookup WHERE product_id = '".$productMetaID."'");
                $productID = $wpdb->get_var("SELECT edara_product FROM ".$wpdb->prefix."edara_products WHERE wp_product = '".$productMetaID."'");
                if ($productID) {
                    array_push($saleOrderLine, array('quantity' => $quantity,'price' => $sub_total,'stock_item_id' => $productID));
                    $total+=(double)$sub_total;
                }
            }

            $warehouseID = $wpdb->get_var("SELECT warehouses_selection FROM ".$wpdb->prefix."edara_config WHERE id = 1");

            if (count($saleOrderLine) >= 0 || $customerID != NULL) {
                $orderDate = $order->get_date_created();
                $data = array('paper_number' => $order->get_id(),'customer_id' => $customerID, 'order_status' =>$order->get_status(),'document_date' => $orderDate->date("Y-m-d H:i:s"),'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'warehouse_id' => $warehouseID, 'salesOrder_details' => $saleOrderLine);

                // $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",
                //    'method'  => 'PUT',
                //    "Authorization: Bearer ".$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);

                $options = array(
                            'http' => array(
                                'header'  => "Authorization:".$edara_accsess_token."",
                                'method'  => 'PUT',
                                '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_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"
                              ));
                            }
                        }
                        
                        
                }elseif ($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->get_id(),'customer_id' => $customerID, 'order_status' =>$order->get_status(),'document_date' => $orderDate->date("Y-m-d H:i:s"),'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'salesstore_id' => $warehouseID, 'salesOrder_details' => $saleOrderLine);

                    $options = array(
                            'http' => array(
                                'header'  => "Authorization:".$edara_accsess_token."",
                                'method'  => 'PUT',
                                '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_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']
                              ));
                            }
                        }
                    }
                }elseif ( $result['status_code'] == 500) {
                    
                    $data = array('customer_id' => $customerID, 'order_status' =>$order->get_status(),'document_date' => $orderDate->date("Y-m-d H:i:s"),'sub_total' => $total,'total_item_discounts' => 0.0, 'taxable' => true, 'tax' => 0, 'salesstore_id' => $warehouseID, 'salesOrder_details' => $saleOrderLine);


                    // {"customer_id":"21","order_status":"wc-pending","document_date":"2022-01-25","sub_total":5100,"total_item_discounts":0,"taxable":true,"tax":0,"salesstore_id":"14","salesOrder_details":[{"quantity":"1","price":"800","stock_item_id":"67"}]}

                    $options = array(
                            'http' => array(
                                'header'  => "Authorization:".$edara_accsess_token."",
                                'method'  => 'PUT',
                                '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_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']
                          ));
                        }
                    }
                }
                
            }
        }
        
            
        // }
             
        return true;
    }
    /**
     * Add edara meta box quick links
     *
     * @param string $postType
     */
    public function addEdaraQuickLinks(string $postType): void
    {
        $this->logFunction("addEdaraQuickLinks");
        // Escape of it's not a shop order
        if ('shop_order' !== $postType) {
            return;
        }

        add_meta_box('Edara-quick-links', 'Quick Links', function (\WP_Post $order) use ($postType) {
            $orderId = 0;
            if (!method_exists( $order, 'get_id' ) ) {
                $orderId = $order->ID;
            } else {
                $orderId = $order->get_id();
            }
            $externalCodeId = get_post_meta($orderId, 'external_code_id', true);
            $externalIssueOfferingCode = get_post_meta($orderId, 'external_issue_offering_code', true);
            $externalSalesReturnCode = get_post_meta($orderId, 'external_sales_return_code', true);
            // phpcs:disable
            $url = edara_url() . "/Sales/SalesOrder.aspx?Code={$externalCodeId}";
            $IOURL = edara_url() . "/Warehouse/IssueOfferings.aspx?Code={$externalIssueOfferingCode}";
            if ($externalCodeId) {
                $orderService = new OrderService();
                $orders = $orderService->findOrdersByExternalId($externalCodeId);
                echo "SO Code: ($externalCodeId) ";
                echo ("<a target='_blank' href='{$url}' style='color:darkgreen'>View</a> <br \>");
                // Display duplicated SO
                if (count($orders) > 1) {
                    echo "<span style='color: red'><strong>Duplicated SO</strong></span>";
                }
            }

            if ($externalIssueOfferingCode) {
                echo "IO Code: ($externalIssueOfferingCode) ";
                echo("<a target='_blank' href='{$IOURL}' style='color:darkgreen'>View</a> <br \>");
            }

            if ($externalSalesReturnCode) {
                echo "SR Code: ($externalSalesReturnCode) <br \>";
            }
            // phpcs:enable
        }, $postType, 'side', 'high');
    }

    /**
     * Add edara meta box quick links
     *
     * @param string $postType
     */
    public function addEdaraProductQuickLinks(string $postType): void
    {
        $this->logFunction("addEdaraProductQuickLinks");
        // Escape of it's not a shop order
        if ('product' !== $postType) {
            return;
        }

        add_meta_box('Edara-product-quick-links', 'Quick Links', function (\WP_Post $product) use ($postType) {
            $externalId = get_post_meta($product->ID, 'external_id', true);
            $externalBundleId = get_post_meta($product->ID, 'external_bundle_id', true);

            // phpcs:disable
            $url = edara_url() . "/Warehouse/stockitems.aspx?stockItemId={$externalId}";
            if ($externalId) {
                echo "Product Id: ($externalId) ";
                echo ("<a target='_blank' href='{$url}' style='color:darkgreen'>View</a> <br \>");
            }

            if ($externalBundleId) {
                $url = edara_url() . "/Sales/SalesBundles.aspx?Id={$externalBundleId}";
                echo "Bundle Id: ($externalBundleId) ";
                echo ("<a target='_blank' href='{$url}' style='color:darkgreen'>View</a> <br \>");
            }
            // phpcs:enable
        }, $postType, 'side', 'high');
    }

    /**
     * Register new cron schedule
     *
     * @param $schedules
     * @return mixed
     */
    public function registerNewCronSchedules(array $schedules):array
    {
        $this->logFunction("registerNewCronSchedules");
        $schedules['every_six_hours_edara_checker'] = [
            'interval' => 3600 * 6,
            'display' => __('Every 6 Hours #1', 'Edara Integration'),
        ];

        return $schedules;
    }

    /**
     * Register new order status
     *
     * @param array $orderStatuses
     * @return array
     */
    public function registerNewOrderStatus(array $orderStatuses):array
    {
        $this->logFunction("registerNewOrderStatus");
        $orderStatuses['wc-ask_for_return'] = 'Ask for return';

        global $post;
        // Ignore of the current is not an order type
        if (!$post || 'shop_order' !== $post->post_type) {
            return $orderStatuses;
        }

        // Display the pending status for the first time
        if ($post && 'shop_order' === $post->post_type && 'auto-draft' === $post->post_status) {
            return ['wc-pending' => $orderStatuses['wc-pending']];
        }
        // phpcs:ignore
        $output[$post->post_status] = array_get($orderStatuses, $post->post_status, array_get($orderStatuses, 'wc-' . $post->post_status));

        foreach ((new OrderService())->retrieveAvailableStatus($post->post_status) as $one) {
            $output[$one] = $orderStatuses[$one];
        }

        return $output;
    }

    /**
     * Remove cancel from the frontend
     *
     * @param array $actions
     * @param \Automattic\WooCommerce\Admin\Overrides\Order $order
     * @return array
     */
    public function validateOrderTransitionForMyAccount(array $actions, Order $order):array
    {
        $this->logFunction("validateOrderTransitionForMyAccount");
        // Display cancel for pending and processing status only
        if (in_array($order->get_status(), ['pending', 'processing'], true)) {
            return $actions;
        }

        // Else remove cancel action
        if (isset($actions['cancel'])) {
            unset($actions['cancel']);
        }

        return $actions;
    }

    /**
     * Register new order column
     *
     * @param $columns
     * @return array
     */
    public function registerNewOrderColInHeader( $columns ) {
        $this->logFunction("registerNewOrderColInHeader");
        $new_columns = array();
        foreach ( $columns as $column_name => $column_info ) {
            if ( 'order_date' === $column_name ) {
                $new_columns['additional_info'] = 'Additional info';
            }
            $new_columns[ $column_name ] = $column_info;
        }

        return $new_columns;
    }

    /**
     * Add order info into content
     *
     * @param  string  $column
     */
    public function addOrderAdditionalInfoContent(string $column)
    {
        $this->logFunction("addOrderAdditionalInfoContent");
        global $post;

        if ('additional_info' === $column) {
            if ($externalCodeId = get_post_meta($post->ID, 'external_code_id', true)) {
                $url = edara_url() . "/Sales/SalesOrder.aspx?Code={$externalCodeId}";
                echo ("<a target='_blank' href='{$url}' style='color:darkgreen'>#$externalCodeId</a>");
            }

            if ($priceNotMatched = get_post_meta($post->ID, 'price_is_not_matched', true)) {
                echo ' <span style="color: white;background-color: red">#Price not matched</span>';
            }
            // Check duplicated
//            echo '<span style="color: red" class="dashicons dashicons-no"></span>';
        }
    }

    /**
     * Check current user has the capability to manage inventory tab
     *
     * @param $tabs
     * @return mixed
     */
    public function hideInventoryTabInProductPage($tabs)
    {
        $this->logFunction("hideInventoryTabInProductPage");
        // Check current user has the capability to manage the inventory tab
        if (current_user_can('manage_inventory_tab')) {
            unset($tabs['inventory']);
        }

        return ($tabs);
    }

    /**
     * Add setting to show qnt less than 20
     *
     * @param $settings
     */
    public function addAdditionalOptionForInventorySettings($settings)
    {
        $this->logFunction("addAdditionalOptionForInventorySettings");
        foreach ($settings as &$setting) {
            if ('woocommerce_stock_format' === $setting['id']) {
                $setting['options']['show_when_less_than_20'] = 'Always show quantity remaining in stock less than 20 "20 in stock"';
                break;
            }
        }

        return $settings;
    }

    /**
     * Change product availability text to show less than 20
     *
     * @param $availability
     * @param  \WC_Product  $product
     * @return string|void
     */
    public function changeProductAvailabilityText($availability, \WC_Product $product)
    {
        $this->logFunction("changeProductAvailabilityText");
        if ( $product->managing_stock() ) {
            $display      = __( 'In stock', 'woocommerce' );
            $stock_amount = $product->get_stock_quantity();

            switch ( get_option( 'woocommerce_stock_format' ) ) {
                case 'low_amount':
                    if ( $stock_amount <= get_option( 'woocommerce_notify_low_stock_amount' ) ) {
                        /* translators: %s: stock amount */
                        $display = sprintf( __( 'Only %s left in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
                    }
                    break;
                case '':
                    /* translators: %s: stock amount */
                    $display = sprintf( __( '%s in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
                    break;
                case 'show_when_less_than_20':
                    if ($product->get_stock_quantity() <= 20 ) {
                        $display = sprintf( __( '%s in stock', 'woocommerce' ), wc_format_stock_quantity_for_display( $stock_amount, $product ) );
                    }
                    break;
            }

            if ( $product->backorders_allowed() && $product->backorders_require_notification() ) {
                $display .= ' ' . __( '(can be backordered)', 'woocommerce' );
            }
        }

        return $display;
    }
    
    public function logFunction($functionName)
    {
      $message = "Function " . $functionName . ": " . date("Y-m-d H:i:s") . PHP_EOL;
      file_put_contents(ABSPATH . "log_system.log",print_r($message,true),FILE_APPEND);
    }

    public function logRequest($requestType,$url,$requestParams,$response)
    {
      file_put_contents(ABSPATH . "log_system.log",$requestType . " Request",FILE_APPEND);
      file_put_contents(ABSPATH . "log_system.log","URL: " . $url,FILE_APPEND);
      file_put_contents(ABSPATH . "log_system.log","Params: " . print_r($requestParams,true),FILE_APPEND);
      file_put_contents(ABSPATH . "log_system.log",print_r($response,true),FILE_APPEND);
    }
    
    public function logGeneral($message)
    {
      $message = "General log " . $message . ": " . date("Y-m-d H:i:s") . PHP_EOL;
      file_put_contents(ABSPATH . "log_system.log",print_r($message,true),FILE_APPEND);
    }
    
    public static function logFunctionStatic($functionName){
        $message = "Function " . $functionName . ": " . date("Y-m-d H:i:s") . PHP_EOL;
        file_put_contents(ABSPATH . "log_system.log",print_r($message,true),FILE_APPEND);
    }
    
    public static function logRequestStatic($requestType,$url,$requestParams,$response)
    {
      file_put_contents(ABSPATH . "log_system.log",$requestType . " Request",FILE_APPEND);
      file_put_contents(ABSPATH . "log_system.log","URL: " . $url,FILE_APPEND);
      file_put_contents(ABSPATH . "log_system.log","Params: " . print_r($requestParams,true),FILE_APPEND);
      file_put_contents(ABSPATH . "log_system.log",print_r($response,true),FILE_APPEND);
    }
    
    public static function logGeneralStatic($message)
    {
      $message = "General log " . $message . ": " . date("Y-m-d H:i:s") . PHP_EOL;
      file_put_contents(ABSPATH . "log_system.log",print_r($message,true),FILE_APPEND);
    }
}
