<?php
if (! defined ( 'sugarEntry' ) || ! sugarEntry)
	die ( 'Not A Valid Entry Point' );
ini_set('display_errors',1);
require_once ('data/SugarBean.php');
class EcmServiceNew 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 $description;
	var $number;
	var $document_no;
	var $register_date;
	var $total;
	var $history;
	var $items_list;
	var $created_by;
	var $created_by_name;
	var $modified_by_name;
	var $assigned_user_name;
	var $module_dir = "EcmServiceNews";
	var $table_name = "ecmservicenews";
	var $object_name = "EcmServiceNew";
	var $additional_column_fields = Array (
			'assigned_user_name',
			'assigned_user_id',
			'modified_user_id',
			'created_by' 
	);
	function EcmServiceNew() {
		parent::SugarBean ();
		$this->setupCustomFields ( 'EcmServiceNews' );
		foreach ( $this->field_defs as $field ) {
			$this->field_name_map [$field ['name']] = $field;
		}
	}
	var $new_schema = true;
	
	//nazwa w title strony
	function get_summary_text(){
		return "$this->document_no";
	}

	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 );
	}
	
	function get_list_view_data() {
		$the_array = parent::get_list_view_data ();
		$the_array['OPTIONS'] = '<a href="index.php?module=EcmServiceNews&action=createPDF&to_pdf=1&record=' 
		. $this->id . '" target="_bank"/><img src="modules/EcmInvoiceOuts/images/pdf.gif"/></a>';
		return $the_array;
	}

	function bean_implements($interface) {
		switch ($interface) {
			case 'ACL' :
				return true;
		}
		return false;
	}
	
	function retrieve($id = -1, $encode=true,$deleted=true){
		global $mod_strings, $dictionary, $app_list_strings;
		$focus = parent::retrieve($id,$encode,$deleted);
		
		if($id != -1){
			//Pobieram rekordy historii danego zlecenia
			$history_query = "SELECT * FROM " . $this->table_name . "_audit WHERE parent_id='" . $id . "'";
			$history_result = $this->db->query($history_query);
			while($row = $this->db->fetchByAssoc($history_result)){
				$old_field_name = $row['field_name'];
				$row['field_name'] = $mod_strings[$dictionary['EcmServiceNew']['fields'][$old_field_name]['vname']];
				if($row['data_type']=='enum'){
					$row['before_value_string'] = $app_list_strings[$dictionary['EcmServiceNew']['fields'][$old_field_name]['options']][$row['before_value_string']];
					$row['after_value_string'] = $app_list_strings[$dictionary['EcmServiceNew']['fields'][$old_field_name]['options']][$row['after_value_string']];
				}
				$focus->history[$row['date_created']][] = $row;
			}
			asort($focus->history);
			//Pobieram rekordy kosztów
			$items_query = "SELECT * FROM ecmservicenewitems WHERE ecmservicenew_id='" . $id . "' AND deleted=0 order by position";
			$items_result = $this->db->query($items_query);
			while($row = $this->db->fetchByAssoc($items_result)){
				$row['ecmproduct_unit_precision'] = $app_list_strings['ecmproducts_unit_dom_precision'][$row['ecmproduct_unit_id']];
				$focus->items_list[] = $row;
			}
		}
		return $focus;
	}
	
	function get_items_list_for_id($id = -1){

	}
	
	function get_history_for_id($id = -1){

	}
	
	function save($check_notify = FALSE) {
		global $current_user, $db;
		require_once('modules/EcmSysInfos/EcmSysInfo.php');
		$EcmSysInfo = new EcmSysInfo();
		$template = $EcmSysInfo->getFormatNumberForModule('EcmServiceNews');
		$this->type='normal';
		unset($EcmSysInfo);
		if (! $this->id || $this->id == '') {
			// generate number
			if ($template != "") {
				require_once('include/ECM/EcmDocumentNumberGenerator/EcmDocumentNumberGenerator.inc.php');
				$dng = new EcmDocumentNumberGenerator('EcmServiceNews');
				$this->document_no=  $dng->parseNormalNumber($template, $this->stock_id);
			}				
		}
		if(!isset($this->number) || $this->number == ""){
			$this->number = $this->generateNumber();
		}
		$return_id = parent::save ( $check_notify );
		
		$old_items_query = "DELETE FROM ecmservicenewitems WHERE ecmservicenew_id ='" . $return_id . "'";
		$db->query($old_items_query);
		$json = getJSONobj();
		$position_list = $json->decode(htmlspecialchars_decode($_POST['position_list']));
		foreach($position_list as $key => $row){
			if($row['name']==''){
				$product = true;
			}
			if($row['quantity'] || $row['quantity'] =='0,00'){
				$quantity = true;
			}
			if($row['price_start']=='' || $row['price_start'] =='0,00'){
				$price = true;
			}
			if($product && $quantity && $price){
				continue;
			}
			$insert_data['date_entered'] = 'NOW()';
			$insert_data['date_modified'] = 'NOW()';
			$insert_data['created_by'] = $current_user->id;
			$insert_data['modified_user_id'] = $current_user->id;
			$insert_data['ecmservicenew_id'] = $return_id;
			$insert_data['ecmproduct_id'] = $row['product_id'];
			$insert_data['position'] = $key;
			$insert_data['ecmproduct_name'] = $row['name'];
			$insert_data['quantity'] = floatval($row['quantity']);
			$insert_data['price'] = round (floatval($row['price_start']),2);
			$insert_data['total'] =  round ($insert_data['quantity']*$insert_data['price'],2);
			$insert_data['ecmproduct_unit_id'] = $row['unit_id'];
			$keys = array_keys($insert_data);
			$values  = array_values($insert_data);
			$query = "INSERT INTO ecmservicenewitems (" . implode(",",$keys) . ") VALUES ('" . implode("','",$values) . "')";
			$db->query(str_replace("'NOW()'", "NOW()",$query));
		}
		return $return_id;
	}
	
	function generateNumber() {
		$db = $GLOBALS['db'];
		$r = $db->fetchByAssoc($db->query("SELECT count(id) as c FROM ecmservicenews WHERE YEAR(register_date)='".date('Y')."'"));

	    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").$tmp;
	}
}
?>