<?php
require_once "../../vendor/autoload.php";
include "..\login.php";
include  "../RESTAPI2.php";
include  "../functionsDetailed.php";

use SAPb1\Filters\Equal;
use SAPb1\Filters\InArray;

try 
{
        $ItemsMAJ = $sap->getService("view.svc/B1_ItemsMAJB1SLQuery");
        $ItemsMAJ_result = $ItemsMAJ->queryBuilder()
        ->select('Type,ItemCode,LogInstanc')
        ->findAll();

        $ItemsLog = array_values(((array) $ItemsMAJ_result)["value"]);        
        $WpLog = $sap->getService('U_WPLOG');

        foreach ($ItemsLog as $Log) {

            $Type =  array_values((array) $Log)[0];
            $ItemCode =  array_values((array) $Log)[1];
            $LogInstanc =  array_values((array) $Log)[2];
            $LogMessage = "";
            $Code_result = $sap->getService("U_WPLOG")->queryBuilder()->select('Code,U_ItemLog,U_PriceLog,U_ItemGroupLog,U_ItemError,U_PriceError,U_ItemGroupError')->where(new Equal("U_ItemCode", $ItemCode))->findAll();
            $Codes = array_values(((array) $Code_result)["value"]);
            $Code = 0;

            if(count((array) $Codes) == 0 ) {

                $result = $WpLog->create([
                    'Name' => $ItemCode,
                    'U_ItemCode' => $ItemCode
                ]);

                $Code =  ((array) $result)["Code"];
            }
            else $Code =  array_values((array) $Codes[0])[0];

            

            $date = date('d/m/Y h:i:s');
            echo "[Date] ".$date."<br>";
            echo "Type: ".$Type."<br>";
            echo "ItemCode: ".$ItemCode."<br>";

            // Get Items List from SAP        
            $Items_result = $sap->getService("view.svc/B1_ItemsB1SLQuery")->queryBuilder()->select('ItemCode, ItemName, ItmsGrpCod, ItmsGrpNam')->where(new Equal("ItemCode", $ItemCode))->findAll();
            $Items = array_values(((array) $Items_result)["value"]);
            $ItemName =  array_values((array) $Items[0]) [1];
            $ItemsGroupCode =  array_values((array) $Items[0]) [2];
            $ItemsGroupName = array_values((array) $Items[0]) [3];

            $Categorie_result = $woocommerce->get("products/categories", [ 'slug' => "'".$ItemsGroupCode."'"]);
            if(count((array) $Categorie_result) == 1 ) {
                 
                $Categories = array_values((array)((array) $Categorie_result)["0"]);
                $id_categorie =  array_values((array) $Categories[0]) [0];

            } 

            if($Type  == "Categorie") {

                  //Insert or Update Categorie

                if(count((array) $Categorie_result) == 0 ) { 

                    $result = CreateCategorie($ItemsGroupCode,$ItemsGroupName,$woocommerce);
                    if(gettype($result) == "string" && strpos($result, "Error") == false) {
                        $LogMessage = $result;
                    }

                } else if ( count((array) $Categorie_result) == 1 ) {

                    $name_categorie  = ((array)((array) $Categorie_result)[0])["name"];                    
                    if($name_categorie <> $ItemsGroupName) { 

                        $result = UpdateCategorie($id_categorie,$ItemsGroupName,$woocommerce);
                        if(gettype($result) == "string" && strpos($result, "Error") == false) {
                            $LogMessage = $result;
                        }
                    }
                }

                if($LogMessage <> "")
                    $WpLog->update($Code, ['U_ItemGroupError' => $LogMessage." (".$date.")"]); 
                else 
                    $WpLog->update($Code, ['U_ItemGroupLog'  => $LogInstanc, 'U_ItemGroupError' => ""]);                
            }

            if($Type  == "Articles") { 

                //GET Item Object (Woocommerce)
                $Items_result = $woocommerce->get("products",[ 'slug' => "'".$ItemCode."'"]);                

                if( count((array) $Items_result) == 0 ) {

                    $result = CreateArticle($ItemName,$ItemCode,$id_categorie,$woocommerce);
                    if(gettype($result) == "string" && strpos($result, "Error") == false) {
                        $LogMessage = $result;
                    }

                } else if ( count((array) $Items_result) == 1 ) {

                    $Products = array_values((array)((array) $Items_result)["0"]);
                    $id_product = array_values((array) $Products[0]) [0];

                    $id_product  = ((array)((array) $Items_result)[0])["id"];
                    $result = UpdateArticle($id_product,$ItemName,$id_categorie,$woocommerce);

                    if(gettype($result) == "string" && strpos($result, "Error") == false) {
                        $LogMessage = $result;
                    }
                }

                if($LogMessage <> "")
                    $result = $WpLog->update($Code, ['U_ItemError' => $LogMessage." (".$date.")"]); 
                else 
                    $result = $WpLog->update($Code, ['U_ItemLog'  => $LogInstanc, 'U_ItemError' => ""]);            
            }

            if($Type  == "PriceList") {

                //GET Item Object (Woocommerce)
                $Items_result = $woocommerce->get("products",[ 'slug' => "'".$ItemCode."'"]);
                $Products = array_values((array)((array) $Items_result)["0"]);
                $id_product = array_values((array) $Products[0]) [0];

                // Get Item Price List from SAP        
                $ItemsPrices_result = $sap->getService("view.svc/B1_ItemsPricesB1SLQuery")->queryBuilder()->select('Price')->where(new Equal("ItemCode", $ItemCode))->findAll();
                $ItemsPrices = array_values(((array) $ItemsPrices_result)["value"]);
                $Price =  array_values((array) $ItemsPrices[0]) [0];
                $Product_variations_result = $woocommerce->get("products/".$id_product."/variations");
                $Prices = [];

                foreach ($Product_variations_result as $ProdVarLog) {
                    array_push($Prices,[ 'id' => ((array)$ProdVarLog)['id'], 'regular_price' => $Price  ]);
                }

                //Insert / Update Prices
                if( count((array) $Product_variations_result) > 0 ) {
                    $result = UpdateVariationPrice($id_product,$Prices,$woocommerce);
                    if(gettype($result) == "string" && strpos($result, "Error") == false) {
                        $LogMessage = $result;
                    }
                }

                //Update WPLOG UDT
                if($LogMessage <> "")
                    $result = $WpLog->update($Code, ['U_PriceError' => $LogMessage." (".$date.")"]); 
                else 
                    $result = $WpLog->update($Code, ['U_PriceLog'  => $LogInstanc, 'U_PriceError' => ""]); 

            }

            echo "<br>";
            echo "---------------------------------------------------------------------------------------------------------------------------------------------------------------------------";
            echo "<br>";
        }

        // Items batch MAJ
       $WPBatchLog = $sap->getService("view.svc/B1_ItemsBatchMAJB1SLQuery");
        $WPBatchLog_result = $WPBatchLog->queryBuilder()
        ->select('Type,ItemCode,DistNumber,LogInstance_Quantity')
        ->findAll();

        $ItemsLBatchLog = array_values(((array) $WPBatchLog_result)["value"]);

        foreach ($ItemsLBatchLog as $Log) {

            $Type =  array_values((array) $Log)[0];
            $ItemCode =  array_values((array) $Log)[1];
            $DistNumber =  array_values((array) $Log)[2];
            $LogInstanc =  array_values((array) $Log)[3];
            $LogMessage = "";
            $WpLinesLog = $sap->getService('U_WPLOGLINES');

            $CodeBatch_result = $sap->getService("U_WPLOGLINES")->queryBuilder()
            ->select('Code,U_BatchLog,U_QtyLog,U_BatchError,U_QtyError')
            ->where(new Equal("U_ItemCode", $ItemCode))
            ->where(new Equal("U_BatchNum", $DistNumber))
            ->findAll();

            $BatchCodes = array_values(((array) $CodeBatch_result)["value"]);
            $BatchCode = 0;

            if(count((array) $BatchCodes) == 0 ) {

                $result = $WpLinesLog->create([
                    'Name' => $ItemCode,
                    'U_ItemCode' => $ItemCode,
                    'U_BatchNum' => $DistNumber
                ]);

                $BatchCode =  ((array) $result)["Code"];

            }
            else $BatchCode =  array_values((array) $BatchCodes[0])[0];

            $date = date('d/m/y h:i:s');
            echo "[Date] ".$date."<br>";
            echo " Batch MAJ Type: ".$Type."<br>";
            echo "ItemCode: ".$ItemCode."<br>";
            echo "DistNumber: ".$DistNumber."<br>";
            echo "LogInstanc: ".$LogInstanc."<br>";
            echo "U_WPLOGLINES Code: ".$BatchCode."<br>";

            //GET Item Object (Woocommerce)
            $Items_result = $woocommerce->get("products",[ 'slug' => "'".$ItemCode."'"]);

            if(count((array) $Items_result) ) {
            
            $Products = array_values((array)((array) $Items_result)["0"]);
            $id_product = array_values((array) $Products[0])[0];

            if($Type  == "Lots") {

                $BatchDetails = $sap->getService("view.svc/B1_ItemsBatchB1SLQuery");
                $Batch_result = $BatchDetails->queryBuilder()
                ->select('ItemCode, BatchNum, Attribute1, Attribute2,Prix,Quantity')
                ->where(new Equal("ItemCode", $ItemCode))
                ->where(new Equal("BatchNum", $DistNumber))
                ->findAll();

                $Batch = array_values(((array) $Batch_result)["value"]);

                $batchList = array ();
                $BatchNum =  array_values((array)((array) $Batch)[0])[1];
                $Attribute1 =  ucfirst(strtolower(array_values((array)((array) $Batch)[0])[2]));
                $Attribute2 =  ucfirst(strtolower(array_values((array)((array) $Batch)[0])[3]));
                $Prix =  ucfirst(strtolower(array_values((array)((array) $Batch)[0])[4]));
                $Quantity =  ucfirst(strtolower(array_values((array)((array) $Batch)[0])[5]));

                $Attribute1List = array ();
                $Attribute2List = array ();
                $ProductAtts_result = $woocommerce->get("products/".$id_product."");
                $Product_Attributes  = ((array)((array)$ProductAtts_result)["attributes"]);
                $updateAttributes = false;

                foreach ($Product_Attributes as $Attribute) {

                    $id = ((array)$Attribute)["id"];
                    $options = ((array)$Attribute)["options"];


                    if($id == 1) {
                        $Result = array_search($Attribute1, $options);
                        $Attribute1List = $options;

                        if($Result === false) {
                            array_push($Attribute1List,$Attribute1);
                            $updateAttributes = true;
                        }
                    }

                    if($id == 2 ) {
                        $Result = array_search($Attribute2, $options);
                        $Attribute2List = $options;

                        if($Result === false) {
                            array_push($Attribute2List,$Attribute2);
                            $updateAttributes = true;
                        }
                    }

                }


                if ($updateAttributes == true) {

                    $Itemattributes = [
                        [ 'id'   =>  $global_attribute1_id, 'visible'   => true, 'variation' => true, 'options'   => $Attribute1List],
                        [ 'id'   =>  $global_attribute2_id, 'visible'   => true, 'variation' => true, 'options'   => $Attribute2List] ];
    
                    $result =  UpdateArticleAttributes($id_product,$Prix,$Quantity,$Itemattributes,$woocommerce);
                    if(gettype($result) == "string" && strpos($result, "Error") == false) {
                        $LogMessage = $result;
                    }

                } else {

                    array_push($Attribute1List,$Attribute1);
                    array_push($Attribute2List,$Attribute2);

                    $Itemattributes = [
                        [ 'id'   =>  $global_attribute1_id, 'visible'   => true, 'variation' => true, 'options'   => $Attribute1List],
                        [ 'id'   =>  $global_attribute2_id, 'visible'   => true, 'variation' => true, 'options'   => $Attribute2List] ];

                    $result =  CreateArticleAttributes($id_product,$Prix,$Quantity,$Itemattributes,$woocommerce);
                    if(gettype($result) == "string" && strpos($result, "Error") == false) {
                        $LogMessage = $result;
                    }
                }

                array_push($batchList, [ 'id' => $global_attribute1_id, 'option' => $Attribute1 ],[ 'id' => $global_attribute2_id, 'option' => $Attribute2 ] );

                $variations_result = $woocommerce->get("products/".$id_product."/variations", ['sku' => $DistNumber]);

                //print_r($variations_result);
                //Insert / Update Products (with attributes)   
                if( count((array) $variations_result) == 0 && $Attribute1 <> "" && $Attribute2 <> "") {
                   
                    $result =   CreateVariation($id_product,$Prix,$Quantity,$BatchNum,$batchList,$woocommerce);
                    if(gettype($result) == "string" && strpos($result, "Error") == false) {
                        $LogMessage = $result;
                    }

                } else if ( count((array) $variations_result) == 1 ) {

                    $id_variation  = ((array)((array)$variations_result)[0])["id"];
                     
                    if($Attribute1 == "" || $Attribute2 == "") {
                    
                        $result =   DeleteVariation($id_product,$id_variation,$woocommerce);
                        if(gettype($result) == "string" && strpos($result, "Error") == false) {
                            $LogMessage = $result;
                        }
    
                    } else {

                        $result =   UpdateVariation($id_product,$Prix,$Quantity,$id_variation,$BatchNum,$batchList,$woocommerce);
                        if(gettype($result) == "string" && strpos($result, "Error") == false) {
                            $LogMessage = $result;
                        }

                    }
                }
                
                if($Attribute1 == "" && $Attribute2 == "") {
                    $LogMessage = "Les attributs de lot manquants";
                }

                if($LogMessage <> "")
                    $WpLinesLog->update($BatchCode,['U_BatchError' => $LogMessage." (".$date.")"]); 
                else 
                    $WpLinesLog->update($BatchCode,['U_BatchLog'  => $LogInstanc, 'U_BatchError' => ""]);      
            
            }
        
            if($Type  == "Qte") {

                $variations_result = $woocommerce->get("products/".$id_product."/variations", ['sku' => $DistNumber]);

                if ( count((array) $variations_result) == 1 ) {

                    $id_variation  = ((array)((array)$variations_result)[0])["id"];

                    $result =   UpdateVariationQuantity($id_product,$id_variation,$LogInstanc,$woocommerce);
                    
                    if(gettype($result) == "string" && strpos($result, "Error") == false) {
                        $LogMessage = $result;
                    }

                }

                if($LogMessage <> "")
                    $WpLinesLog->update($BatchCode,['U_QtyError' => $LogMessage." (".$date.")"]); 
                else 
                    $WpLinesLog->update($BatchCode,['U_QtyLog'  => $LogInstanc, 'U_QtyError' => ""]);     
            }

        }

        echo "<br>";
        echo "---------------------------------------------------------------------------------------------------------------------------------------------------------------------------";
        echo "<br>";

    }

 

 


} catch (Exception $e) {
    echo $e->getMessage();    
}