<?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');
include_once("modules/EcmStockOperations/EcmStockOperation.php");
include_once("modules/EcmPaymentStates/helper.php");

// SHOULD INCLUDE SELECTIVELY


class EcmProduct 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;

	//TABLE COLUMNS 
	var $code;
	var $product_category_id;
	var $product_category_name;
	var $product_subcategory_id;
	var $product_subcategory_name;
	var $product_line_id;
	var $product_line_name;
	var $manufacturer_id;
	var $manufacturer_name;
	var $contact_id;
	var $contact_name;
	var $vendor_id;
	var $vendor_name;
	var $vendor_part_no;
	var $product_active;
	var $flag;
	var $sales_start_date;
	var $sales_end_date;
	var $parent_type;
	var $parent_id;
	var $parent_name;
	var $website;
	var $part_no;
	var $serial_no;
	var $exchange_rate_id;
	var $exchange_rate_name;
	var $fob_price;
	var $purchase_price;
	var $ems_price;
	var $commission_rate;
	var $custom_duty_rate;
	var $srp_price;
	var $srp_price_eur;
	var $srp_promo_price;
	var $tax_class_id;
	var $tax_class_name;
	var $usage_unit_id;
	var $usage_unit_name;
	var $qty_in_stock;
	var $qty_in_demand;
	var $ems_qty_in_stock;
	var $reorder_level;
	var $sales_last_month_1;
	var $sales_last_month;
	var $sales_this_month;
	var $qty_per_unit;
	var $average_sale_3_months;
	var $sales_plus_1;
	var $sales_plus_2;
	var $sales_plus_3;
	var $product_picture;
	var $packing_front_picture;
	var $driver_1;
	var $driver_2;
	var $moq;
	var $fob_basis_id;
	var $fob_basis_name;
	var $delivery_time_fob;
	var $pieces_per_carton;
	var $product_netto_weight;
	var $product_brutto_weight;
	var $packing_type_id;
	var $packing_type_name;
	var $packing_dimensions_1;
	var $packing_dimensions_2;
	var $packing_dimensions_3;
	var $rma;
	var $carton_dimensions_1;
	var $carton_dimensions_2;
	var $carton_dimensions_3;
	var $carton_netto_weight;
	var $carton_brutto_weight;
	var $carton_volume_meter;
	var $carton_volume_feet;
	var $country_of_origin;
	var $certificate_of_origin;
	var $form_a;
	var $vat_id;
	var $vat_name;
	var $vat_value;
	var $selling_price;
	var $ems_ordered;
	var $graduated_prices;
	var $unit_id;
	var $ordered;
	var $lead_time;
	var $production;
	var $description_card;
	var $characteristic_card;
	var $specification_card;
	var $used_to_card;
	var $image_card;
	var $end_of_line;
	var $status;
	var $add_status;
	var $models;
	var $position_list;
	var $th;
	var $url1;
	var $url2;
	var $url3;
	var $url4;
	var $url5;
	var $url6;
	var $url7;
	var $url8;
	var $url9;
	var $ean;

	// RELATED FIELDS
	var $created_by;
	var $created_by_name;
	var $modified_by_name;
	var $assigned_user_name;

	// SUBPANELS RELATED

	// MODULE OBJECT DETAILS 
	var $module_dir        = 'EcmProducts';
	var $table_name        = "ecmproducts";
	var $object_name       = "EcmProduct";

	//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',
	);

	var $relationship_fields = array(
		//RELATIONSHIP FIELDS 

	);

	function EcmProduct()
	{
		parent::SugarBean();
		$this->setupCustomFields('EcmProducts');
		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 create_list_query($order_by, $where, $show_deleted = 0)
	{
		// Fill in the assigned_user_name
		$custom_join = $this->custom_fields->getJOIN();
		$query   = "SELECT ";
		$query  .= "
                     ecmproducts.*
                    ,users.user_name as assigned_user_name";
		if ($custom_join) {
			$query .= $custom_join['select'];
		}
		$query  .= " FROM ecmproducts 
                   LEFT JOIN users
                          ON ecmproducts.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 ";
		} else if ($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";
		} else if ($order_by != "")
			$query .= " ORDER BY $order_by";
		else
			$query .= " ORDER BY ecmproducts.name";

		return $query;
	}

	function create_export_query($order_by, $where)
	{
		$custom_join = $this->custom_fields->getJOIN();
		$query       = "SELECT
                    ecmproducts.*,
                    users.user_name assigned_user_name";
		if ($custom_join) {
			$query .=  $custom_join['select'];
		}
		$query .= " FROM ecmproducts ";

		$query .= "    LEFT JOIN users
                          ON ecmproducts.assigned_user_id=users.id";
		if ($custom_join) {
			$query .=  $custom_join['join'];
		}
		$query  .= "";
		$where_auto = "  ecmproducts.deleted=0
                  ";

		if ($where != "")
			$query .= " where $where AND " . $where_auto;
		else
			$query .= " where " . $where_auto;

		if ($order_by != "")
			$query .= " ORDER BY $order_by";
		else
			$query .= " ORDER BY ecmproducts.name";

		return $query;
	}

	function fill_in_additional_list_fields() {}

	function fill_in_additional_detail_fields()
	{
		// FILL IN THE ASSIGNED_USER_NAME
		$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
		$this->created_by_name    = get_assigned_user_name($this->created_by);
		$this->modified_by_name   = get_assigned_user_name($this->modified_user_id);


		if ($_REQUEST['action '] == 'DetailView') {
			$this->url1 = '<a href="' . $this->url1 . '" target="_blank"/>' . $this->url1 . '</a>';
			$this->url2 = '<a href="' . $this->url2 . '" target="_blank"/>' . $this->url2 . '</a>';
			$this->url3 = '<a href="' . $this->url3 . '" target="_blank"/>' . $this->url3 . '</a>';
			$this->url4 = '<a href="' . $this->url4 . '" target="_blank"/>' . $this->url4 . '</a>';
			$this->url5 = '<a href="' . $this->url5 . '" target="_blank"/>' . $this->url5 . '</a>';
			$this->url6 = '<a href="' . $this->url6 . '" target="_blank"/>' . $this->url6 . '</a>';
			$this->url7 = '<a href="' . $this->url7 . '" target="_blank"/>' . $this->url7 . '</a>';
			$this->url8 = '<a href="' . $this->url8 . '" target="_blank"/>' . $this->url8 . '</a>';
			$this->url9 = '<a href="' . $this->url9 . '" target="_blank"/>' . $this->url9 . '</a>';
		}

		//$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT SUM(quantity) as qty FROM ecmstockstates WHERE product_id='".$this->id."'"));
		//$this->ems_qty_in_stock = $r['qty'];
	}
	function getSale($date)
	{
		foreach ($date as $d) {
			$z = "select
		sum(
			CASE WHEN e.type!='correct' 
				THEN 
					CASE WHEN e.currency_value is null or e.currency_value='' 
						THEN 		
							i.price*i.quantity 
						ELSE 
							i.price*i.quantity*e.currency_value 
					END 
				ELSE 
				CASE WHEN ci.price is null or ci.quantity is null 
					THEN 
						0 
					ELSE 
						i.price*i.quantity-ci.price*ci.quantity 
				END 
			END
		) as sales,
		sum(
			CASE WHEN e.type!='correct' 
				THEN 
					i.purchase_price*i.quantity 
				ELSE 
				CASE WHEN ci.quantity is null 
					THEN 
						0 
					ELSE 
						ci.purchase_price*i.quantity-ci.purchase_price*ci.quantity 
				END 
			END
		) as purchase,
		sum(
			CASE WHEN e.type!='correct' 
				THEN 
					i.quantity
				ELSE 
				CASE WHEN ci.quantity is null 
					THEN 
						0 
					ELSE 
						i.quantity-ci.quantity 
				END 
			END
		) as quantity
		from ecminvoiceoutitems as i 
		left join ecminvoiceoutitems as ci on i.ecminvoiceoutitem_id=ci.id
		inner join ecminvoiceouts as e on e.id=i.ecminvoiceout_id
		left join ecmstockdocouts as w on e.wz_id=w.id
		left join ecmproducts as p on p.id=i.ecmproduct_id
		where 
		e.register_date like '" . $d . "%' and e.status='accepted' and i.ecmproduct_id='" . $this->id . "'";
			$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query($z));
			$total_s += $r['sales'];
			$total_p += $r['purchase'];
			$total_q += $r['quantity'];
			/*$r=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(i.quantity) as q,sum(i.quantity*i.price) as s,sum(i.quantity*i.purchase_price) as p from ecminvoiceouts as e inner join ecminvoiceoutitems as i on i.ecminvoiceout_id=e.id where e.register_date like '".$d."%' and e.status='accepted' and i.ecmproduct_id='".$this->id."'"));
			$total_s+=$r['s'];
			$total_p+=$r['p'];
			$total_q+=$r['q'];
			$w=$GLOBALS['db']->query("select i.quantity,i.price,i.purchase_price,i.ecminvoiceoutitem_id from ecminvoiceouts as e inner join ecminvoiceoutitems as i on i.ecminvoiceout_id=e.id where e.register_date like '".$d."%' and e.status='accepted' and e.type='correct' and i.ecmproduct_id='".$this->id."'");
			while($r=$GLOBALS['db']->fetchByAssoc($w)){
				$total_s+=$r['price']*$r['quantity'];
				$total_q+=$r['quantity'];
				$rr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select price,quantity,purchase_price from ecminvoiceoutitems where id='".$r['ecminvoiceoutitem_id']."'"));
				$totat_s-=$rr['price']*$rr['quantity'];
				$totat_p-=$rr['purchase_price']*$rr['quantity'];
				$total_p+=$rr['purchase_price']*$r['quantity'];
				$totat_q-=$rr['quantity'];
			}*/
		}
		//echo $total_s." ".$total_p." ".$total_q."<br>";
		return array("sale" => $total_s, "purchase" => $total_p, "quantity" => $total_q);
	}

	function get_list_view_data()
	{
		global $current_language, $current_user;
		global $numerek;
		$numerek = $this->id;
		$i = 0;
		$i++;
		$the_array        = parent::get_list_view_data();
		$app_list_strings = return_app_list_strings_language($current_language);
		$mod_strings      = return_module_language($current_language, 'EcmProducts');
		global $current_user_id;

		$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT SUM(quantity) as qty FROM ecmstockstates WHERE product_id='" . $this->id . "'"));
		$this->ems_qty_in_stock = $r['qty'];
		// THE NEW LISTVIEW CODE ONLY FETCHES COLUMNS THAT WE'RE DISPLAYING AND NOT ALL
		// THE COLUMNS SO WE NEED THESE CHECKS. 
		$the_array['NAME'] = (($this->name == "") ? "<em>blank</em>" : $this->name);
		//chmod('modules/EcmProducts/upload/images/'.$this->product_picture,777);
		if (file_exists('modules/EcmProducts/upload/images/' . $this->product_picture) && $this->product_picture) {
			$the_array['IMAGE'] = '<img src="pic.php?p=modules/EcmProducts/upload/images/' . $this->product_picture . '&w=90&h=84" border="0">';
		}
		$the_array['STOCK_QTY'] = 0;
		$op = new EcmStockOperation();
		$the_array['STOCK_QTY'] = format_number($op->getAllQuantity($this->id));
		$the_array['ENCODED_NAME']   = $this->name;
		$lolek = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(pp.product_quantity) as l from ecmproducts_ecmpurchaseorders as pp inner join ecmpurchaseorders as p on p.id=pp.ecmpurchaseorder_id where pp.ecmproduct_id='" . $this->id . "' and p.status='accepted' and p.deleted='0'"));

		//echo "select sum(pp.product_quantity) as l from ecmproducts_ecmpurchaseorders as pp inner join ecmpurchaseorders as p on p.id=pp.ecmpurchaseorder_id where pp.ecmproduct_id='".$this->id."' and p.status='accepted'<br><br>";

		$the_array['ORDERED'] = $lolek['l'];
		$the_array['SRP_PRICE'] = number_format($this->srp_price, 2, $GLOBALS['sugar_config']['default_decimal_seperator'], $GLOBALS['sugar_config']['default_number_grouping_seperator']);
		$the_array['EDIT_BTN'] = '<img src="modules/EcmQuotes/images/edit_inline_enabled.gif" onclick="javascript:window.location=\'index.php?module=EcmProducts&action=EditView&record=' . $this->id . '&return_module=EcmProducts&return_action=index\';" style="cursor: pointer;" border="0">';
		$the_array['PURCHASE_PRICE'] = number_format($this->purchase_price, 2, $GLOBALS['sugar_config']['default_decimal_seperator'], $GLOBALS['sugar_config']['default_number_grouping_seperator']);
		$the_array['COMMISSION_RATE'] = number_format($this->commission_rate, 2, $GLOBALS['sugar_config']['default_decimal_seperator'], $GLOBALS['sugar_config']['default_number_grouping_seperator']);
		if ($_SESSION[$current_user->user_name . '_PREFERENCES']['global']['EcmProductsQ']['stock_id_basic']) {
			$sid = $_SESSION[$current_user->user_name . '_PREFERENCES']['global']['EcmProductsQ']['stock_id_basic'];
			$st = " and stock_id='" . $sid . "'";
		} elseif ($_SESSION[$current_user->user_name . '_PREFERENCES']['global']['EcmProductsQ']['stock_id_advanced']) {
			$sid = $_SESSION[$current_user->user_name . '_PREFERENCES']['global']['EcmProductsQ']['stock_id_advanced'];
			$st = " and stock_id='" . $sid . "'";
		} else $st = "";
		$this->retrieve($this->id);


		if (!$this->code) $this->code = '--';

		if ($_REQUEST['action'] == 'ListView' || $_REQUEST['action'] == 'index') {
			if ($this->product_active) {
				if ($this->status == 'active') {
					$the_array['CODE'] = '<div style="background:green;font-weight:bold;padding:3px;color:white;text-align:left">' . $this->code . '</div>';
				}
				if ($this->status == 'new') {
					$the_array['CODE'] = '<div style="background:blue;font-weight:bold;padding:3px;color:white;text-align:left">' . $this->code . '</div>';
				}
				if ($this->status == 'end_of_line') {
					$the_array['CODE'] = '<div style="background:yellow;font-weight:bold;padding:3px;color:red;text-align:left">' . $this->code . '</div>';
				}
				if (!$this->status) {
					$the_array['CODE'] = '<div style="background:grey;font-weight:bold;padding:3px;color:red;text-align:left">' . $this->code . '</div>';
				}
			} else
				$the_array['CODE'] = '<div style="background:red;font-weight:bold;padding:3px;color:white;text-align:left">' . $this->code . '</div>';
		}

		/*$z="select sum(quantity) as q from ecmstockstates where product_id='".$this->id."' and deleted='0'".$st;
	  $w=$GLOBALS['db']->query($z);
	  $qq=0;
	  $r=$GLOBALS['db']->fetchByAssoc($w);
	  $qq+=$r['q'];*/



		$the_array['EMS_QTY_IN_STOCK'] = number_format($this->ems_qty_in_stock, 0, "", "");

		/*
	  include_once("modules/EcmProductReports/vtigerConnector.php");
	  $vc=new vtigerConnector();
	  $vc->where="poproductrel.productcode like '".$this->code."'";
	  $vc->limit="0,999";
	  $vc->getData();
	  $vc->getCount();
	  $data=$vc->data;
	  for($i=0;$i<$vc->count;$i++){
	  	$ord+=$data[$i]['quantity'];
	  }
	  */
		$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select * from ecmproducts where id='" . $this->id . "'"));

		$rp_sum = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(p.product_quantity) as s from ecmproducts_ecmpurchaseorders as p inner join ecmpurchaseorders as e on e.id=p.ecmpurchaseorder_id where p.ecmproduct_id='" . $this->id . "' and p.deleted='0' and e.deleted='0'"));
		$rp_app = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(p.product_quantity) as s from ecmproducts_ecmpurchaseorders as p inner join ecmpurchaseorders as e on e.id=p.ecmpurchaseorder_id where p.ecmproduct_id='" . $this->id . "' and p.deleted='0' and (e.status='accepted' or e.status='mailed') and e.deleted='0'"));
		$rp_cr = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select sum(p.product_quantity) as s from ecmproducts_ecmpurchaseorders as p inner join ecmpurchaseorders as e on e.id=p.ecmpurchaseorder_id where p.ecmproduct_id='" . $this->id . "' and p.deleted='0' and e.status='not_accepted' and e.deleted='0'"));

		$the_array['ORD_CREATED'] = $rp_cr['s'];
		$the_array['ORD_APPROVED'] = $rp_app['s'];
		//$the_array['ORDERED']=$rp_app['s']+$rp_cr['s'];
		//$the_array['ORD_DELIVERED']=$r['ord_delivered'];

		$the_array['Q0'] = round($r['q0']);
		$the_array['Q3'] = round(($r['q3']));

		$the_array['S0'] = number_format($r['s0'], 2, ",", ".");
		$the_array['S3'] = number_format($r['s3'], 2, ",", ".");

		$the_array['P0'] = number_format($r['p0'], 2, ",", ".");
		$the_array['P3'] = number_format($r['p3'], 2, ",", ".");

		$stock_value = ($this->ems_price * $this->ems_qty_in_stock);
		$the_array['STOCK_VALUE'] = number_format($stock_value, 2, ",", ".");

		if (round(($r['s3'])) != 0) $stock_month = (($this->ems_qty_in_stock + $this->ordered) / round(($r['s3'])));
		else $stock_month = 0;
		$the_array['STOCK_MONTH'] = number_format($stock_month, 2, ",", ".");

		$the_array['EMS_PRICE'] = number_format($this->ems_price, 2, ",", ".");
		$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select flag from ecmproducts where id='" . $this->id . "'"));
		if ($this->flag) {
			$flag = 0;
			$color = "red";
		} else {
			$flag = 1;
			$color = "#cccccc";
		}
		$the_array['FLAGS'] = '<a href="index.php?module=EcmProducts&action=setFlag&flag=' . $flag . '&record=' . $this->id . '" style="color:' . $color . ';font-weight:bold;text-decoration:none;font-size:16px;">!</a>';

		$the_array['HINT'] = HintProduct($this->id, $this->description, $this->add_status);

		//	$the_array['TO_ORDER'] = $r['to']

		$the_array['STAN'] = "<a href='index.php?module=EcmProducts&action=cd&record=" . $this->id . "&set=" . (int)(!$this->active) . "'>" . ($this->active ? 'Tak' : 'Nie') . "</a>";

		//$GLOBALS['db']->query("update ecmproducts set q0='".$s0['quantity']."',p0='".($s0['sale']-$s0['purchase'])."',s0='".$s0['sale']."',q3='".($s3['quantity']/3)."',p3='".(($s3['sale']-$s3['purchase'])/3)."',s3='".($s3['sale']/3)."',stock_month='".$stock_month."',stock_value='".$stock_value."' where id='".$this->id."'");
		//echo mysql_error();
		// echo $i;
		return  $the_array;
	}

	/**
    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 build_generic_where_clause($the_query_string)
	{
		$where_clauses    = array();
		$the_query_string = PearDatabase::quote(from_html($the_query_string));
		array_push($where_clauses, "ecmproducts.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, $simplemodule)
	{
		global $mod_strings, $app_list_strings;

		$xtpl->assign("NAME",        $simplemodule->name);
		$xtpl->assign("ECMPRODUCTS_DESCRIPTION",    $ecmproducts->description);
		return $xtpl;
	}

	function bean_implements($interface)
	{
		switch ($interface) {
			case 'ACL':
				return true;
		}
		return false;
	}
	function r($t)
	{
		$t = str_replace(".", "", $t);
		$t = str_replace(",", ".", $t);
		$t = floatval($t);
		return $t;
	}
	function save($check_notify = FALSE)
	{
		include("modules/EcmProducts/generateEAN.php");
		if ($_REQUEST['newEan'] == '1') $_REQUEST['ean'] = generateEan(1);
		if ($_REQUEST['newEan2'] == '1') $this->ean2 = generateEAN(2);

		//$_REQUEST['ean2'] = generateEan(1);


		if ($_REQUEST['massupdate']) {
			foreach ($_REQUEST['mass'] as $m) $mm[] = "id='" . $m . "'";
			if ($_REQUEST['production']) $set[] = "production='" . $_REQUEST['production'] . "'";
			if ($_REQUEST['product_active']) $set[] = "product_active='" . $_REQUEST['product_active'] . "'";
			if ($_REQUEST['end_of_line']) $set[] = "end_of_line='" . $_REQUEST['end_of_line'] . "'";
			if ($_REQUEST['sales_start_date']) $set[] = "sales_start_date='" . date("Y-m-d", strtotime($GLOBALS['timedate']->to_db_date($_REQUEST['sales_start_date'])) + 24 * 3600) . "'";
			if ($_REQUEST['sales_end_date']) $set[] = "sales_end_date='" . date("Y-m-d", strtotime($GLOBALS['timedate']->to_db_date($_REQUEST['sales_end_date'])) + 24 * 3600) . "'";
			if (count($set) > 0) $z = "update ecmproducts set " . implode(",", $set) . " where " . implode(" or ", $mm);
			//echo $z;
			$GLOBALS['db']->query($z);
			header("Location: index.php?module=EcmProducts&action=index");
		} else {
			$return_id = parent::save($check_notify);

			//$components = self::ParseComponentsFromPOST();
			//if(!(!is_array($components) && $components == false)) $this->position_list = $components;
			//$this->savePositions($return_id);

			//save categories
			$this->savePositions3($_POST['position_list3']);
			//save prices
			$this->savePrices($_POST['position_list4']);


			return $return_id;
		}
	}


	static function ParseComponentsFromPOST()
	{
		if (isset($_POST['position_list'])) {
			$c_ = $_POST['position_list'];
			$json = getJSONobj();
			$c = $json->decode(htmlspecialchars_decode($c_));
			return $c;
		}
		return false;
	}
	//***************************Start Managing Positions*************************//
	function constructInsertQuery($data, $table = '')
	{

		if ($table == '' && isset($this->object_name) && $this->object_name != '') {
			$table = strtolower($this->object_name) . "components";
		} else return "";

		$keys = array();
		$values = array();
		foreach ($data as $key => $value) {
			$keys[] = $key;
			if (is_array($value))
				$values[] = $value[1] . str_replace("'", "\'", $value[0]) . $value[1];
			else
				$values[] = "'" . str_replace("'", "\'", $value) . "'";
		}

		$q = "insert into `$table` (`";
		$q .= implode('`, `', $keys);
		$q .= "`) values (";
		$q .= implode(", ", $values);
		$q .= ");";

		return $q;
	}
	function savePositions($id = null, $position_list = null)
	{

		global $current_user, $timedate;

		if ($position_list == null) $position_list = $this->position_list;
		if ($id == null) $id = $this->id;

		if (count($position_list) > 0) $this->deleteAssignedPositions($id);

		$arr = array();
		$position = 0;

		for ($i = 0; $i < count($position_list); $i++) {

			if ($position_list[$i]['name'] == '') continue;

			$p = $position_list[$i];

			/* Not Nessesary
			require_once("modules/EcmVats/EcmVat.php");
			$vats = new EcmVat();
			$vats->retrieve($p['vat_id']);
			$p['vat_name'] = $vats->name;

			require_once("modules/Currencies/Currency.php");
			$curr = new Currency();
			$curr->retrieve($p['currency_id']);
			$p['currency_name'] = $curr->name;
	
			if(!empty($p['category_id']) || $p['category_id'] == '') {
				require_once("modules/EcmProducts/EcmProduct.php");
				$pr = new EcmProduct();
				$pr->retrieve($p['id']);
				$p['category_id'] = $pr->product_category_id;	
			}
			*/

			$arr = array(

				'id' => create_guid(),
				'date_entered' => array('NOW()', ''),
				'date_modified' => array('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' => $id,
				'ecmcomponent_id' => $p['id'],
				'position' => $position,
				'code' => $p['code'],
				'name' => $p['name'],
				'quantity' => ((empty($p['quantity']) || $p['quantity'] == '') ? 0 : $p['quantity']),
				'ecmusageunit_id' => $p['unit_id'],

				/* Not Nessesary
				'price' => ((empty($p['price']) || $p['price'] == '') ? 0 : $p['price']),
				'discount' => ((empty($p['discount']) || $p['discount'] == '') ? 0 : $p['discount']),
				'total' => ((empty($p['total']) || $p['total'] == '') ? 0 : $p['total']),
				'dd_unit_id' => $p['unit_id'],
				'dd_unit_name' => '',
				'ecmvat_id' => $p['vat_id'],
				'ecmvat_name' => $p['vat_name'],
				'ecmvat_value' => $p['vat_value'],
				'ecmproductcategory_id' => $p['category_id'],
				'currency_id' => $p['currency_id'],
				'currency_name' => $p['currency_name'],
				'recipient_code' => $p['recipient_code'],
				*/

			);

			$this->db->query($this->constructInsertQuery($arr));
			$position++;
		}
	}
	function getPosition($position)
	{

		global $app_list_strings;

		if (!is_array($position)) return '';

		global $timedate;

		$return_array = array();
		$unit = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select unit_id from ecmproducts where id='" . $position['ecmcomponent_id'] . "'"));
		$return_array['id'] = $position['ecmcomponent_id'];
		$return_array['position'] = $position['position'];
		$return_array['code'] = $position['code'];
		$return_array['name'] = str_replace('&quot;', '', $position['name']);
		$return_array['quantity'] = $position['quantity'];
		$return_array['price'] = $position['price'];
		$return_array['discount'] = $position['discount'];
		$return_array['total'] = $position['total'];
		$return_array['unit_id'] = $unit['unit_id'];
		$return_array['unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$unit['unit_id']];
		$return_array['vat_id'] = $position['ecmvat_id'];
		$return_array['vat_name'] = $position['ecmvat_name'];
		$return_array['vat_value'] = $position['ecmvat_value'];
		$return_array['category_id'] = $position['ecmproductcategory_id'];
		$return_array['currency_id'] = $position['currency_id'];
		$return_array['currency_name'] = $position['currency_name'];
		$return_array['recipient_code'] = $position['recipient_code'];

		//get ems price
		$r = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT ems_price FROM ecmproducts WHERE id='" . $position['ecmcomponent_id'] . "'"));
		$return_array['ems_price'] = $position['quantity'] * $r['ems_price'];
		if (!$r || $r['ems_price'] == 0) {
			$pz = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("
					SELECT price FROM ecmstockoperations WHERE
product_id= '" . $position['ecmcomponent_id'] . "' AND
parent_type = 'EcmStockDocIns'
ORDER BY date_entered DESC
LIMIT 0,1
					"));

			$return_array['ems_price'] = $pz['price'];
		}

		global $db;
		$c = $db->fetchByAssoc($db->query("SELECT product_category_id as c, purchase_price as p FROM ecmproducts WHERE id='" . $position['ecmcomponent_id'] . "'"));
		$return_array['category_id'] = $c['c'];
		if ($c['c'] == 'd7f876b0-1a3d-43a1-7c9b-511ba40df3d1')
			$return_array['ems_price'] = $c['p'];

		if (!$return_array['ems_price'] || $return_array['ems_price'] == "")
			$return_array['ems_price'] = $c['purchase_price'];

		return $return_array;
	}
	function getPositionList($array = false)
	{
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM `ecmproductcomponents` WHERE `ecmproduct_id`='" . $this->id . "' order by position asc";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {
				while ($w = $this->db->fetchByAssoc($r)) {
					$return_array[] = $this->getPosition($w);
				}
				$json = getJSONobj();
				return $array ? $return_array : $json->encode($return_array);
			}
		}
		return $array ? false : '[]';
	}
	function deleteAssignedPositions()
	{
		if (isset($this->id) && $this->id != '') {
			$query = "DELETE FROM `" . strtolower($this->object_name) . "components` WHERE `" . strtolower($this->object_name) . "_id`='" . $this->id . "'";
			$r = $this->db->query($query);
			if ($r) return true;
		}
		return false;
	}
	//***************************End Managing Positions*************************//
	//start managing categories
	function savePositions3($pl)
	{
		global $current_user;
		$exists = array();

		$first = true;
		foreach ($pl as $p) {
			if (!isset($p['ecmproductcategory_id']) || $p['ecmproductcategory_id'] == '') continue;
			//first position save into main category
			if ($first) {
				$q = "UPDATE ecmproducts set product_category_id='" . $p['ecmproductcategory_id'] . "', product_category_name='" . $p['ecmproductcategory_name'] . "' WHERE id='" . $this->id . "'";
				$GLOBALS['db']->query($q);
				$first = false;
			}
			if (isset($p['id']) && $p['id'] != '') {
				//update exists
				$q = "
				UPDATE ecmproductcategories_bean set
					date_modified = '" . date("Y-m-d H:i:s") . "',
					modified_user_id = '" . $current_user->id . "',
					bean_id = '" . addslashes($this->id) . "',
					ecmproductcategory_id = '" . addslashes($p['ecmproductcategory_id']) . "',
					position = '" . $p['position'] . "'
					WHERE id = '" . $p['id'] . "'
				";

				$GLOBALS['db']->query($q);
				$exists[] = $p['id'];
			} else {
				//insert new record
				$id = create_guid();
				$t = array(
					$id,
					addslashes($p['ecmproductcategory_id']),
					$this->id,
					"EcmProducts",
					date("Y-m-d H:i:s"),
					date("Y-m-d H:i:s"),
					$current_user->id,
					$current_user->id,
					'0',
					$p['position'],
				);
				$q = "INSERT INTO ecmproductcategories_bean VALUES ('" . implode("','", $t) . "')";
				$GLOBALS['db']->query($q);
				$exists[] = $id;
			}
		}
		//delete old
		$GLOBALS['db']->query("UPDATE ecmproductcategories_bean SET deleted='1', modified_user_id='" . $current_user->id . "',date_modified = '" . date("Y-m-d H:i:s") . "' WHERE bean_id='" . $this->id . "' AND id NOT IN ('" . implode("','", $exists) . "')");
	}

	function getPositionList3($array = false)
	{
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT * FROM ecmproductcategories_bean WHERE bean_id='" . $this->id . "' AND deleted='0' AND bean_name='EcmProducts'";

			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {

				while ($w = $this->db->fetchByAssoc($r)) {
					//get category name && assigned_file
					$n = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT name, assigned_file FROM ecmproductcategories WHERE id='" . $w['ecmproductcategory_id'] . "'"));
					$w['ecmproductcategory_name'] = $n['name'];
					$w['assigned_file'] = $n['assigned_file'];
					$return_array[] = $w;
				}
				$json = getJSONobj();

				return $array ? $return_array : $json->encode($return_array);
			}
		}
		return $array ? false : '[]';
	}

	function showPositions3()
	{
		$arr = $this->getPositionList3(true);


		global $mod_strings;
		if (count($arr) > 0) {
			$table = '
			<table cellpadding="0" cellspacing="0" border="0" class="list view" width="40%">
			<tr class="oddListRowS1">
				<th><b>' . $mod_strings['LBL_CATEGORY_NAME'] . '</b></td>
				<th><b>' . $mod_strings['LBL_CATEGORY_ASSIGNED_FILE'] . '</b></td>
			</tr>
			';
			$i == 0;
			foreach ($arr as $a) {
				$i++;
				//assigned file
				if ($a['assigned_file'] != "" && $a['assigned_file']) {
					$tmp = explode(".", $a['assigned_file']);
					if (end($tmp) == 'jpeg' || end($tmp) == 'jpg' || end($tmp) == 'png' || end($tmp) == 'bmp')
						$af = '<img src="modules/EcmProductCategories/files/' . $a['assigned_file'] . '"/>';
					else
						$af = '<a href="modules/EcmProductCategories/files/' . $a['assigned_file'] . '" target="new">' . $a['assigned_file'] . '</a>';
				}
				$table .= '
				<tr class="oddListRowS1">
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;"><a href="index.php?module=EcmProductCategories&action=DetailView&record=' . $a['ecmproductcategory_id'] . '">' . $a['ecmproductcategory_name'] . '</a></td>
    
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">' . $af . '</td>
    
				';
			}
			$table .= '</table>';
		}

		return $table;
	}
	//end managing categories 
	//prices manage

	function savePrices($prices)
	{
		if (!is_array($prices)) return null;

		$fields = array('id', 'ecmprice_id', 'ecmproduct_id', 'price');
		$new = array();
		$db = $GLOBALS['db'];


		foreach ($prices as $p) {
			if (!isset($p['price']) || !isset($p['ecmpricebook_id']) || floatval($p['price']) == 0) continue;

			$id = create_guid();
			$new[] = $id;

			$tmp = array();
			$tmp[] = $id;
			$tmp[] = $p['ecmpricebook_id'];
			$tmp[] = $this->id;
			$tmp[] = floatval($p['price']);

			$query = "INSERT INTO ecmprices_ecmproducts (" . implode(",", $fields) . ") VALUES ('" . implode("','", $tmp) . "')";

			$db->query($query);
		}
		$db->query("delete from ecmprices_ecmproducts where ecmproduct_id='" . $this->id . "' AND id NOT IN ('" . implode("','", $new) . "')");
	}

	function getPricePosition($position)
	{
		if (!is_array($position)) return '';

		global $timedate;
		$query = "SELECT id,name FROM ecmpricebooks WHERE id='" . $position['ecmpricebook_id'] . "'";
		$r = $this->db->fetchByAssoc($this->db->query($query));

		$return_array = array();

		$return_array['price'] = $position['price'];
		$return_array['pricebook_name'] = $r['name'];
		$return_array['pricebook_id'] = $r['id'];

		//var_dump($return_array);
		return $return_array;
	}
	function getPricesList($array = false)
	{
		if (isset($this->id) && $this->id != '') {
			$query = "SELECT p.id as id, p.name as name, pp.price as price  FROM ecmprices as p 
    				LEFT JOIN ecmprices_ecmproducts as pp
    				ON pp.ecmprice_id=p.id AND pp.ecmproduct_id='" . $this->id . "'
    				WHERE p.deleted='0'";
			$r = $this->db->query($query);
			$return_array = array();
			if ($r) {
				while ($w = $this->db->fetchByAssoc($r)) {
					$tmp = array();
					$tmp['pricebook_id'] = $w['id'];
					$tmp['pricebook_name'] = $w['name'];
					$tmp['price'] = $w['price'];
					$return_array[] = $tmp;
				}
				$json = getJSONobj();
				return $array ? $return_array : $json->encode($return_array);
			}
		}
		return $array ? false : '[]';
	}

	function showPrices()
	{
		$arr = $this->getPricesList(true);
		if (count($arr) > 0) {
			$table = '
			<table cellpadding="0" cellspacing="0" border="0" class="list view">
			<tr class="oddListRowS1">
				<th width="15%"><b>Nazwa</b></td>
				<th><b>Wartość</b></td>
			</tr>
			';
			foreach ($arr as $a) {
				$table .= '
				<tr class="oddListRowS1">
				<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">
				' . $a['pricebook_name'] . '</td>
				<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">
				' . format_number($a['price']) . '</td>
				';
			}
			$table .= '</table>';
		}

		return $table;
	}
	//end manage prices  
	function getProductResInfo($product_id, $stock_id)
	{
		$info = array();
		global $db;

		require_once('modules/EcmStockOperations/EcmStockOperation.php');
		$op = new EcmStockOperation();
		$info['stock'] = $op->getRealStock($product_id, $stock_id);
		//temp reserwations
		$rr = $db->fetchByAssoc($db->query("SELECT sum(quantity) as s FROM ecmreservations WHERE product_id='$product_id' AND doc_id IS NULL"));
		if (!$rr['s']) $rr['s'] = 0;
		$info['res'] = $rr['s'];
		//doc reservations
		$res = $db->query("SELECT quantity, doc_id, doc_type FROM ecmreservations WHERE product_id='$product_id' AND doc_id IS NOT NULL");

		if (!is_array($res) == 0) return $info;

		while ($row = $db->fetchByAssoc($res)) {
			$tmp = array();
			$type = '';
			if ($row['doc_type'] == 'EcmSales') $type = 'ZS';
			if ($row['doc_type'] == 'EcmInsideOrders') $type = 'ZW';
			//get document name
			$doc = $GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("SELECT document_no, parent_name  FROM " . strtolower($row['doc_type']) . " WHERE id='" . $row['doc_id'] . "'"));
			$tmp[] = '<a target="new" href="index.php?module=' . $row['doc_type'] . '&action=DetailView&record=' . $row['doc_id'] . '">' . $type . ' ' . $doc['document_no'] . '</a> - ' . $row['quantity'] . '&nbsp&nbsp' . $doc['parent_name'];
		}
		$info['docs'] = $tmp;

		return $info;
	}

	//add mz 2014-12-11
	//android mobile functions

	//search product by EAN
	//simply try found product_id and executa function below
	static function mobile_getProductInfoByEAN($params)
	{
		$ean = trim($params['product_ean']);
		if (!$ean || $ean == "")
			return -2;

		$db = $GLOBALS['db'];

		$prod = $db->fetchByAssoc($db->query("SELECT
    			id FROM ecmproducts 
    			WHERE
    			(TRIM(ean) = '$ean' OR
    			 TRIM(ean2) = '$ean') AND
    			deleted = '0'
    			ORDER BY code
    			LIMIT 0,1"));

		if (!$prod['id'])
			return -3; //product not exist
		else
			return EcmProduct::mobile_getProductInfo(
				array(
					'product_id' => $prod['id']
				)
			);
	}


	//ERROR CODES
	// -2 - wrong paramaters
	// -3 - can't find object
	static function mobile_getProductInfo($params)
	{
		$app_list_strings = return_app_list_strings_language("pl_pl");

		$product_id = $params['product_id'];
		if (!$product_id || $product_id == "")
			return -2;

		$db = $GLOBALS['db'];
		$prod = $db->fetchByAssoc($db->query("SELECT 
    			id, 
    			IFNULL(name,'-') AS name, 
    			IFNULL(code,'-') AS code, 
    			IFNULL(ean,'-') AS ean, 
    			IFNULL(ean2,'-') AS ean2, 
    			IFNULL(unit_id,'-') AS unit_id 
    			FROM ecmproducts WHERE id='$product_id'"));

		if (!$prod['id'])
			return -3; //product not exist

		//get stocks array
		$stocks = array();
		$res = $db->query("SELECT IFNULL(stock_name, '-') as stock_name, quantity FROM ecmstockstates WHERE product_id = '$product_id' AND deleted = '0' AND quantity IS NOT NULL AND quantity != '0' ORDER BY stock_name;");

		while ($row = $db->fetchByAssoc($res)) {
			//format number precision
			if ($prod['unit_id'] == "1")
				$qty = format_number(intval($row['quantity']), 0, 0);
			else
				$qty = format_number(intval($row['quantity']), 4, 2);

			$tmp = array();
			$tmp['name'] = $row['stock_name'];
			$tmp['quantity'] = $qty;
			$stocks[] = $tmp;
		}

		if (sizeof($stocks) == 1)
			$s = htmlspecialchars_decode(json_encode($stocks), ENT_QUOTES);
		else
			$s = htmlspecialchars_decode(json_encode($stocks), ENT_QUOTES);

		$result = array(
			'code' => $prod['code'],
			'name' => base64_encode($prod['name']),
			'id' => $prod['id'],
			'ean' => $prod['ean'],
			'ean2' => $prod['ean'],
			'stockStates' =>  base64_encode($s),
			'unit' => $app_list_strings['ecmproducts_unit_dom'][$prod['unit_id']],
		);

		return $result;
	}
}
