<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
	die ( 'Not A Valid Entry Point' );
/**
 * *******************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc.
 * Copyright (C) 2004 - 2007 SugarCRM Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 * ******************************************************************************
 */
/**
 * *******************************************************************************
 *
 * Description: TODO: To be written.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 * ******************************************************************************
 */

require_once ('data/SugarBean.php');
require_once ('include/utils.php');
class EcmStockState extends SugarBean {
	var $field_name_map = array ();
	var $id;
	var $date_entered;
	var $date_modified;
	var $modified_user_id;
	var $assigned_user_id;
	var $name;
	var $stock_name;
	var $stock_id;
	var $product_code;
	var $product_name;
	var $product_id;
	var $quantity;
	// var $part_id;
	var $module_dir = 'EcmStockStates';
	var $table_name = "ecmstockstates";
	var $object_name = "EcmStockState";
	var $new_schema = true;
	var $additional_column_fields = array (
			'assigned_user_name',
			'assigned_user_id' 
	);
	function EcmStockState() {
		parent::SugarBean ();
		$this->setupCustomFields ( 'EcmStockStates' );
		foreach ( $this->field_defs as $field ) {
			$this->field_name_map [$field ['name']] = $field;
		}
	}
	function get_summary_text() {
		return $this->name;
	}
	function create_list_query($order_by, $where, $show_deleted = 0) {
		$custom_join = $this->custom_fields->getJOIN ();
		$query = "SELECT ";
		$query .= "ecmstockstates.*,users.user_name as assigned_user_name";
		if ($custom_join)
			$query .= $custom_join ['select'];
		$query .= " FROM ecmstockstates ";
		$query .= "LEFT JOIN users ON ecmstockstates.assigned_user_id=users.id";
		$query .= "  ";
		if ($custom_join)
			$query .= $custom_join ['join'];
		$where_auto = '1=1';
		if ($show_deleted == 0)
			$where_auto = " $this->table_name.deleted=0 ";
		elseif ($show_deleted == 1)
			$where_auto = " $this->table_name.deleted=1 ";
		if ($where != "")
			$query .= "where $where AND " . $where_auto;
		else
			$query .= "where " . $where_auto;
		if (substr_count ( $order_by, '.' ) > 0)
			$query .= " ORDER BY $order_by";
		elseif ($order_by != "")
			$query .= " ORDER BY $order_by";
		else
			$query .= " ORDER BY ecmstockstates.name";
		return $query;
	}
	function create_export_query($order_by, $where) {
		$custom_join = $this->custom_fields->getJOIN ();
		$query = "SELECT ";
		$query .= "ecmstockstates.*,users.user_name as assigned_user_name";
		if ($custom_join)
			$query .= $custom_join ['select'];
		$query .= " FROM ecmstockstates ";
		$query .= "LEFT JOIN users ON ecmstockstates.assigned_user_id=users.id";
		$query .= "  ";
		if ($custom_join)
			$query .= $custom_join ['join'];
		$where_auto = '1=1';
		if ($show_deleted == 0)
			$where_auto = " $this->table_name.deleted=0 ";
		elseif ($show_deleted == 1)
			$where_auto = " $this->table_name.deleted=1 ";
		if ($where != "")
			$query .= "where $where AND " . $where_auto;
		else
			$query .= "where " . $where_auto;
		if (substr_count ( $order_by, '.' ) > 0)
			$query .= " ORDER BY $order_by";
		elseif ($order_by != "")
			$query .= " ORDER BY $order_by";
		else
			$query .= " ORDER BY ecmstockstates.name";
		return $query;
	}
	function fill_in_additional_list_fields() {
	}
	function fill_in_additional_detail_fields() {
		parent::fill_in_additional_detail_fields ();
	}
	function UpdateStockState($stock_id, $product_id) {
		$q = 0;
		$p = 0;
		$i = 0;
		$pp = 0;
		$qq = 0;
		
		$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='" . $stock_id . "' and product_id='" . $product_id . "'" );
		while ( $rrr = $GLOBALS ['db']->fetchByAssoc ( $w ) ) {
			$rrp = $GLOBALS ['db']->fetchByAssoc ( $GLOBALS ['db']->query ( "select sum(quantity) as s from ecmstockoperations where in_id='" . $rrr ['id'] . "' and type='1' and in_id IS NOT NULL and stock_id='" . $stock_id . "' and product_id='" . $product_id . "' and deleted='0'" ) );
			$rqty = $rrp ['s'];
			
			$qty = $rrr ['qty'] - $rqty;
			if ($qty > 0) {
				$arr [] = array (
						"qty" => $qty,
						"id" => $rrr ['id'],
						"price" => $rrr ['price'] 
				);
				$GLOBALS ['db']->query ( "UPDATE ecmstockoperations SET used='0' WHERE id='" . $rrr ['id'] . "'" );
			} else if ($qty == 0) {
				// set used = 1
				$GLOBALS ['db']->query ( "UPDATE ecmstockoperations SET used='1' WHERE id='" . $rrr ['id'] . "'" );
			}
		}
		
		if (count ( $arr ) > 0) {
			foreach ( $arr as $v ) {
				$q1 += $v ['qty'];
				$pp1 += $v ['qty'] * $v ['price'];
			}
		}
		$GLOBALS ['db']->query ( "delete from ecmstockstates where stock_id='" . $stock_id . "' and product_id='" . $product_id . "' and deleted='0'" );
		
		require_once ("modules/EcmStockOperations/EcmStockOperation.php");
		$o = new EcmStockState ();
		$o->unformat_all_fields ();
		
		require_once ("modules/EcmProducts/EcmProduct.php");
		$o->product_id = $product_id;
		$p = new EcmProduct ();
		$p->retrieve ( $product_id );
		$o->product_name = $p->name;
		$o->product_code = $p->code;
		$o->product_id = $p->id;
		
		require_once ("modules/EcmStocks/EcmStock.php");
		$o->stock_id = $stock_id;
		$s = new EcmStock ();
		$s->retrieve ( $stock_id );
		$o->stock_name = $s->name;
		$o->quantity = $q1;
		if ($q1 > 0)
			$o->price = $pp1 / $q1;
		if($o->price==''){
			$o->empty=0;
		} else {
			$o->empty=1;
		}
		if ($p->id) {
			//echo 'Robie save<br>';
			$oid = $o->save ();
		}
		if ($q1 > 0)
			$GLOBALS ['db']->query ( "update ecmstockstates set price='" . ($pp1 / $q1) . "' where id='" . $oid . "'" );
		unset($o);	
			// add mz
			// update ems_price
		$GLOBALS ['db']->query ( "UPDATE ecmproducts as p
				INNER JOIN (
				SELECT round(sum(quantity*price)/sum(quantity),2) as avg_price, product_id FROM ecmstockstates GROUP BY product_id
		) s ON p.id=s.product_id
				SET p.ems_price = s.avg_price
				WHERE p.id='$product_id'" );
	}
	
	function opList(){
$link='window.open("https://crm.twinpol.com/index.php?module=EcmProducts&action=infomag&product_id='.$this->product_id.'&stock_id='.$this->stock_id.'&to_pdf=1&type=0", "", "width=800,height=600,scrollbars=1")';
$link2='window.open("https://crm.twinpol.com/index.php?module=EcmProducts&action=infomag&product_id='.$this->product_id.'&stock_id='.$this->stock_id.'&to_pdf=1&type=1", "", "width=800,height=600,scrollbars=1")';

		$ii.="
			<img title='Struktura zapasu' alt='Struktura zapasu' src='modules/EcmSales/images/search.gif' onclick='".$link."'>
					<img title='Operacje magazynowe' alt='Operacje magazynowe' src='modules/EcmSales/images/search.gif' onclick='".$link2."'>
			";
		return $ii;
	}
	
	function get_list_view_data() {
		global $current_language;
		$the_array = parent::get_list_view_data ();
		$app_list_strings = return_app_list_strings_language ( $current_language );
		$mod_strings = return_module_language ( $current_language, 'EcmStockStates' );
		
		$the_array ['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);
		//$the_array ['QUANTITY'] = format_number($this->quntity,4);
		$p = new EcmProduct ();
		$p->retrieve ( $this->product_id );
		
		global $app_list_strings;
		//$op = '<a href="index.php?module=EcmInvoiceOuts&action=createPDF&pdf_type=0&to_pdf=1&show_img=1&show_ean=0&show_ean2=0&show_recipient_code=0&record=' . $this->id . '" target="new"/><img src="modules/EcmInvoiceOuts/images/pdf.gif"/></a>';
		$the_array ['OPTIONS'] = $this->opList();
		$the_array ['PART_ID'] = $app_list_strings ['ecmproducts_unit_dom'] [$p->unit_id];
		$the_array ['QUANTITY'] = number_format($this->quantity,$app_list_strings['ecmproducts_unit_dom_precision'] [$p->unit_id],',','');

		$the_array ['ENCODED_NAME'] = $this->name;
		return $the_array;
	}
	function build_generic_where_clause($the_query_string) {
		$where_clauses = array ();
		$the_query_string = PearDatabase::quote ( from_html ( $the_query_string ) );
		array_push ( $where_clauses, "ecmstockstates.name like '$the_query_string%'" );
		
		$the_where = "";
		foreach ( $where_clauses as $clause ) {
			if ($the_where != "")
				$the_where .= " or ";
			$the_where .= $clause;
		}

		return $the_where;
	}
	function set_notification_body($xtpl, $ecmstockstate) {
		global $mod_strings, $app_list_strings;
	//	$xtpl->assign ( "ECMSTOCKSTATE_SUBJECT", $ecmstockstate->name );
		return $xtpl;
	}
	function bean_implements($interface) {
		switch ($interface) {
			case 'ACL' :
				return true;
		}
		return false;
	}
	function save($check_notify = FALSE) {
		return parent::save ( $check_notify );
	}
	function getParts($stock_id, $product_id) {
		$db = $GLOBALS ['db'];
		$q = "SELECT parent_name,parent_id,quantity,price,part_no,part_no2,part_no3,part_no4,part_no5,id from ecmstockoperations where product_id = '" . $product_id . "' and stock_id = '" . $stock_id . "' and deleted = '0' and used = '0' AND 
					(part_no IS NOT NULL
					 OR part_no2 IS NOT NULL
					 OR part_no3 IS NOT NULL
					 OR part_no4 IS NOT NULL
					 OR part_no5 IS NOT NULL
					);";
		
		$res = $db->query ( $q );
		if ($res->num_rows == 0)
			return 0;
		
		$parts = array ();
		// first element - no parts
		$tmp ['part_id'] = null;
		// get product quantity
		$ss = new EcmStockOperation ();
		$tmp ['part_quantity'] = $ss->getStock ( $product_id, $stock_id );
		unset ( $ss );
		$tmp ['part_name'] = '-';
		$parts [] = $tmp;
		while ( $row = $db->fetchByAssoc ( $res ) ) {
			$tmp = array ();
			$tmp ['part_id'] = $row ['id'];
			$tmp ['part_name'] = $row ['part_no'] . ' - ' . $row ['part_no2'] . ' - ' . $row ['part_no3'] . ' - ' . $row ['part_no4'] . ' - ' . $row ['part_no5'];
			// is this part used?
			$r = $db->fetchByAssoc ( $db->query ( "SELECT sum(quantity) as qty FROM ecmstockoperations WHERE in_id='" . $row ['id'] . "'" ) );
			if ($r && $r ['quantity'] > 0)
				$tmp ['part_quantity'] = $row ['quantity'] - $r ['qty'];
			else
				$tmp ['part_quantity'] = $row ['quantity'];
			$parts [] = $tmp;
		}
		
		return json_encode ( $parts );
	}
}
?>
