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

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

try 
{
        // Get Items List from SAP        
        $Items = $sap->getService("view.svc/B1_ItemsB1SLQuery");
        $Items_result = $Items->queryBuilder()
        ->select('ItemCode, ItemName, ItmsGrpCod, ItmsGrpNam, U_WP, UserText')
        ->findAll();

        $Items = array_values(((array) $Items_result)["value"]);

        //print_r($Items)."<br>";

        foreach ($Items as $Item) {

            $ItemCode =  array_values((array) $Item) [0];

            // Get Items List from SAP        
            $ItemsPrices = $sap->getService("view.svc/B1_ItemsPricesB1SLQuery");
            $ItemsPrices_result = $ItemsPrices->queryBuilder()
            ->select('Price')
            ->where(new Equal("ItemCode", $ItemCode))
            ->where(new Equal("PriceList", $PriceList))
            ->findAll();
            
            $ItemsPrices = array_values(((array) $ItemsPrices_result)["value"]);
           
            $ItemName =  array_values((array) $Item) [1];
            $ItemsGroupCode =  array_values((array) $Item) [2];
            $ItemsGroupName = array_values((array) $Item) [3];
            $U_WP =  array_values((array) $Item) [4];
            $UserText =  array_values((array) $Item) [5];
            $regular_price =  strval(((array)array_values((array) $ItemsPrices) [0])['Price']);

            $BatchDetails = $sap->getService("view.svc/B1_ItemsBatchB1SLQuery");

            $Batch_result = $BatchDetails->queryBuilder()
            ->select('ItemCode, BatchNum, U_couleur, U_Taille, Quantity')
            ->where(new Equal("ItemCode", $ItemCode))
            ->where(new Equal("WhsCode", $Magasin))
            ->findAll();

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

            $Attribute1List = array ();
            $Attribute2List = array ();
            $BatchNums = array ();

            foreach ($Batches as $Batch) {
                
                $BatchNum =  array_values((array) $Batch) [1];
                $Attribute1 =  array_values((array) $Batch) [2];
                $Attribute2 =  array_values((array) $Batch) [3];
                $Quantity =  array_values((array) $Batch) [4];

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

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

            echo "ItemCode: ".$ItemCode;
            echo " ItemName: ".$ItemName;
            echo " UserText: ".$UserText;
            echo " ItemsGroupCode: ".$ItemsGroupCode;
            echo " ItemsGroupName: ".$ItemsGroupName;
            echo " U_WP: ".$U_WP;
            echo " regular_price: ".$regular_price;
            echo "<br>";

            //Insert / Update Categories in Wordpress            
            $query = [ 'slug' => "'".$ItemsGroupCode."'"];
            $Categorie_result = $woocommerce->get("products/categories",$query);

            $id_categorie = "";
            if( count((array) $Categorie_result) == 0 ) {
                $id_categorie = CreateCategorie($ItemsGroupCode,$ItemsGroupName,$woocommerce);

            } else if ( count((array) $Categorie_result) == 1 ) {
                $id_categorie  = ((array)((array) $Categorie_result)[0])["id"];
                $name_categorie  = ((array)((array) $Categorie_result)[0])["name"];

                if($name_categorie <> $ItemsGroupName) {
                    UpdateCategorie($id_categorie,$ItemsGroupName,$woocommerce);
                }               
            }
        
            //Insert / Update Products (with attributes)
            $query = [ 'slug' => "'".$ItemCode."'"];
            $Items_result = $woocommerce->get("products",$query);
 
            $name = $ItemName ;
            $description = $UserText ;
            $categorie = $id_categorie ;

            $id_product = "";
            if( count((array) $Items_result) == 0 ) {  

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

                $id_product = CreateArticle($name,$ItemCode,$regular_price,$description,$categorie,$Itemattributes,$woocommerce);

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

                $id_product  = ((array)((array) $Items_result)[0])["id"];
                echo " Regular_price: ".$regular_price."<br>";
                UpdateArticle($id_product,$name,$regular_price,$description,$categorie,$woocommerce);
            }

            //Insert / Update Variations (with stock)
            //localhost:8080/brakett/wp-json/wc/v3/products/31/variations            
            $variations_result = $woocommerce->get("products/".$id_product."/variations");
         
            //print_r($variations_result);
            //$var_result = $woocommerce->get("products/".$id_product."/variations?sku=A0000020007");
            //print_r($var_result);

            foreach ((array) $variations_result as $valeur) {

                $id_variation  = ((array)$valeur)["id"];
                $sku_variation  = ((array)$valeur)["sku"];
                echo "<br>";
                echo "id_variation ".$id_variation. " sku ".$sku_variation." id_product: ".$id_product."<br>";

                if(in_array($sku_variation, $BatchNums)) {
                    //Update
                    $key = array_search($sku_variation, array_column($batchList, 0));
                    echo "Update: ".$id_variation." key: ".$key."<br>";
                    print_r($batchList[$key])."<br>";
                    UpdateVariation($id_product,$id_variation,$regular_price,$batchList[$key],$woocommerce);

                    //Remove from $batchlist
                    $batchList = searchForId($sku_variation,$batchList);
                    print_r($batchList)."<br>";

                } else {
                    //Delete
                    echo "Delete: ".$id_variation."<br>";
                    DeleteVariation($id_product,$id_variation,$woocommerce);
                }

            }

            if(count($batchList) > 0 ) {
                echo "Create Variation "."<br>";
                print_r($batchList)."<br>";
                CreateVariation($id_product,$regular_price,$batchList,$woocommerce);
            }


            

    }

 


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