<?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 EcmPrepaymentInvoice 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 $inv_value;
	var $position_list;
	var $products_on_pdf;
	
	var $module_dir = 'EcmPrepaymentInvoices';
	var $table_name = "ecmprepaymentinvoices";
	var $object_name = "EcmPrepaymentInvoice";
	
	var $new_schema = true;

	var $additional_column_fields = array('assigned_user_name', 'assigned_user_id');

	function EcmPrepaymentInvoice() {
		parent::SugarBean();
		$this->setupCustomFields('EcmPrepaymentInvoices');
		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.="ecmprepaymentinvoices.*,users.user_name as assigned_user_name";
		if($custom_join)$query.=$custom_join['select'];
        $query.=" FROM ecmprepaymentinvoices ";
		$query.="LEFT JOIN users ON ecmprepaymentinvoices.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 ecmprepaymentinvoices.name";		
		return $query;
	}
	function create_export_query($order_by,$where){
		$custom_join = $this->custom_fields->getJOIN();
		$query ="SELECT ";
        $query.="ecmprepaymentinvoices.*,users.user_name as assigned_user_name";
		if($custom_join)$query.=$custom_join['select'];
        $query.=" FROM ecmprepaymentinvoices ";
		$query.="LEFT JOIN users ON ecmprepaymentinvoices.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 ecmprepaymentinvoices.name";		
		return $query;
    }
	function fill_in_additional_list_fields(){
	}

	function fill_in_additional_detail_fields(){   
		$this->to_nip = 'tt';
        parent::fill_in_additional_detail_fields();
	}		
	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,'EcmPrepaymentInvoices');

	    $the_array['NAME']=(($this->name == "") ? "<em>blank</em>" : $this->name);
	    $the_array['ENCODED_NAME']=$this->name;
		$the_array['PDF']='<img border="0" src="modules/EcmSales/images/pdf.gif" title="Podglad Zam�wienia" onclick="EcmPreviewPDF(\'index.php?module=EcmPrepaymentInvoices&amp;action=previewPDF&amp;method=I&amp;record='.$this->id.'&amp;to_pdf=1\',{zoom:75,toolbar:1});" style="cursor:pointer">';
		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,"ecmprepaymentinvoices.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,$ecmprepaymentinvoice)
	{
		global $mod_strings,$app_list_strings;
		$xtpl->assign("ECMPREPAYMENTINVOICE_SUBJECT",$ecmprepaymentinvoice->name);
		return $xtpl;
	}
	
	function bean_implements($interface){
		switch($interface){
			case 'ACL':return true;
		}
		return false;
	}
	
	function save($check_notify=FALSE){
		$return_id = parent::save($check_notify);
		
		//$this->savePositions($return_id);
		
		return $return_id;
	}
	
	
	
	
	
    function setTemplate() {

      if(!isset($this->template_id) || $this->template_id == '') return null;

      if(isset($this->template)) return $this->template;

      

      require_once('modules/EcmDocumentTemplates/EcmDocumentTemplate.php');

      $this->template = new EcmDocumentTemplate();

      //$this->template->retrieve($this->template_id);
	  $this->template->retrieve($this->template_id, true, false);


      if(isset($this->template->id) && $this->template->id != '') {

        $this->template->format_all_fields();

      } 

      else

        $this->template = null;

        

      return $this->template;

    }
	
	function generateNumber() {
	  $this->setTemplate();
      $this->number = isset($this->template) ? $this->template->generateNumber($this->table_name) : '';
      return $this->number;
    }  

    function formatNumber() {
      $this->setTemplate();
      $this->document_no = isset($this->template) ? $this->template->formatNumber($this->number, $this->module_dir) : ''; 
      return $this->document_no;
    }
    function formatDocumentNumber($documentNumber = '', $code = '') {
      return isset($this->template) ? $this->template->formatDocumentNumber($documentNumber, $code) : ''; 
    }
    function getPDF($id = null,$method = 'I',$name = null) {
	
      global $sugar_config;

      if($id != null) {

        $this->retrieve($id);

        if($this->id == '') return;

      }

      global $mod_strings;
	  require_once('modules/EcmTexts/EcmText.php');
	  if(isset($this->ecmlanguage) && $this->ecmlanguage != '') {
		  $data = EcmText::LoadText(null,null,"EcmPrepaymentInvoices",$this->ecmlanguage);
		  if(isset($data[0]) && isset($data[0]['data']) && isset($data[0]['data']['labels'])) {
			$data = $data[0]['data']['labels'];
			foreach($data as $key => $value) {
				$mod_strings[$value['label']] = $value['translation'];
			}
		  }
	  }

      $this->format_all_fields();

      $this->setTemplate();


      if(isset($this->template->id) && $this->template->id != '') {

        $this->template->setPDF($this->template_id);
	 $this->template->pdf->SetAutoPageBreak(true,40);
        $this->DrawMainPDF($this->template->pdf);

        $this->template->outputPDF((($name) ? $name : $this->createPdfFileName()),$method);

      }
	  

    }
	
    function DrawMainPDF($pdf) {


	  global $mod_strings;
	  
	  $arr=$this->template->getTemplateFile($_REQUEST['module']);
	  
	  include_once("modules/EcmDocumentTemplates/templates/".$arr[0]."/".$arr[1]."/subheader.php");
	  /*
	  $pdf->SetFont('arialpl','','7');
      $this->DrawPositions($pdf);
	  */
	  include_once("modules/EcmDocumentTemplates/templates/".$arr[0]."/".$arr[1]."/subfooter.php");
    }
	
    function setUser() {
      if(is_object($this->user)) return $this->user;
      require_once('modules/Users/User.php');
      $us = new User();
      global $current_user;
      $us->retrieve(($this->assigned_user_id)?$this->assigned_user_id:$current_user->id);
      if(isset($us->id) && $us->id != '') {
        $this->user = $us;
      } 
      else
        $this->user = null;
      return $this->user;
    }
	function createPdfFileName($format=true) {
	  $arr1 = Array('\\', '/', ':', '*', '?' , '"',  '<', '>', '|', ' ');
      $arr2 = Array('',  '', '',  '',  '',   '\'', '[', ']', '', '_');
      $tmp = $this->document_no;
      if($format) { 
          $tmp = str_replace($arr1, $arr2, 'Invoice_'.$tmp.'.pdf');
      }
      else
        $tmp = 'InvoiceOut '.$tmp.'.pdf';
      return $tmp; 

    }
	
	//manage positions
	function getPosition($position, $checked = false) {

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

		global $timedate;
		global $db;
		
		$r=$db->fetchByAssoc($db->query("select q.document_no,q.id from ecmquotes as q inner join ecmquoteitems as i on i.ecmquote_id=q.id where i.id='".$position['item_id']."'"));
		$rs=$db->fetchByAssoc($db->query("select sum(quantity) as q from ecmstockdocoutitems where item_id='".$position['id']."'"));
		
		$pr=$db->fetchByAssoc($db->query("select unit_name from ecmproducts where id='".$position['ecmproduct_id']."'"));
		$return_array = array();
		$return_array['id'] = $position['ecmproduct_id'];
		//$return_array['ecmquote_id']=$r['id'];
		//$return_array['ecmquote_name']=$r['document_no'];
		
		$return_array['iid'] = $position['id'];
		//$return_array['item_id'] = $position['item_id'];
		//$return_array['position'] = $position['position'];
		$return_array['code'] = $position['code'];
		$return_array['name'] = $position['name'];
		$return_array['quantity'] = $position['quantity'];
		
		if ($checked) $return_array['checked'] = true;
		//$return_array['price'] = $position['price'];
		//$return_array['discount'] = $position['discount'];
		//$return_array['total'] = $position['total'];
		//$return_array['unit_id'] = $position['dd_unit_id'];
		//$return_array['unit_name'] = $pr['unit_name'];
		//$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'];
		//$return_array['temp_item_id'] = $position['temp_item_id'];
		//$return_array['temp_date'] = $position['temp_date'];
		//$return_array['rq'] = $position['rq'];
		//if($rs['q']<$position['quantity'])$return_array['check']=$position['id'];
		//include_once("modules/EcmStockOperations/EcmStockOperation.php");
		//$op=new EcmStockOperation();
		//$return_array['stock']=$op->getStock($position['ecmproduct_id']);
		return $return_array;		
	}
	
    function getPositionListDetailView($sale_id, $array = false) {
		//get invoice products 
		$inv_prod = explode("|", $this->products_on_pdf);
        $query = "SELECT * FROM `ecmsaleitems` WHERE  id IN ('".implode("','", $inv_prod)."') order by position asc";
        $r = $this->db->query($query);
        $return_array = array();

        if($r) {
          while($w = $this->db->fetchByAssoc($r)) {
			if (in_array($w['id'], $inv_prod)) $checked = true; else $checked = false;
            $return_array [] = $this->getPosition($w, $checked);
          }
          $json = getJSONobj();
          return $array ? $return_array : $json->encode($return_array);
        }
      
      return $array ? false : '[]';
    }
    function getPositionList($sale_id, $array = false) {
		//get invoice products 
		$inv_prod = explode("|", $this->products_on_pdf);
        $query = "SELECT * FROM `ecmsaleitems` WHERE `ecmsale_id`='".$sale_id."' order by position asc";
        $r = $this->db->query($query);
        $return_array = array();
		//return $query;
        if($r) {
          while($w = $this->db->fetchByAssoc($r)) {
			if (in_array($w['id'], $inv_prod)) $checked = true; else $checked = false;
            $return_array [] = $this->getPosition($w, $checked);
          }
          $json = getJSONobj();
          return $array ? $return_array : $json->encode($return_array);
        }
      
      return $array ? false : '[]';
    }
}
?>
