<?php
trait ProductSync
{
    private $productJSON;
    private $productPriceJSON;
    private $productExtrafieldsJSON;

    /**
	 * Product syncronisation
	 * 
	 * @return array|mixed|string Data without useless information
	 * 
	 * @url POST Sync
	 */
    public function Sync()
    {
        $this->BBUSProductJSON();
        $this->curlRunner('bbus/syncproduct', '', 'POST', true);
        //$this->BBUSProductPriceJSON();
        //$this->BBUSProductExtrafieldsJSON();
        //print_r($this->productJSON);
        exit;
        return 'OK';
    }

    private function BBUSProductJSON(): void {
        $sql = "SELECT * FROM llx_product WHERE rowid > 5000";
        $this->productJSON = $this->CreateJSON($sql);
    }

    private function BBUSProductPriceJSON(): void {
        $sql = "SELECT * FROM llx_product_price WHERE fk_object > 5000";
        $this->productPriceJSON = $this->CreateJSON($sql);
    }
    
    private function BBUSProductExtrafieldsJSON(): void {
        $sql = "SELECT * FROM llx_product_extrafields WHERE fk_object > 5000";
        $this->productExtrafieldsJSON = $this->CreateJSON($sql);
    }

    private function CreateJSON($sql): string
    {
        global $db;
        $array = [];
        $JSON = '';
        $result = $db->query($sql);
        if ($db->num_rows($result) > 0) {
            while ($row = $db->fetch_object($result)) {
                $array[] = $row;
            }
            $JSON = json_encode($array);
        }
        return $JSON;
    }

    private function decodeJSON($JSON):array{
        if($JSON !== ''){
            return json_decode($JSON);
        }
        return [];
    } 

    /**
	 * syncproduct
	 *
	 * @param  int $product_id			Product rowid
	 *
	 * @return array|mixed Data without useless information
	 *
	 * @url POST syncproduct
	 *
	 * @throws RestException 401
	 * @throws RestException 403
	 * @throws RestException 404
	 */
	public function syncproduct($JSON)
	{
		$products = $this->decodeJSON($JSON);
        print_r($products);
	}
}
