<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
	die ( 'Not A Valid Entry Point' );
/**
 * ***************************************************************************
 * The contents of this file are subject to the RECIPROCAL PUBLIC LICENSE
 * Version 1.1 ("License"); You may not use this file except in compliance
 * with the License.
 * You may obtain a copy of the License at
 * http://opensource.org/licenses/rpl.php. Software distributed under the
 * License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied.
 *
 * You may:
 * a) Use and distribute this code exactly as you received without payment or
 * a royalty or other fee.
 * b) Create extensions for this code, provided that you make the extensions
 * publicly available and document your modifications clearly.
 * c) Charge for a fee for warranty or support or for accepting liability
 * obligations for your customers.
 *
 * You may NOT:
 * a) Charge for the use of the original code or extensions, including in
 * electronic distribution models, such as ASP (Application Service
 * Provider).
 * b) Charge for the original source code or your extensions other than a
 * nominal fee to cover distribution costs where such distribution
 * involves PHYSICAL media.
 * c) Modify or delete any pre-existing copyright notices, change notices,
 * or License text in the Licensed Software
 * d) Assert any patent claims against the Licensor or Contributors, or
 * which would in any way restrict the ability of any third party to use the
 * Licensed Software.
 *
 * You must:
 * a) Document any modifications you make to this code including the nature of
 * the change, the authors of the change, and the date of the change.
 * b) Make the source code for any extensions you deploy available via an
 * Electronic Distribution Mechanism such as FTP or HTTP download.
 * c) Notify the licensor of the availability of source code to your extensions
 * and include instructions on how to acquire the source code and updates.
 * d) Grant Licensor a world-wide, non-exclusive, royalty-free license to use,
 * reproduce, perform, modify, sublicense, and distribute your extensions.
 *
 * The Original Code is: CommuniCore
 * Olavo Farias
 * 2006-04-7 olavo.farias@gmail.com
 *
 * The Initial Developer of the Original Code is CommuniCore.
 * Portions created by CommuniCore are Copyright (C) 2005 CommuniCore Ltda
 * All Rights Reserved.
 * ******************************************************************************
 */
require_once ('data/SugarBean.php');
require_once ('include/utils.php');
class EcmInventory extends SugarBean {
	var $field_name_map = array ();
	// STANDARD FIELDS
	var $id;
	var $date_entered;
	var $date_modified;
	var $modified_user_id;
	var $assigned_user_id;
	var $name;
	var $description;
	var $number;
	var $document_no;
	var $register_date;
	var $total;
	var $position_list;
	var $created_by;
	var $created_by_name;
	var $modified_by_name;
	var $assigned_user_name;
	var $ecmstockdoccorrects_name_minus;
	var $ecmstockdoccorrects_name_plus;
	var $stock_id;
	// SUBPANELS RELATED
	// MODULE OBJECT DETAILS
	var $module_dir = "EcmInventorys";
	var $table_name = "ecminventorys";
	var $object_name = "EcmInventory";
	// RELATED TABLE NAMES
	// USED TO RETRIEVE RELATED FIELDS FROM FORM POSTS.
	var $additional_column_fields = Array (
			'assigned_user_name',
			'assigned_user_id',
			'modified_user_id',
			'created_by' 
	);
	// RELATIONSHIP FIELDS
	var $relationship_fields = Array (
			'note_id' => 'notes',
		);
	function EcmInventory() {
		parent::SugarBean ();
		$this->setupCustomFields ( 'EcmInventorys' );
		foreach ( $this->field_defs as $field ) {
			$this->field_name_map [$field ['name']] = $field;
		}
	}
	
	var $new_schema = true;
	function get_summary_text() {
		return "$this->name";
	}

	function get_list_view_data() {
		$row_view = parent::get_list_view_data ();
		if( strlen($row_view['ECMSTOCKDOCCORRECTS_ID_MINUS']) > 0){
			$korekta_minus = new EcmStockDocCorrect();
			$korekta_minus->retrieve($row_view['ECMSTOCKDOCCORRECTS_ID_MINUS']);
			$korekta_minus_link = '<a href="index.php?module=EcmStockDocCorrects&action=DetailView&record=' . $korekta_minus->id . '">' . $korekta_minus->document_no .'</a>';
			unset($korekta_minus);
			$row_view['ECMSTOCKDOCCORRECTS_ID_MINUS'] = $korekta_minus_link;
		}
		if( strlen($row_view['ECMSTOCKDOCCORRECTS_ID_PLUS']) > 0){
			$korekta_plus = new EcmStockDocCorrect();
			$korekta_plus->retrieve($row_view['ECMSTOCKDOCCORRECTS_ID_PLUS']);
			$korekta_plus_link = '<a href="index.php?module=EcmStockDocCorrects&action=DetailView&record=' . $korekta_plus->id . '">' . $korekta_plus->document_no .'</a>';
			unset($korekta_plus);
			$row_view['ECMSTOCKDOCCORRECTS_ID_PLUS'] = $korekta_plus_link;
		}
		return $row_view;
	}
	 
	/**
	 * BUILDS A GENERIC SEARCH BASED ON THE QUERY STRING USING OR.
	 * DO NOT INCLUDE ANY $THIS-> BECAUSE THIS IS CALLED ON WITHOUT HAVING THE CLASS INSTANTIATED.
	 */

	function bean_implements($interface) {
		switch ($interface) {
			case 'ACL' :
				return true;
		}
		return false;
	}
	
	function retrieve($id = -1, $encode=true,$deleted=true){
		$EcmInventory = parent::retrieve ($id ,$encode,$deleted);
		$EcmInventory->position_list = $EcmInventory->getPositionList();
		if( strlen($EcmInventory->ecmstockdoccorrects_id_minus) > 0){
			$korekta_minus = new EcmStockDocCorrect();
			$korekta_minus->retrieve($EcmInventory->ecmstockdoccorrects_id_minus);
			$EcmInventory->ecmstockdoccorrects_name_minus =  $korekta_minus->document_no;
			unset($korekta_minus);
		}
		if( strlen($EcmInventory->ecmstockdoccorrects_id_plus) > 0){
			$korekta_plus = new EcmStockDocCorrect();
			$korekta_plus->retrieve($EcmInventory->ecmstockdoccorrects_id_plus);
			$EcmInventory->ecmstockdoccorrects_name_plus =  $korekta_plus->document_no;
			unset($korekta_plus);
		}
		//var_dump($EcmInventory);
		return $EcmInventory;
	}
	
	function save($check_notify = FALSE) {
		global $current_user,$app_list_strings;
		if($this->number == ''){
			$this->number = $this->generateNumber();
		}
		
		$return_id = parent::save ( $check_notify );
		$this->deleteAssignedPositions();
		//zapis pozycji
		foreach ($this->position_list as $value) {
			if ($value ['ecmproduct_id'] == '') {
				continue;
			}
			$item_id = create_guid();
			$arr = array (
					'id' => $item_id,
					'date_entered' => 'NOW()',
					'date_modified' => 'NOW()',
					'modified_user_id' => $current_user->id,
					'assigned_user_id' => $current_user->id,
					'created_by' => $current_user->id,
					'deleted' => '0',
					strtolower ( $this->object_name ) . '_id' => $return_id,
					'ecmproduct_id' => $value['ecmproduct_id'],
					'position' => $value,
					'code' => $value['code'],
					'name' => $value['name'],
					'price'=> $value['price'],
					'total'=> ROUND($value['price'] * $value['quantity'],2),
					'quantity' => $value['quantity'],
					'dd_unit_id' => $value['dd_unit_id'],
					'dd_unit_name' => $app_list_strings['ecmproducts_unit_dom'][$value['dd_unit_id']],
					'ecmproductcategory_id' => $value['ecmproductcategory_id'],
			);
			$keys = array_keys($arr);
			$values = array_values($arr);
			$inster_query = 'INSERT INTO ecminventoryitems (' . implode(",",$keys) .') VALUES ("' . implode('","',$values) . '");';
			$inster_query = str_replace ( '"NOW()"', 'NOW()', $inster_query );
			$this->db->query ($inster_query);
		}
		return $return_id;
	}

	function deleteAssignedPositions() {
		if (isset ( $this->id ) && $this->id != '') {
			$query = "DELETE FROM `" . strtolower ( $this->object_name ) . "items` WHERE `" . strtolower ( $this->object_name ) . "_id`='" . $this->id . "'";
			$r = $this->db->query ( $query );
			if ($r)
				return true;
		}
		return false;
	}

	function generateNumber() {
		$date = $this->register_date;
		$db = $GLOBALS['db'];
		$r = $db->fetchByAssoc($db->query("SELECT count(id) as c FROM ecminventorys WHERE deleted='0' AND YEAR(register_date)='".date('Y',strtotime($date)) ."'"));

	    if (!$r || !$r['c'] || $r['c']=='')
	    	$count = 0;
	    else
	    	$count = intval($r['c']);
	    
	    $count++;
	    
	    //has 5 digits?
	    $tmp = strval($count);
	    while (strlen($tmp) < 5)
	    	$tmp = '0'.$tmp;
	    
	   return date('Ymd',strtotime($date)). $tmp;
	}
	
	function getPositionList(){
		global $app_list_strings;
		$db = $GLOBALS ['db'];
		$q = 'SELECT * FROM ecminventoryitems WHERE ecminventory_id ="' . $this->id . '";';
		$rs = $db->query($q);
		$id_array = array();
		while ($row = $db->fetchByAssoc($rs)) {
			$row['stock_state'] = EcmStockOperation::getStock($row['ecmproduct_id'] , $this->stock_id);
			$row['stock_state_quantity_difference'] = $row['quantity']-$row['stock_state'];
			$row['dd_unit_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$row ['dd_unit_id']];
			
			if($row['stock_state_quantity_difference'] < 0){
				//specjalna tabelka dla pobrania przewidywanej ceny
				$tmp = array(
					'ecmproduct_id' => $row['ecmproduct_id'],
					'quantity' =>  abs($row['stock_state_quantity_difference']),
				);
				$tabelka_z_cenami = $this->getPriceInfo($tmp);
				//$ilosc = 0;
				$wartosc = 0;
				foreach($tabelka_z_cenami as $cenka){
					//$ilosc += $cenka['qty'];
					$wartosc += $cenka['qty'] * $cenka['price'];
				}
				$row['projected_price'] = $wartosc*-1;
			}else{
				$row['projected_price'] = $row['stock_state_quantity_difference'] * $row['price'];
			}
			$id_array[] = $row;
		}
		
		return $id_array;
	}
	
	function getPriceInfo($p){
        $arr = array();
		// pobiera ilosci magazynowe danego produktu wraz z cena i id operacji magazynowej
		
        $w   = $GLOBALS['db']->query("select quantity as qty,id,price from ecmstockoperations where deleted='0' and type='0' and in_id IS NULL and stock_id='" . $this->stock_id . "' and product_id='" . $p['ecmproduct_id'] . "' and used='0' ORDER BY counter ASC");
		//echo "select quantity as qty,id,price from ecmstockoperations where deleted='0' and type='0' and in_id IS NULL and stock_id='" . $this->stock_id . "' and product_id='" . $p['ecmproduct_id'] . "' and used='0'  ORDER BY counter ASC<br><br>";
		while ($rrr = $GLOBALS['db']->fetchByAssoc($w)) {

            $ww   = $GLOBALS['db']->query("select quantity from ecmstockoperations where in_id='" . $rrr['id'] . "' and type='1' and in_id IS NOT NULL and stock_id='" . $this->stock_id . "' and product_id='" . $p['ecmproduct_id'] . "' and deleted='0' ORDER BY counter ASC");
            $rqty = 0;
            while ($rrp = $GLOBALS['db']->fetchByAssoc($ww)) {
                $rqty += $rrp['quantity'];
            }
            $qty = $rrr['qty'] - $rqty;
            if ($qty > 0) {
                $arr[] = array(
                    "qty" => $qty,
                    "id" => $rrr['id'],
                    "price" => $rrr['price']
                );
            }
        }
		
        $rr       = array();
        $used_qty = 0;
        $stop     = 0;
        foreach ($arr as $value) {
            if ($p['quantity'] - $used_qty <= $value['qty']) {
                $rr[] = array(
                    "id" => $value['id'],
                    "qty" => $p['quantity'] - $used_qty,
                    "price" => $value['price']
                );
                $stop = 1;
            } else {
                $rr[] = array(
                    "id" => $value['id'],
                    "qty" => $value['qty'],
                    "price" => $value['price']
                );
                $used_qty += $value['qty'];
            }
            if ($stop) {
                $stop = 0;
                break;
            }
        }
        $avg_pq = 0;
        $avg_q  = 0;
		return $rr;
	}
	
	
	function create_ks_documents($ks_date_document){
		global $current_user;
		$produkty_minus = Array();
		$produkty_plus = Array();
		$total_minus = 0;
		$total_plus = 0;
		//Dzielimy produkty na minus i plus
		$minus_pozycja = 0;
		$plus_pozycja = 0;
		
		// Sprawdzamy date podana czy moze byc;
		$db=$GLOBALS['db'];
		$uq=$db->query("SELECT MAX(register_date) AS date FROM ecmstockdoccorrects WHERE stock_id='".$this->stock_id."' and deleted=0");
		$rul = $db->fetchByAssoc($uq);
		
		$datetime2 = new DateTime($ks_date_document);
		$datetime1 = new DateTime($rul['date']);
		$interval = $datetime1->diff($datetime2);
		
		if($interval->format('%R%a') >= 0){
		
		}else{
			return -2;
		}
		
		$states=array();
		foreach($this->position_list as $key => $pozycja){
			if( $pozycja['stock_state_quantity_difference'] < 0){
				$pozycja['quantity'] = $pozycja['stock_state_quantity_difference'];
				$pozycja['product_id'] = $pozycja['ecmproduct_id'];
				$pozycja['unit_id'] = $pozycja['dd_unit_id'];
				$pozycja['unit_name'] = $pozycja['dd_unit_name'];
				$pozycja['product_code'] = $pozycja['code'];
				$pozycja['position'] = $minus_pozycja;
				$produkty_minus[] = $pozycja;
				$total_minus +=  $pozycja['stock_state_quantity_difference'] * $pozycja['price'];
				$minus_pozycja++;
				
			} else if( $pozycja['stock_state_quantity_difference'] > 0){
				$pozycja['quantity'] = $pozycja['stock_state_quantity_difference'];
				$pozycja['product_id'] = $pozycja['ecmproduct_id'];
				$pozycja['unit_id'] = $pozycja['dd_unit_id'];
				$pozycja['unit_name'] = $pozycja['dd_unit_name'];
				$pozycja['product_code'] = $pozycja['code'];
				$pozycja['position'] = $plus_pozycja;
				$produkty_plus[] = $pozycja;
				$total_plus +=  $pozycja['stock_state_quantity_difference'] * $pozycja['price'];
				$plus_pozycja++;
			} 
			$states[$pozycja['ecmproduct_id']]['stock_state']=$pozycja['stock_state'];
		}
		
		//Korekta Minus
		//Sprawdzamy czy sa produkty na minus
		$minusik = false;
		if(count($produkty_minus)>0){
			$EcmStockDocCorrectMinus = new EcmStockDocCorrect();
			$EcmStockDocCorrectMinus->type = '7bb903d0-c296-7d1b-6e50-54c209e30850';
			$EcmStockDocCorrectMinus->pdf_text = 'Do dokumentu remanentu nr: ' . $this->document_no . ' z dnia ' . $this->register_date;
			$EcmStockDocCorrectMinus->name = 'Korekta minus do dokumentu remanetntu: ' . $this->document_no;
			$EcmStockDocCorrectMinus->created_by = $current_user->id;
			$EcmStockDocCorrectMinus->assigned_user_id = $current_user->id;
			$EcmStockDocCorrectMinus->modified_user_id = $current_user->id;
			$EcmStockDocCorrectMinus->register_date = $ks_date_document;
			$EcmStockDocCorrectMinus->stock_id = $this->stock_id;
			$EcmStockDocCorrectMinus->total = $total_minus;
			$EcmStockDocCorrectMinus->description = "Renament_".$this->document_no;
			$EcmStockDocCorrectMinus->position_list = $produkty_minus;
			$this->ecmstockdoccorrects_id_minus =  $EcmStockDocCorrectMinus->save();
			$minusik = true;
		}
		
		
		//Korekta Plus
		//Sprawdzamy czy jest korekta na plus
		$plusik = false;
		if(count($produkty_plus)>0){
			$EcmStockDocCorrectPlus = new EcmStockDocCorrect();
			$EcmStockDocCorrectPlus->type = '8a6b804b-fac7-5cc2-de19-54c209116b19';
			$EcmStockDocCorrectPlus->pdf_text = 'Do dokumentu remanentu nr: ' . $this->document_no . ' z dnia ' . $this->register_date;
			$EcmStockDocCorrectPlus->name = 'Korekta plus do dokumentu remanetntu: ' . $this->document_no;
			$EcmStockDocCorrectPlus->created_by = $current_user->id;
			$EcmStockDocCorrectPlus->assigned_user_id = $current_user->id;
			$EcmStockDocCorrectPlus->modified_user_id = $current_user->id;
			$EcmStockDocCorrectPlus->register_date = $ks_date_document;
			$EcmStockDocCorrectPlus->stock_id = $this->stock_id;
			$EcmStockDocCorrectPlus->total = $total_plus;
			$EcmStockDocCorrectPlus->description = "Renament_".$this->document_no;
			$EcmStockDocCorrectPlus->position_list = $produkty_plus;
			$this->ecmstockdoccorrects_id_plus = $EcmStockDocCorrectPlus->save();
			$plusik = true;
		}
		if($minusik || $plusik){
			
			$this->status = 'implemented';
			$this->save();
			$this->position_list=$this->getPositionList();
			foreach($this->position_list as $key => $pozycja){
	
				$this->db->query("update ecminventoryitems set stock_state='".$states[$pozycja['ecmproduct_id']]['stock_state']."' where id='".$pozycja['id']."'");
			}
			
			return 1;
		}else{
			return -1;
		}
		
	}
}
?>