<?php 
class ProductFactory{
	public $rows;
	public $purchase_price;
	public $sell_price;
	public $product_name;
	public $date;
	public $fileHandler;
	static private $_objectCount=0;
	
	public function __construct($rows,$date,FileHandler $fileHandler){
		$this->rows=$rows;
		$this->date;
		$this->fileHandler=$fileHandler;
	}
	
	public function createProducts(){
		foreach ($this->rows as $row){
			$data =substr($row[1],0,10);
			if($data=='Sprzedaz: '){
	
				$this->date=date("Y-m-d 00:00:01",strtotime(substr($row[1],9,12)));
			}
			if($row[1]=='Artykul')continue;
			if($row[2]=='Suma:')continue;
			if($row[1]!="" && $row[2]=="" && $row[3]=="" && $row[4]==""){
				continue;
			}
			if($row[1]!="" && $row[2]!="" && $row[3]!="" && $row[4]!=""){
				$this->product_name=$row[1];
				$this->purchase_price=$row[5];
				$this->sell_price=$row[6];
			}			
			$order = new Order();
			$order->setProductId($this->product_name);
			$order->setParentId($row[2]);
			$order->sell_quantity=$row[3];
			$order->buy_quantity=$row[4];
			$order->getPrice();
			$order->date=$this->date;
			$order->file_id=$this->fileHandler->file_id;
			$order->file_name=$this->fileHandler->orginal_file;
			$order->file_date=$this->fileHandler->file_date;
			$this->saveProduct($order);
			self::$_objectCount++;
		}
	}
	
	static public function getObjectCount()
	{
		return self::$_objectCount;
	}
	
	public function saveProduct($product){

		$fields=[];
		$values=[];
		$types=[];
		$type='s';
		$types="";
		foreach ($product as $key=>$value){
			$fields[]= $key;
			$values[]=$value;
			$types.=$type;
		}
		
		$this->insert($types,'orders',$fields,$values);
		
	}
	
	public function SqlArrayReferenceValues(&$rawArray){
		$refArray = array();
		foreach($rawArray as $key => $value)
		{
			$refArray[$key] = &$rawArray[$key];
		}
		return $refArray; 
	}
	
	public function insert($setType, $setTable, $setRow, $setValues) {
		
		$change = function($values) {
			return "?";
		};
		
		$row = join(",", $setRow);
		
		$done = join(",", array_map($change, $setValues));
		
		$insert = $GLOBALS['db']->database->prepare("INSERT INTO $setTable ($row) VALUES ($done)");
		
		$params = $setValues;
		
		$ww = array_merge(array($setType), $params);

		call_user_func_array(array($insert, "bind_param"), $this->SqlArrayReferenceValues($ww));
		
		
		$insert->execute();
		$insert->close();
		
		return $insert;
	}
}
?>