<?php

##now uses bulk update
//the global file operation
session_start();
ob_start();

// get the config file
include_once("../public/config.php");
include_once("dailyentryfun.php");

//here the db files that include in the file
// GOES HERE ....................
include("../public/include_dao.php");

//Onlinestoresetting
require_once('../models/dao/OnlinestoresettingDAO.class.php');
require_once('../models/dto/Onlinestoresetting.class.php');
require_once('../models/mysql/OnlinestoresettingMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinestoresettingMySqlExtDAO.class.php');
//Onlinetempcategory
require_once('../models/dao/OnlinetempcategoryDAO.class.php');
require_once('../models/dto/Onlinetempcategory.class.php');
require_once('../models/mysql/OnlinetempcategoryMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetempcategoryMySqlExtDAO.class.php');
//Onlinetemporder
require_once('../models/dao/OnlinetemporderDAO.class.php');
require_once('../models/dto/Onlinetemporder.class.php');
require_once('../models/mysql/OnlinetemporderMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetemporderMySqlExtDAO.class.php');
//Onlinetemporderclient
require_once('../models/dao/OnlinetemporderclientDAO.class.php');
require_once('../models/dto/Onlinetemporderclient.class.php');
require_once('../models/mysql/OnlinetemporderclientMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetemporderclientMySqlExtDAO.class.php');
//Onlinetemporderproduct
require_once('../models/dao/OnlinetemporderproductDAO.class.php');
require_once('../models/dto/Onlinetemporderproduct.class.php');
require_once('../models/mysql/OnlinetemporderproductMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetemporderproductMySqlExtDAO.class.php');
//Onlinetempproduct
require_once('../models/dao/OnlinetempproductDAO.class.php');
require_once('../models/dto/Onlinetempproduct.class.php');
require_once('../models/mysql/OnlinetempproductMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetempproductMySqlExtDAO.class.php');
//Onlinetempstoredetail
require_once('../models/dao/OnlinetempstoredetailDAO.class.php');
require_once('../models/dto/Onlinetempstoredetail.class.php');
require_once('../models/mysql/OnlinetempstoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetempstoredetailMySqlExtDAO.class.php');
//Onlinetempstorereport
require_once('../models/dao/OnlinetempstorereportDAO.class.php');
require_once('../models/dto/Onlinetempstorereport.class.php');
require_once('../models/mysql/OnlinetempstorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/OnlinetempstorereportMySqlExtDAO.class.php');
//Productcat
require_once('../models/dao/ProductcatDAO.class.php');
require_once('../models/dto/Productcat.class.php');
require_once('../models/mysql/ProductcatMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatMySqlExtDAO.class.php');
//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');
//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.class.php');
//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');
//Storereport
require_once('../models/dao/StorereportDAO.class.php');
require_once('../models/dto/Storereport.class.php');
require_once('../models/mysql/StorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/StorereportMySqlExtDAO.class.php');
//Unit
require_once('../models/dao/UnitDAO.class.php');
require_once('../models/dto/Unit.class.php');
require_once('../models/mysql/UnitMySqlDAO.class.php');
require_once('../models/mysql/ext/UnitMySqlExtDAO.class.php');
//Productunit
require_once('../models/dao/ProductunitDAO.class.php');
require_once('../models/dto/Productunit.class.php');
require_once('../models/mysql/ProductunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductunitMySqlExtDAO.class.php');
//Store
require_once('../models/dao/StoreDAO.class.php');
require_once('../models/dto/Store.class.php');
require_once('../models/mysql/StoreMySqlDAO.class.php');
require_once('../models/mysql/ext/StoreMySqlExtDAO.class.php');
//Productcatunit
require_once('../models/dao/ProductcatunitDAO.class.php');
require_once('../models/dto/Productcatunit.class.php');
require_once('../models/mysql/ProductcatunitMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductcatunitMySqlExtDAO.class.php');

//Storereport
require_once('../models/dao/StorereportDAO.class.php');
require_once('../models/dto/Storereport.class.php');
require_once('../models/mysql/StorereportMySqlDAO.class.php');
require_once('../models/mysql/ext/StorereportMySqlExtDAO.class.php');

//Storedetail
require_once('../models/dao/StoredetailDAO.class.php');
require_once('../models/dto/Storedetail.class.php');
require_once('../models/mysql/StoredetailMySqlDAO.class.php');
require_once('../models/mysql/ext/StoredetailMySqlExtDAO.class.php');

//Storemovement
require_once('../models/dao/StoremovementDAO.class.php');
require_once('../models/dto/Storemovement.class.php');
require_once('../models/mysql/StoremovementMySqlDAO.class.php');
require_once('../models/mysql/ext/StoremovementMySqlExtDAO.class.php');
//Availableparcode
require_once('../models/dao/AvailableparcodeDAO.class.php');
require_once('../models/dto/Availableparcode.class.php');
require_once('../models/mysql/AvailableparcodeMySqlDAO.class.php');
require_once('../models/mysql/ext/AvailableparcodeMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];

$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

/* ======================
  Controller Name :- onlinestoresync
  ======================== */
//here goes the instances and general variables
//Onlinestoresetting
$onlineStoreSetting = new Onlinestoresetting();
$onlineStoreSettingDAO = new OnlinestoresettingMySqlDAO();
$onlineStoreSettingEX = new OnlinestoresettingMySqlExtDAO();
//Onlinetempcategory
$onlineTempCategory = new Onlinetempcategory();
$onlineTempCategoryDAO = new OnlinetempcategoryMySqlDAO();
$onlineTempCategoryEX = new OnlinetempcategoryMySqlExtDAO();
//Onlinetemporder
$onlineTempOrder = new Onlinetemporder();
$onlineTempOrderDAO = new OnlinetemporderMySqlDAO();
$onlineTempOrderEX = new OnlinetemporderMySqlExtDAO();
//Onlinetemporderclient
$onlineTempOrderClient = new Onlinetemporderclient();
$onlineTempOrderClientDAO = new OnlinetemporderclientMySqlDAO();
$onlineTempOrderClientEX = new OnlinetemporderclientMySqlExtDAO();
//Onlinetemporderproduct
$onlineTempOrderProduct = new Onlinetemporderproduct();
$onlineTempOrderProductDAO = new OnlinetemporderproductMySqlDAO();
$onlineTempOrderProductEX = new OnlinetemporderproductMySqlExtDAO();
//Onlinetempproduct
$onlineTempProduct = new Onlinetempproduct();
$onlineTempProductDAO = new OnlinetempproductMySqlDAO();
$onlineTempProductEX = new OnlinetempproductMySqlExtDAO();
//Onlinetempstoredetail
$onlineTempStoreDetail = new Onlinetempstoredetail();
$onlineTempStoreDetailDAO = new OnlinetempstoredetailMySqlDAO();
$onlineTempStoreDetailEX = new OnlinetempstoredetailMySqlExtDAO();

//Onlinetempstorereport
$onlineTempStoreReport = new Onlinetempstorereport();
$onlineTempStoreReportDAO = new OnlinetempstorereportMySqlDAO();
$onlineTempStoreReportEX = new OnlinetempstorereportMySqlExtDAO();
//Productcat
$productCat = new Productcat();
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();
//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientEX = new ClientMySqlExtDAO();
//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeEX = new ClientdebtchangeMySqlExtDAO();
//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();
//Storedetail
$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailExt = new StoredetailMySqlExtDAO();
//Storereport
$storeReport = new Storereport();
$storeReportDAO = new StorereportMySqlDAO();
//Unit
$unitDAO = new UnitMySqlDAO();
$unitExt = new UnitMySqlExtDAO();
//Productunit
$productUnit = new Productunit();
$productUnitDAO = new ProductunitMySqlDAO();
$productUnitExt = new ProductunitMySqlExtDAO();
//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();

//Storemovement
$myStoremovement = new Storemovement();
$myStoremovementRecord = new StoremovementMySqlDAO();
$myStoremovementEx = new StoremovementMySqlExtDAO();

//Storedetail
$myStoredetailEx = new StoredetailMySqlExtDAO();
$myStoredetailRecord = new StoredetailMySqlDAO();
$Storedetail = new Storedetail();
//Availableparcode
$availableParcode = new Availableparcode();
$availableParcodeDAO = new AvailableparcodeMySqlDAO();
$availableParcodeEX = new AvailableparcodeMySqlExtDAO();

//check and use the condetion that suite this action
$onlineStoreSetting = getOrHandleOnlineStoreSetting();
$Programsettingdata = $ProgramsettingDAO->load(1);

if ($do == "syncCatAndProducts") {
    if (!empty($onlineStoreSetting->url)) {
        $joinConditionWithStore = " and storedetail.storeid in (0,$onlineStoreSetting->availableStores) ";
        //onlinetempcategory
        $onlineTempCategory = $productCatExt->queryAllForCURLSyncAndLock();
        if (count($onlineTempCategory) > 0) {
            foreach ($onlineTempCategory as $value) {
                $path = str_replace('\\', '/', getcwd()) . '/../views/default/images/cat_image/' . $value->logo;
                //$path = dirname(__FILE__) . '\..\views\default\images\cat_image\\' . $value->logo;
                //handle file
                $value->logo_base64 = base64_encode(file_get_contents($path));
            }
            $response = CURL_IT2($onlineTempCategory, $onlineStoreSetting->url . '/api_erp/syncEditedCatsFromERPCURL');
            if ((int) $response == 1) {
                $onlineTempCategoryEX->TRUNCATE();
            } else {
                $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
                $txt = "syncEditedCatsFromERPCURL ERROR " . date("Y-m-d H:i:s") . " ;\r\n";
                fwrite($myfile, $txt);
            }
        }
        //onlinetempproduct  -- normal product
        $onlineTempProduct = $productExt->queryAllSimpleForCurlNormalSyncAndLock('', $joinConditionWithStore);
        if (count($onlineTempProduct) > 0) {
            foreach ($onlineTempProduct as $value) {
                //handle file
                $path = str_replace('\\', '/', getcwd()) . '/../views/default/images/product_image/';
                //$path = dirname(__FILE__) . '\..\views\default\images\product_image\\' . $value->logo;
                //handle file
                $value->logo_base64 = base64_encode(file_get_contents($path . $value->logo));
                $value->logo1_base64 = base64_encode(file_get_contents($path . $value->logo1));
                $value->logo2_base64 = base64_encode(file_get_contents($path . $value->logo2));
                $value->logo3_base64 = base64_encode(file_get_contents($path . $value->logo3));
                $value->logo4_base64 = base64_encode(file_get_contents($path . $value->logo4));
                $value->logo5_base64 = base64_encode(file_get_contents($path . $value->logo5));
                $value->logo6_base64 = base64_encode(file_get_contents($path . $value->logo6));
                $value->logo7_base64 = base64_encode(file_get_contents($path . $value->logo7));
            }
            $response = CURL_IT2($onlineTempProduct, $onlineStoreSetting->url . '/api_erp/syncEditedProductsFromERPCURL');
            if ((int) $response == 1) {
                $onlineTempProductEX->TRUNCATE();
            } else {
                $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
                $txt = "syncEditedProductsFromERPCURL ERROR " . date("Y-m-d H:i:s") . " ;\r\n";
                fwrite($myfile, $txt);
            }
        }
        echo "Done";
    } else {
        echo "Empty online url";
    }
} elseif ($do == "syncProductQuantityAndStoreReport") {
    if (!empty($onlineStoreSetting->url)) {
        $joinConditionWithStore = " and storedetail.storeid in (0,$onlineStoreSetting->availableStores) ";
        //onlinetempstoredetail
        $onlineTempStoreDetail = $productExt->queryAllOrderedLimitedSimpleForCurlNormal2('', $joinConditionWithStore);
        //$onlineTempStoreDetailEX->queryAllSimpleForCurl($sql);
        if (count($onlineTempStoreDetail) > 0) {
            foreach ($onlineTempStoreDetail as $value) {
                if (empty($onlineStoreSetting->availableStores)) {
                    $value->quantity = 0;
                } else {
                    $value->quantity = $value->sumProductQuantity;
                }

                //handle file
                $path = str_replace('\\', '/', getcwd()) . '/../views/default/images/product_image/';
                //$path = dirname(__FILE__) . '\..\views\default\images\product_image\\' . $value->logo;
                //handle file
                $value->logo_base64 = base64_encode(file_get_contents($path . $value->logo));
                $value->logo1_base64 = base64_encode(file_get_contents($path . $value->logo1));
                $value->logo2_base64 = base64_encode(file_get_contents($path . $value->logo2));
                $value->logo3_base64 = base64_encode(file_get_contents($path . $value->logo3));
                $value->logo4_base64 = base64_encode(file_get_contents($path . $value->logo4));
                $value->logo5_base64 = base64_encode(file_get_contents($path . $value->logo5));
                $value->logo6_base64 = base64_encode(file_get_contents($path . $value->logo6));
                $value->logo7_base64 = base64_encode(file_get_contents($path . $value->logo7));
            }
            $response = CURL_IT2($onlineTempStoreDetail, $onlineStoreSetting->url . '/api_erp/syncProductQuantityFromERPCURL');
            if ((int) $response == 1) {
                $onlineTempStoreDetailEX->TRUNCATE();
            } else {
                $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
                $txt = "syncProductQuantityFromERPCURL ERROR " . date("Y-m-d H:i:s") . " ;\r\n";
                fwrite($myfile, $txt);
            }
        }
        //onlinetempstorereport
        $onlineTempStoreReport = $onlineTempStoreReportEX->queryAllSimpleAndLockForCurl();
        if (count($onlineTempStoreReport) > 0) {
            $response = CURL_IT2($onlineTempStoreReport, $onlineStoreSetting->url . '/api_erp/insertNewStoreReportFromERPCURL');
            if ((int) $response == 1) {
                $onlineTempStoreReportEX->TRUNCATE();
            } else {
                $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
                $txt = "insertNewStoreReportFromERPCURL ERROR " . date("Y-m-d H:i:s") . " ;\r\n";
                fwrite($myfile, $txt);
            }
        }
        echo "Done";
    } else {
        echo "Empty online url";
    }
} elseif ($do == "syncClientsDeptOnline") {
    if (!empty($onlineStoreSetting->url)) {
        if ($onlineStoreSetting->clientdebtchangeStartId >= 0) {
            $last = $onlineStoreSetting->clientdebtchangeStartId;
        } else {
            $last = CURL_IT2($clientsDebtHistory, $onlineStoreSetting->url . '/api_erp/getLastClientDebtChangeIdInOnlineShop');
        }
        //
        if ($last == "error") {
            echo "error";
        } else {
            $id = (int) $last;
            $clientsDebtHistory = $clientDeptChangeEX->getAllClientDeptChangeAfterId($id, ' and client.clientid != 1 ');
            //array_chunk($clientsDebtHistory,30,true);
            $partOfClientsDebtHistory = array();
            foreach ($clientsDebtHistory as $value) {
                array_push($partOfClientsDebtHistory, $value);
                //if (count($partOfClientsDebtHistory) == 30) {
                CURL_IT($partOfClientsDebtHistory, $onlineStoreSetting->url . '/api_erp/updateClientsDebtFromERPCURL');
                $partOfClientsDebtHistory = array();
                //}
            }
            //echo CURL_IT($clientsDebtHistory, $onlineStoreSetting->url . '/api_erp/updateClientsDebtFromERPCURL');
        }
        echo "Done";
    } else {
        echo "Empty online url";
    }
}
##
elseif ($do == "saveOnlineOrders") {
    $allOrders = CURL_IT2(array(), $onlineStoreSetting->url . '/api_erp/ERPSendOrders');
    $allOrders = json_decode($allOrders);

    ###
    $mainStoreId = explode(',', $onlineStoreSetting->availableStores)[0]; //1;
    $onlineStoreId = $onlineStoreSetting->onlinestoreid;
    ###
    foreach ($allOrders as $data_arr) {
        $the_order = $data_arr->order;
        $order_products = $data_arr->order_products;
//        print_r('<pre>');
//        print_r($the_order);
//        print_r($order_products);
//        die();
        //saveorder
        $onlineTempOrder = $onlineTempOrderDAO->queryByOnlineorderid($the_order->id);
        $onlineTempOrder->onlineorderid = $the_order->id;
        $onlineTempOrder->address_id = $the_order->address_id; //of order
        $onlineTempOrder->customerid = getclientId($the_order->client, $onlineStoreSetting, $the_order->id, $the_order->customer_id); //$the_order->customer_id;
        $onlineTempOrder->ordertotal = $the_order->order_total;
        $onlineTempOrder->shippingcost = $the_order->shipping_cost;
        $onlineTempOrder->fulltotal = $the_order->full_total;
        $onlineTempOrder->paytype = $the_order->pay_type;
        $onlineTempOrder->createdatetime = $the_order->create_date_time;
        $onlineTempOrder->orderstatus = $the_order->order_status;
        $onlineTempOrder->tax_value = $the_order->tax_value;
        $onlineTempOrder->userid = (int) $the_order->user_id; //userid online
        if (isset($onlineTempOrder->id) && $onlineTempOrder->id > 0) {
            $onlineTempOrderDAO->update($onlineTempOrder);
            //
            $operationnum = getNextIdStoreMovement();
            $onlineTempOrderProducts = $onlineTempOrderProductDAO->queryByOrderid($onlineTempOrder->onlineorderid);
            foreach ($onlineTempOrderProducts as $value) {
                //move from store online to mainstore
                moveProductFromStoreToAnother($value->productid, $value->quantity, $onlineStoreId, $mainStoreId, $operationnum);
            }
            $onlineTempOrderProductDAO->deleteByOrderid($the_order->id);
        } else {
            $onlineTempOrderDAO->insert($onlineTempOrder);
        }

        //
        $operationnum = getNextIdStoreMovement();
        foreach ($order_products as $value) {
            $onlineTempOrderProduct = $onlineTempOrderProductEX->queryByOrderidAndProductid($value->orderid, $value->productid);
            $onlineTempOrderProduct->orderid = $value->order_id;
            $onlineTempOrderProduct->productid = getProductId($value->product_data, $onlineStoreSetting);
            $onlineTempOrderProduct->sizeid = $value->size_id; //later
            $onlineTempOrderProduct->price = $value->price;
            $onlineTempOrderProduct->quantity = $value->quantity;
            $onlineTempOrderProduct->shippingcost = $value->shipping_cost;
            $onlineTempOrderProduct->total = $value->total;
            $onlineTempOrderProduct->orderstatus = $value->order_status;
            $onlineTempOrderProduct->shippingtype = $value->shipping_type;
            $onlineTempOrderProduct->discountprice = $value->discount_price;
            if (isset($onlineTempOrderProduct->id) && $onlineTempOrderProduct->id > 0) {
                $onlineTempOrderProductDAO->update($onlineTempOrderProduct);
            } else {
                $onlineTempOrderProductDAO->insert($onlineTempOrderProduct);
            }

            //move from mainstore to store online
            moveProductFromStoreToAnother($onlineTempOrderProduct->productid, $onlineTempOrderProduct->quantity, $mainStoreId, $onlineStoreId, $operationnum);
        }
    }
    echo "Done";
}
##
elseif ($do == "autoSyncWithOnline") {
    $smarty->assign("onlineStoreSetting_head", $onlineStoreSetting);
    $smarty->assign("db", $_SESSION['dbname']);
    $smarty->display("onlinestoresettingview/autoSyncWithOnline.html");
} elseif ($do == "autoSyncWithOnlinCatAndProduct") {
    $smarty->assign("onlineStoreSetting_head", $onlineStoreSetting);
    $smarty->assign("db", $_SESSION['dbname']);
    $smarty->display("onlinestoresettingview/autoSyncWithOnlinCatAndProduct.html");
} elseif ($do == "autoSyncWithOnlinProductQuantity") {
    $smarty->assign("onlineStoreSetting_head", $onlineStoreSetting);
    $smarty->assign("db", $_SESSION['dbname']);
    $smarty->display("onlinestoresettingview/autoSyncWithOnlinProductQuantity.html");
}
##
elseif ($do == "updateonlineproductsFromTo") {
    $from = (int) filter_input(INPUT_POST, "from");
    $afterFromId = (int) filter_input(INPUT_POST, "afterFromId");
    $to = (int) filter_input(INPUT_POST, "to");
    $tillEnd = (int) filter_input(INPUT_POST, "tillEnd");
    try {
        $onlineStoreSetting = $onlineStoreSettingDAO->load(1);
        if (!empty($onlineStoreSetting->url)) {
            //$started_at = microtime(true);
            $onlineStoreSetting = $onlineStoreSettingDAO->load(1);
            $joinConditionWithStore = '';
            if ($onlineStoreSetting->availableStores != "") {
                $joinConditionWithStore = " and storeid in ($onlineStoreSetting->availableStores) ";
            }


            $idsQueryString = " and product.productId >= $from ";
            if ($afterFromId == 1) {
                $idsQueryString = " and product.productId > $from ";
            }
            if ($tillEnd == 0) {
                $idsQueryString .= " and product.productId <= $to ";
            }
            ####2-add normal products
            $limit = 1; //50;
            $allproduct = $productExt->queryAllOrderedLimitedSimpleForCurlNormal3($limit, $idsQueryString, $joinConditionWithStore);
            foreach ($allproduct as $value) {
                if (empty($onlineStoreSetting->availableStores)) {
                    $value->quantity = 0;
                } else {
                    $value->quantity = $value->sumProductQuantity;
                }

                //handle file
                $path = str_replace('\\', '/', getcwd()) . '/../views/default/images/product_image/';
                //$path = dirname(__FILE__) . '\..\views\default\images\product_image\\' . $value->logo;
//                $type = pathinfo($path, PATHINFO_EXTENSION);
//                $data = file_get_contents($path);
//                $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
                //handle file
                $value->logo_base64 = base64_encode(file_get_contents($path . $value->logo));
                $value->logo1_base64 = base64_encode(file_get_contents($path . $value->logo1));
                $value->logo2_base64 = base64_encode(file_get_contents($path . $value->logo2));
                $value->logo3_base64 = base64_encode(file_get_contents($path . $value->logo3));
                $value->logo4_base64 = base64_encode(file_get_contents($path . $value->logo4));
                $value->logo5_base64 = base64_encode(file_get_contents($path . $value->logo5));
                $value->logo6_base64 = base64_encode(file_get_contents($path . $value->logo6));
                $value->logo7_base64 = base64_encode(file_get_contents($path . $value->logo7));
            }
            CURL_IT($allproduct, $onlineStoreSetting->url . '/api_erp/copyProductsFromERPCURL');
            ####3-add optic products
            echo (int) $allproduct[0]->productId;
        } else {
            echo -1;
        }
//    echo 'Cool, that only took ' . (microtime(true) - $started_at) . ' seconds!';
    } catch (Exception $e) {
        echo -2;
    }
} elseif ($do == "updateonlineclientsFromTo") {
    $from = (int) filter_input(INPUT_POST, "from");
    $afterFromId = (int) filter_input(INPUT_POST, "afterFromId");
    $to = (int) filter_input(INPUT_POST, "to");
    $tillEnd = (int) filter_input(INPUT_POST, "tillEnd");
    try {
        $onlineStoreSetting = $onlineStoreSettingDAO->load(1);
        if (!empty($onlineStoreSetting->url)) {
            //$started_at = microtime(true);
            $onlineStoreSetting = $onlineStoreSettingDAO->load(1);

            $idsQueryString = " and clientid >= $from ";
            if ($afterFromId == 1) {
                $idsQueryString = " and clientid > $from ";
            }
            if ($tillEnd == 0) {
                $idsQueryString .= " and clientid <= $to ";
            }
            $idsQueryString .= ' and clientid != 1 ';
            ####2
            $limit = 1; //50;
            $allclients = $clientEX->queryAllOrderedLimitedSimpleForCurlNormal2($limit, $idsQueryString);
            CURL_IT($allclients, $onlineStoreSetting->url . '/api_erp/copyClientsFromERPCURL');
            ####3
            echo (int) $allclients[0]->clientid;
        } else {
            echo -1;
        }
//    echo 'Cool, that only took ' . (microtime(true) - $started_at) . ' seconds!';
    } catch (Exception $e) {
        echo -2;
    }
} elseif ($do == "syncClientsDeptOnlineFromTo") {
    $from = (int) filter_input(INPUT_POST, "from");
    $afterFromId = (int) filter_input(INPUT_POST, "afterFromId");
    $to = (int) filter_input(INPUT_POST, "to");
    $tillEnd = (int) filter_input(INPUT_POST, "tillEnd");
    try {
        $onlineStoreSetting = $onlineStoreSettingDAO->load(1);
        if (!empty($onlineStoreSetting->url)) {
            //$started_at = microtime(true);
            $onlineStoreSetting = $onlineStoreSettingDAO->load(1);

            $idsQueryString = " and clientdebtchangeid >= $from ";
            if ($afterFromId == 1) {
                $idsQueryString = " and clientdebtchangeid > $from ";
            }
            if ($tillEnd == 0) {
                $idsQueryString .= " and clientdebtchangeid <= $to ";
            }
            $idsQueryString .= ' and client.clientid != 1 ';
            ####2
            $limit = 1; //50;

            $clientsDebtHistory = $clientDeptChangeEX->getAllClientDeptChange($limit, $idsQueryString);
            CURL_IT($clientsDebtHistory, $onlineStoreSetting->url . '/api_erp/updateClientsDebtFromERPCURL');

            ####3
            echo (int) $clientsDebtHistory[0]->clientdebtchangeid;
        } else {
            echo -1;
        }
//    echo 'Cool, that only took ' . (microtime(true) - $started_at) . ' seconds!';
    } catch (Exception $e) {
        echo -2;
    }
}
/* ===============================
  function in this CONTROLLER
  ================================ */

//by insert temporarly in onlinetemporderclient .then if accept order save in client table depending on user choice new client or existing one
function getclientId($client_data, $onlineStoreSetting, $orderid, $customer_id) {
    global $onlineTempOrderClient;
    global $onlineTempOrderClientDAO;
    global $onlineTempOrderClientEX;
    global $clientDAO;

    $clientid = (int) $client_data->erpid;
    if ($clientid > 0) {
        $client_data = $clientDAO->load($clientid);
        $areaId = $client_data->clientareaid;
    } else {
        $areaId = $onlineStoreSetting->onlineclientareaid;
    }

    $onlineTempOrderClient = $onlineTempOrderClientEX->queryByOrderidAndCustomerId($orderid, $customer_id);
    //save data
    $onlineTempOrderClient->erpid = $clientid;
    $onlineTempOrderClient->customer_id = (int) $client_data->customer_id;
    $onlineTempOrderClient->orderid = $orderid;

    $onlineTempOrderClient->clientname = $client_data->clientname;
    $onlineTempOrderClient->clientcode = $client_data->clientcode;
    $onlineTempOrderClient->clientmobile = $client_data->clientmobile;
    $onlineTempOrderClient->clientdebt = $client_data->clientdebt;
    $onlineTempOrderClient->clientaddress = $client_data->clientaddress;
    $onlineTempOrderClient->clientareaid = $onlineStoreSetting->onlineclientareaid;
    if (isset($onlineTempOrderClient->id) && $onlineTempOrderClient->id > 0) {
        $onlineTempOrderClientDAO->update($onlineTempOrderClient);
    } else {
        $clientid = $onlineTempOrderClientDAO->insert($onlineTempOrderClient);
    }

    return $clientid;
}

function getProductId($product_data, $onlineStoreSetting) {
    global $productDAO;
    global $productExt;
    global $productUnitDAO;
    global $storeReportDAO;
    global $storeDetailDAO;
    $productId = (int) $product_data->erpid;
    $today = date('Y-m-d');
    if ($productId < 1) {
        $product = $productDAO->queryByProductName($product_data->name);
        $product = $product[0];
        ###################################################################
        $parcode = generateParcode();
        removeParcodeFromTable($parcode);
        ###################################################################
        //insert into product tbl
        $product->lastbuyprice = $product_data->productBuyPrice;
        $product->lastbuyprice_withDiscount = $product_data->productBuyPrice;
        $product->meanbuyprice = $product_data->productBuyPrice;
        $product->meanbuyprice_withDiscount = $product_data->productBuyPrice;


        $product->productbuypricereal = $product_data->productBuyPrice;
        $product->buypricereal_precentage = 0;
        $product->buytotal_precentage = 0;
        $product->buyhalf_precentage = 0;
        $product->buypart_precentage = 0;


        $product->type = 0;
        $product->inMenu = 0;
        $product->conditions = 0;
        $product->limitamount = (int) $product_data->limitamount;
        $product->parcode = $parcode;
        $product->expireDate = 0;
        $product->productBuyPrice = $product_data->productBuyPrice;
        $product->productCatId = getCatId($product_data->cat, $onlineStoreSetting);
        $product->productDate = date('Y-m-d');
        $product->productDescription = $product_data->productDescription;
        $product->productName = $product_data->name;
        $product->productSellAllPrice = $product_data->productSellAllPrice;
        $product->productSellHalfPrice = $product_data->productSellHalfPrice;
        $product->productSellUnitPrice = $product_data->productSellUnitPrice;
        $product->userId = 1; //$_SESSION['userid'];
        $product->dailyentryId = 0;
        $product->isService = 0;
        $product->isOptic = 0;
        $product->hasSizeAndColor = 0;

        if (isset($product->productName) && $product->productName != "") {
            $success = file_put_contents('../views/default/images/product_image/' . $product_data->logo, base64_decode($product_data->logo_base64));
            $success = file_put_contents('../views/default/images/product_image/' . $product_data->logo1, base64_decode($product_data->logo1_base64));
            $success = file_put_contents('../views/default/images/product_image/' . $product_data->logo2, base64_decode($product_data->logo2_base64));
            $success = file_put_contents('../views/default/images/product_image/' . $product_data->logo3, base64_decode($product_data->logo3_base64));
            $success = file_put_contents('../views/default/images/product_image/' . $product_data->logo4, base64_decode($product_data->logo4_base64));
            $success = file_put_contents('../views/default/images/product_image/' . $product_data->logo5, base64_decode($product_data->logo5_base64));
            $success = file_put_contents('../views/default/images/product_image/' . $product_data->logo6, base64_decode($product_data->logo6_base64));
            $success = file_put_contents('../views/default/images/product_image/' . $product_data->logo7, base64_decode($product_data->logo7_base64));
            $product->logo = $product_data->logo;
            $product->logo1 = $product_data->logo1;
            $product->logo2 = $product_data->logo2;
            $product->logo3 = $product_data->logo3;
            $product->logo4 = $product_data->logo4;
            $product->logo5 = $product_data->logo5;
            $product->logo6 = $product_data->logo6;
            $product->logo7 = $product_data->logo7;
            if (isset($product->productId) && $product->productId > 0) {
                $productId = $product->productId;
                $productDAO->update($product);
            } else {
                $productId = $productDAO->insert($product);
            }

            if (!empty($productId)) {
//                if ($Unitdone == 0) {
                $productUnit->conditions = 0;
                $productUnit->productid = $productId;
                $productUnit->productnumber = 1;
                $productUnit->productunitdate = $today;
                $productUnit->unitid = 1;
                $productUnit->userid = 1; //$_SESSION['userid'];

                $productUnitDAO->insert($productUnit);
//                }
                //insert into storedetail tbl
                $storeDetail->productid = $productId;
                $storeDetail->productquantity = 0;
                $storeDetail->storedetaildate = $today;
                $storeDetail->storeid = 1;
                $storeDetail->userid = 1; //$_SESSION['userid'];

                $storeDetailDAO->insert($storeDetail);

                //insert into storereport tbl
                $storeReport->processname = "إضافة منتج";
                $storeReport->productafter = 0;
                $storeReport->productbefore = 0;
                $storeReport->productquantity = 0;
                $storeReport->storeid = 1;
                $storeReport->storereportdate = $today;
                $storeReport->storereportmodelid = $productId;
                $storeReport->storereporttype = 0;
                $storeReport->tablename = "productController.php";
                $storeReport->userid = 0; //$_SESSION['userid'];
                $storeReport->productid = $productId;

                $storeReportDAO->insert($storeReport);
            }
            //save client erpid in shop"online"
            $allproduct = $productExt->queryAllOrderedLimitedSimpleForCurlNormal(0, 1, ' and product.productId = ' . $productId);
            $allproduct[0]->onlineid = $product_data->productId;
            $allproduct[0]->quantity = $allproduct[0]->sumProductQuantity;
            $path = str_replace('\\', '/', getcwd()) . '/../views/default/images/product_image/';
            //$path = dirname(__FILE__) . '\..\views\default\images\product_image\\' . $allproduct[0]->logo;
            $allproduct[0]->logo_base64 = base64_encode(file_get_contents($path . $allproduct[0]->logo));
            $allproduct[0]->logo1_base64 = base64_encode(file_get_contents($path . $allproduct[0]->logo1));
            $allproduct[0]->logo2_base64 = base64_encode(file_get_contents($path . $allproduct[0]->logo2));
            $allproduct[0]->logo3_base64 = base64_encode(file_get_contents($path . $allproduct[0]->logo3));
            $allproduct[0]->logo4_base64 = base64_encode(file_get_contents($path . $allproduct[0]->logo4));
            $allproduct[0]->logo5_base64 = base64_encode(file_get_contents($path . $allproduct[0]->logo5));
            $allproduct[0]->logo6_base64 = base64_encode(file_get_contents($path . $allproduct[0]->logo6));
            $allproduct[0]->logo7_base64 = base64_encode(file_get_contents($path . $allproduct[0]->logo7));
            CURL_IT($allproduct, $onlineStoreSetting->url . '/api_erp/copyProductsFromERPCURL');
        }
    }
    return $productId;
}

function getCatId($cat_data, $onlineStoreSetting) {
    global $productCatDAO;
    global $productCatExt;

    $productCatId = (int) $cat_data->erpid;
    $today = date('Y-m-d');
    if ($productCatId < 1) {
        $productCat = $productCatDAO->queryByProductCatName($cat_data->productCatName);
        $productCat = $productCat[0];
        $productCat->discounttype = 0;
        $productCat->selldiscount = 0;
        $productCat->buydiscount = 0;

        $productCat->conditions = 0;
        $productCat->isOptic = 0;
        $productCat->productCatDate = $today;
        $productCat->productCatDescription = $cat_data->productCatDescription;
        $productCat->productCatName = $cat_data->productCatName;
        $productCat->inMenu = 0;
        $productCat->productCatParent = $cat_data->productCatId; //later
        $productCat->userId = 1; //$_SESSION['userid'];

        $productCat->buytotal = 0;
        $productCat->buyhalf = 0;
        $productCat->buypart = 0;
        $productCat->buypricereal = 0;
        $productCat->opticServices = '';


        $success = file_put_contents('../views/default/images/cat_image/' . $cat_data->logo, base64_decode($cat_data->logo_base64));
        $productCat->logo = $cat_data->logo;
        //print_r($productCat);
        if (isset($productCat->productCatId) && $productCat->productCatId > 0) {
            $productCatId = $productCat->productCatId;
            $productCatDAO->update($productCat);
        } else {
            $productCatId = $productCatDAO->insert($productCat);
        }

        //save client erpid in shop"online"
        $all_items = $productCatExt->queryAllOrderedLimitedForCURL(0, 1, ' and productCatId = ' . $productCatId);
        $all_items[0]->onlineid = $cat_data->productCatId;
        $path = str_replace('\\', '/', getcwd()) . '/../views/default/images/cat_image/' . $all_items[0]->logo;
        //$path = dirname(__FILE__) . '\..\views\default\images\cat_image\\' . $all_items[0]->logo;
        $all_items[0]->logo_base64 = base64_encode(file_get_contents($path));
        CURL_IT($all_items, $onlineStoreSetting->url . '/api_erp/copyCatsFromERPCURL');
    }
    return $productCatId;
}

function addPreDigitsToNum($num, $length = 7) {
    global $Programsettingdata;

    if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
        $Programsettingdata->parcodeDigits = 5;
    }
    $length = $Programsettingdata->parcodeDigits;

    $preDigits = '';
    if (strlen($num) != $length) {
        $noDigitsLeft = $length - strlen($num);
        for ($j = 0; $j < $noDigitsLeft; $j++) {
            $preDigits .= '0';
        }
    }
    return $preDigits . $num;
}

function checkbarcode($parcode, $productId = 0) {
    global $productDAO;
    global $productExt;
    global $availableParcodeDAO;
    global $Programsettingdata;
    $flag = 1;
    if ($Programsettingdata->usedParcode == 0) {
        if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
            $Programsettingdata->parcodeDigits = 5;
        }

        $biggestParcode = '';
        for ($i = 1; $i <= (int) $Programsettingdata->parcodeDigits; $i++) {
            $biggestParcode .= '9';
        }
        $biggestParcode = (int) $biggestParcode;


        if ($parcode <= $biggestParcode) {
            $parcodeResult = $availableParcodeDAO->queryByValue($parcode);
            if (isset($parcodeResult) && count($parcodeResult) > 0) {
                //if value in the table it is not repeated
                $flag = 2;
                return $flag;
            }
        }
    }
    //check if this parcode already exists in db
    $query = '';
    if ($productId > 0) {
        $query = " and productId != $productId ";
    }
    $data = $productExt->isParcodeRepated($parcode, $query);
    //$data = $productDAO->queryByParcode($parcode);
    $flag2;
    if (count($data) > 0) {//> 1 as now i check for barcode after in
        $flag2 = 1;
    } else {
        $flag2 = 2;
    }

    $flagToreturn = 1;
    if ($flag == 2 || $flag2 == 2) {
        $flagToreturn = 2;
    }


    return $flagToreturn;
}

function generateParcode() {
    global $availableParcodeEX;
    $parcode = $availableParcodeEX->getAvailableParcodeValue();
    //check if this parcode already exists
    $data = checkbarcode($parcode);
    if ($data != 2) {
        $parcode = generateParcode();
    }
    return $parcode;
}

function removeParcodeFromTable($barcodeToRemove, $barcodeToAdd = '') {
    global $Programsettingdata;
    global $availableParcodeDAO;
    if ($Programsettingdata->usedParcode == 0) {

        if (!isset($Programsettingdata->parcodeDigits) || empty($Programsettingdata->parcodeDigits)) {
            $Programsettingdata->parcodeDigits = 5;
        }

        $biggestParcode = '';
        for ($i = 1; $i <= (int) $Programsettingdata->parcodeDigits; $i++) {
            $biggestParcode .= '9';
        }
        $biggestParcode = (int) $biggestParcode;


        if ($barcodeToRemove <= $biggestParcode) {
            $availableParcodeDAO->deleteByValue($barcodeToRemove);
            if (!empty($barcodeToAdd)) {
                $availableParcode = new stdClass();
                $availableParcode->value = $barcodeToAdd;
                $availableParcodeDAO->insert($availableParcode);
            }
        }
    }
}

function getStoredetailData($storeid, $productid) {
    global $myStoredetailEx;

    //select data from storerawmaterialdetails by storeid and rawmaterialid
    $storedetailData = $myStoredetailEx->queryWithStoreAndProduct($productid, $storeid);

    $storedetailId = $storedetailData->storedetailid;
    $productquantityBefore = $storedetailData->productquantity;

    return array($storedetailData, $storedetailId, $productquantityBefore);
}

//update and increase productquantity in storedetail tbl
function increaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount) {
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;

    //increase productquantity
    $productquantityAfter = $productquantityBefore + $productChangeAmount;
    $myStoredetail = $myStoredetailRecord->load($storedetailId);
    //update productquantity in storedetail tbl
    $myStoredetail->storedetailid = $storedetailId;
    $myStoredetail->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productquantityAfter;

    $myStoredetailEx->updateProductquantity($myStoredetail);

    onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, abs($productChangeAmount), 1);

    return $productquantityAfter;
}

//update and decrease Rawmaterialamount in storerawmaterialdetails tbl
function decreaseProductQuantity($storedetailId, $productquantityBefore, $productChangeAmount) {
    global $myStoredetail;
    global $myStoredetailRecord;
    global $myStoredetailEx;

    //increase productquantity
    $productquantityAfter = $productquantityBefore - $productChangeAmount;
    $myStoredetail = $myStoredetailRecord->load($storedetailId);
    //update productquantity in storedetail tbl
    $myStoredetail->storedetailid = $storedetailId;
    $myStoredetail->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productquantityAfter;

    $myStoredetailEx->updateProductquantity($myStoredetail);

    onlineTempStoreDetailFunc($myStoredetail->storeid, $myStoredetail->productid, 0, 0, (abs($productChangeAmount) * -1), 1);

    return $productquantityAfter;
}

//add in storerawmaterialdetails tbl
function insertStoredetail($storeid, $productid, $productChangeAmount) {
    global $myStoredetail;
    global $myStoredetailRecord;

    $myStoredetail->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $myStoredetail->storedetaildate = date("Y-m-d");
    $myStoredetail->productquantity = $productChangeAmount;
    $myStoredetail->storeid = $storeid;
    $myStoredetail->productid = $productid;

    $myStoredetailRecord->insert($myStoredetail);
}

//add in Storemovement tbl
function insertStorereport($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename) {
    global $myStorereport;
    global $myStorereportRecord;

    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = (float) $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = date("Y-m-d");
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
    $myStorereport->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;

    $id = $myStorereportRecord->insert($myStorereport);
    $myStorereport->storereportid = $id;
    onlineTempStoreReportFunc($myStorereport);
}

function moveProductFromStoreToAnother($productId, $transferproductAmount, $storeidfrom, $storeidto, $operationnum) {
    global $myStoremovementRecord;

    //add in storemovement tbl
    $myStoremovement->conditions = 0;
    $myStoremovement->storeidfrom = $storeidfrom;
    $myStoremovement->storeidto = $storeidto;
    $myStoremovement->transferproductdate = date("Y-m-d");
    $myStoremovement->userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 1;
    $myStoremovement->productid = $productId;
    $myStoremovement->transferproductamount = $transferproductAmount;
    $myStoremovement->operationnum = $operationnum;
    $myStoremovement->storetype = 0; //#تحويل بين المخازن

    if (isset($productId) && $productId != '-1') {
        //insert data in stormovement
        $transferproductId = $myStoremovementRecord->insert($myStoremovement);

        //////////////**Store From**///////////////////////////
        //get storefrom productquantity before change
        $storedetailFromData = getStoredetailData($storeidfrom, $productId);

        $allStoredetailFromData = $storedetailFromData[0];
        $storedetailFromId = $storedetailFromData[1];
        $productquantityFromBefore = $storedetailFromData[2];

        //update productquantity in storedetail
        $productquantityFromAfter = decreaseProductQuantity($storedetailFromId, $productquantityFromBefore, $transferproductAmount);


        //insert in storereport
        insertStorereport($productId, $storeidfrom, $transferproductAmount, $productquantityFromBefore, $productquantityFromAfter, 1, $transferproductId, "تحويل منتجات من المخزن", "storemovementController.php");



        //////////////**Store To**///////////////////////////
        //get storeto productquantity before change
        $storedetailToData = getStoredetailData($storeidto, $productId);

        $allStoredetailToData = $storedetailToData[0];
        $storedetailToId = $storedetailToData[1];
        $productquantityToBefore = $storedetailToData[2];

        if (count($allStoredetailToData) > 0) {

            //update productquantity in storedetail
            $productquantityToAfter = increaseProductQuantity($storedetailToId, $productquantityToBefore, $transferproductAmount);


            //insert in storereport
            insertStorereport($productId, $storeidto, $transferproductAmount, $productquantityToBefore, $productquantityToAfter, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php");
        } else {
            //insert in storedetail tbl
            insertStoredetail($storeidto, $productId, $transferproductAmount);


            //insert in storereport
            insertStorereport($productId, $storeidto, $transferproductAmount, 0, $transferproductAmount, 0, $transferproductId, "تحويل منتجات إلى المخزن", "storemovementController.php");
        }
    }
}

function getNextIdStoreMovement() {
    global $myStoremovementEx;
    $nextId = $myStoremovementEx->queryAlloperationnum();
    $last_val = $nextId[0];
    $last = $last_val->operationnum + 1;
    return $last;
}

function CURL_IT($data_arr, $url) {
    // set post fields
    $post = [
        'data_arr' => json_encode($data_arr), //encode it as it is array
    ];
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    //return $response;
}

function CURL_IT2($data_arr, $url) {
    // set post fields
    $post = [
        'data_arr' => json_encode($data_arr), //encode it as it is array
    ];
    $ch = curl_init($url);
    //
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
    //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
    //setting them to false.
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
    // execute!
    $response = curl_exec($ch);
    if ($response === false) {
        //echo 'Error : ' . curl_error($ch);
    }

    // close the connection, release resources used
    curl_close($ch);
    // do anything you want with your response
    //var_dump($response);
    return $response;
}

?>