<?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-2010 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero 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 Affero General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero 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 Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero 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".
 ********************************************************************************/
require_once ('include/upload_file.php');


// User is used to store Forecast information.
class EcmKpkw extends SugarBean {

	var $id;
	var $ecmkpkw_name;
	var $description;
	var $category_id;
	var $subcategory_id;
	var $status_id;
	var $status;
	var $created_by;
	var $date_entered;
	var $date_modified;
	var $modified_user_id;
	var $active_date;
	var $exp_date;
	var $ecmkpkw_revision_id;
	var $filename;

	var $img_name;
	var $img_name_bare;
	var $related_doc_id;
	var $related_doc_name;
	var $related_doc_rev_id;
	var $related_doc_rev_number;
	var $is_template;
	var $template_type;

	//additional fields.
	var $revision;
	var $last_rev_create_date;
	var $last_rev_created_by;
	var $last_rev_created_name;
	var $file_url;
	var $file_url_noimage;

	var $table_name = "ecmkpkw";
	var $object_name = "EcmKpkw";
	var $user_preferences;

	var $encodeFields = Array ();

	// This is used to retrieve related fields from form posts.
	var $additional_column_fields = Array ('revision');
	
	var $new_schema = true;
	var $module_dir = 'EcmKpkw';
	
	var $save_file;

	var $relationship_fields = Array(
		'contract_id'=>'contracts',
	 );
	  

	function EcmKpkw() {
		parent :: SugarBean();
		$this->setupCustomFields('EcmKpkw'); //parameter is module name
		$this->disable_row_level_security = false;
	}

	function save($check_notify = false) {
		global $current_user;
		$db = $GLOBALS ['db'];
		// global $db;
		$this->number = $this->generateNumber();
        $this->document_no = $this->formatNumber();
		if($this->dir==1){ $this->document_no='KW/'.$this->document_no; } else {
		$this->document_no='KP/'.$this->document_no; 
		}
		
		$value = $this->amount;
		if ($this->dir) {
		  $value = ($this->amount)*-1;
		}
		
		$value = str_replace(",", "", $value);
 
	    $return_id = parent::save($check_notify);
 
 
		if (isset($_REQUEST['record']) && $_REQUEST['record'] != '') {
		 
		  // edytowanie informacji do listy platnosci		
		//  mysql_query("UPDATE `ecmpayments` SET `value`='".($value)."', `parent_name`='".$this->parent_name."', `parent_id`='".$this->parent_id."', `description`='".$this->description."', `created_by`='".$this->created_by."' WHERE `parent_document_id`='".$this->id."'");
		
		} else {
		
		  // dodawanie informacji do listy platnosci		
		 // mysql_query("INSERT INTO `ecmpayments` SET `id`=UUID(), `parent_document_id`='".$return_id."', `name`='".$this->document_no."', `value`='".($value)."', `parent_name`='".$this->parent_name."', `parent_id`='".$this->parent_id."', `description`='".$this->description."', `created_by`='".$this->created_by."'");
		
		}
		
 

		//echo $this->parent_id; exit;
		// $query = "SELECT 
						 // billing_address_street 	AS `street`, 
						 // billing_address_city   	AS `city`,
						 // billing_address_postalcode	AS `postalcode`,
						 // billing_address_country	AS `country`,
						 // index_dbf					AS `indeks`
				  // FROM `accounts`
					
				  // WHERE `id` = '".$this->parent_id."';";
		
		// echo $query; exit;
		// if($row = $db->fetchByAssoc($db->query($query)))
			// {
				// $this->parent_name =				$row["name"];
				// $this->parent_address_street      = $row["street"];
				// $this->parent_address_city        = $row["city"];
				// $this->parent_address_postalcode  = $row["postalcode"];
				// $this->parent_address_country     = $row["country"];
				// $this->index_dbf				  = $row["indeks"];
			// }
		// echo "<pre>".var_export($row,true)."</pre>"; exit;
		
		//echo "<pre>".var_export(array($this->ToArray()),true)."</pre>";
		$res_count = $db->query ( "select id from ecmtransactions where record_id='" . $this->id . "' and deleted='0'" );
		
		$count = $res_count->num_rows;
		$a=$GLOBALS ['db']->query ("SELECT amount from ecmkpkw where id='" . $this->id . "'");
		$r = $GLOBALS ['db']->fetchByAssoc ( $a );
		if ($count == 0) {
	
		//$GLOBALS ['db']->query ("INSERT INTO ecmtransactions(id,name,date_entered,date_modified,modified_user_id,created_by,description,deleted,assigned_user_id,value,parent_name,parent_id,payment_date,type,paid,register_date,record_id,record_type,currency_id,currency_value)VALUES('".create_guid()."','".$this->ecmkpkw_name."','".date("Y-m-d H:i:s")."','".date("Y-m-d H:i:s")."','".$_SESSION['authenticated_user_id']."','".$_SESSION['authenticated_user_id']."','".$this->description."','".$this->deleted"','".$this->assigned_user_id."','".$this->amount."','".$this->parent_name."','".$this->parent_id."','".$this->register_date."','".$this->dir."','1','".$this->date_entered."','".$this->id."','EcmKpkw','".$this->currency_id ."','".$this->currency_value ."')");
		} else {
			//$db->query ( "update ecmtransactions set value=$this->amount where record_id='" . $this->id . "'" );
		}
		
		return parent :: save($check_notify);
	}
    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 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_id = "97700b0d-fbe9-e366-4016-4b260f058a47";
        //$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 get_summary_text() {
		return "$this->ecmkpkw_name";
	}

	function is_authenticated() {
		return $this->authenticated;
	}

	function fill_in_additional_list_fields() {
			// $this->modified_user_fullname = get_assigned_user_name($this->modified_user_id);
		// $this->created_by_fullname = get_assigned_user_name($this->created_by);
		$this->fill_in_additional_detail_fields();
	}

	function fill_in_additional_detail_fields() {
		$this->modified_user_fullname = get_assigned_user_name($this->modified_user_id);
		$this->created_by_fullname = get_assigned_user_name($this->created_by);
		// echo "<pre>".var_export($this->ToArray(),true)."</pre>";
		// exit;
		return;
		global $theme;
		global $current_language;
		global $timedate;
		global $locale;

		parent::fill_in_additional_detail_fields();
		
		$mod_strings = return_module_language($current_language, 'EcmKpkw');

		$query = "SELECT filename,revision,file_ext FROM ecmkpkw_revisions WHERE id='$this->document_revision_id'";

		$result = $this->db->query($query);
		$row = $this->db->fetchByAssoc($result);

		//popuplate filename
        if(isset($row['filename']))$this->filename = $row['filename'];
        //$this->latest_revision = $row['revision'];
        if(isset($row['revision']))$this->revision = $row['revision'];
        
		//populate the file url. 
		//image is selected based on the extension name <ext>_icon_inline, extension is stored in ecmkpkw_revisions.
		//if file is not found then default image file will be used.
		global $img_name;
		global $img_name_bare;
		if (!empty ($row['file_ext'])) {
			$img_name = SugarThemeRegistry::current()->getImageURL(strtolower($row['file_ext'])."_image_inline.gif");
			$img_name_bare = strtolower($row['file_ext'])."_image_inline";
		}

		//set default file name.
		if (!empty ($img_name) && file_exists($img_name)) {
			$img_name = $img_name_bare;
		} else {
			$img_name = "def_image_inline"; //todo change the default image.						
		}
		if($this->ACLAccess('DetailView')){
    		$this->file_url = "<a href='index.php?entryPoint=download&id=".basename(UploadFile :: get_url($this->filename, $this->ecmkpkw_revision_id))."&type=EcmKpkw' target='_blank'>".SugarThemeRegistry::current()->getImage($img_name, 'alt="'.$mod_strings['LBL_LIST_VIEW_DOCUMENT'].'"  border="0"')."</a>";
    		$this->file_url_noimage = basename(UploadFile :: get_url($this->filename, $this->ecmkpkw_revision_id));
		}else{
            $this->file_url = "";
            $this->file_url_noimage = "";
		}
		
		//get last_rev_by user name.
		$query = "SELECT first_name,last_name, ecmkpkw_revisions.date_entered as rev_date FROM users, document_revisions WHERE users.id = document_revisions.created_by and document_revisions.id = '$this->document_revision_id'";
		$result = $this->db->query($query, true, "Eror fetching user name: ");
		$row = $this->db->fetchByAssoc($result);
		if (!empty ($row)) {
			$this->last_rev_created_name = $locale->getLocaleFormattedName($row['first_name'], $row['last_name']);

			$this->last_rev_create_date = $timedate->to_display_date_time($row['rev_date']);
		}
		
		global $app_list_strings;
	    if(!empty($this->status_id)) {
	       //_pp($this->status_id);
	       $this->status = $app_list_strings['ecmkpkw_status_dom'][$this->status_id];
	    }
        $this->related_doc_name = EcmKpkw::get_ecmkpkw_name($this->related_doc_id);
        $this->related_doc_rev_number = EcmKpkwRevision::get_ecmkpkw_revision_name($this->related_doc_rev_id);
        $this->save_file = basename($this->file_url_noimage);
        
	}

	function list_view_parse_additional_sections(& $list_form, $xTemplateSection) {
		return $list_form;
	}

    function create_export_query(&$order_by, &$where, $relate_link_join='')
    {
        $custom_join = $this->custom_fields->getJOIN(true, true,$where);
		if($custom_join)
				$custom_join['join'] .= $relate_link_join;
		$query = "SELECT
						ecmkpkw.*";
		if($custom_join){
			$query .=  $custom_join['select'];
		}
		$query .= " FROM ecmkpkw ";
		if($custom_join){
			$query .=  $custom_join['join'];
		}

		$where_auto = " ecmkpkw.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 ecmkpkw.ecmkpkw_name";

		return $query;
	}

	function get_list_view_data() {
		$this->fill_in_additional_detail_fields();
		// global $current_language;
		// $app_list_strings = return_app_list_strings_language($current_language);

		$ecmkpkw_fields = $this->get_list_view_array();
		// exit;
		// $ecmkpkw_fields['FILE_URL'] = $this->file_url;
		// $ecmkpkw_fields['FILE_URL_NOIMAGE'] = $this->file_url_noimage;
		// $ecmkpkw_fields['LAST_REV_CREATED_BY'] = $this->last_rev_created_name;
		// $ecmkpkw_fields['CATEGORY_ID'] = empty ($this->category_id) ? "" : $app_list_strings['document_category_dom'][$this->category_id];
		// $ecmkpkw_fields['SUBCATEGORY_ID'] = empty ($this->subcategory_id) ? "" : $app_list_strings['document_subcategory_dom'][$this->subcategory_id];
		$ecmkpkw_fields['MODIFIED_USER_ID'] = '<a href="index.php?module=Users&offset=1&return_module=Users&action=DetailView&record='.$this->modified_user_id.'">'.$this->modified_user_fullname.'</a>';
		// $ecmkpkw_fields['DOCUMENT_NAME_JAVASCRIPT'] = $GLOBALS['db']->helper->escape_quote($document_fields['DOCUMENT_NAME']);

		// echo "<pre>".var_export($this->get_list_view_array(),true)."</pre>";
		// exit;
		return $ecmkpkw_fields;
	}
	function mark_relationships_deleted($id) {
		//do nothing, this call is here to avoid default delete processing since  
		//delete.php handles deletion of ecmkpkw revisions.
	}

	function bean_implements($interface) {
		switch ($interface) {
			case 'ACL' :
				return true;
		}
		return false;
	}
	
function createPdfFileName($format = true) {

        $arr1 = array('\\', '/', ':', '*', '?', '"', '<', '>', '|', ' ');

        $arr2 = array('', '', '', '', '', '\'', '[', ']', '', '_');

        $tmp = $this->document_no;

        if ($format) {

            if ($this->type == "normal")
                $tmp = str_replace($arr1, $arr2, 'Invoice_' . $tmp . '.pdf');
            else
            if ($this->type == "correct")
                $tmp = str_replace($arr1, $arr2, 'Correct_' . $tmp . '__to_Invoice_' . $this->ecmkpkw->document_no . '.pdf');
        }
        else
            $tmp = 'Kpkw ' . $tmp . '.pdf';

        //$mod = return_module_language($current_language, 'EcmInvoiceOuts');
        //return urlencode(
//      return $mod['LBL_PDF_INVOICE_FILE_NAME'].$tmp.'.pdf';//);

        return $tmp; //);
    }

	//static function.
	function get_ecmkpkw_name($doc_id){
		if (empty($doc_id)) return null;
		
		$db = DBManagerFactory::getInstance();				
		$query="select ecmkpkw_name from ecmkpkw where id='$doc_id'";
		$result=$db->query($query);
		if (!empty($result)) {
			$row=$db->fetchByAssoc($result);
			if (!empty($row)) {
				return $row['ecmkpkw_name'];
			}
		}
		return null;
	}
	function DrawMainPDF($pdf, $type = null) {
        global $mod_strings;

//        $arr = $this->template->getTemplateFile($_REQUEST['module']);
        //var_dump($type ? : $this->pdf_type); exit;


                include($this->template->getTemplateFile('subheader.php'));
                include($this->template->getTemplateFile('subfooter.php'));

        
        
        //exit;

        return;
    }

    function getPDF($id = null, $method = 'I', $name = null, $type = 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, "EcmKpkw", $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();

        //$type = $_REQUEST['type'];

        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, $type);

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


?>