<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
 * SugarCRM Community Edition is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2013 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".
 ********************************************************************************/

/*********************************************************************************

 * Description:  Defines the Account SugarBean Account entity with the necessary
 * methods and variables.
 ********************************************************************************/

require_once("include/SugarObjects/templates/company/Company.php");

// Account is used to store account information.
class Account extends Company {
	var $field_name_map = array();
	// Stored fields
	var $date_entered;
	var $date_modified;
	var $modified_user_id;
	var $assigned_user_id;
	var $annual_revenue;
	var $billing_address_street;
	var $billing_address_city;
	var $billing_address_state;
	var $billing_address_country;
	var $billing_address_postalcode;

    var $billing_address_street_2;
    var $billing_address_street_3;
    var $billing_address_street_4;

	var $description;
	var $email1;
	var $email2;
	var $email_opt_out;
	var $invalid_email;
	var $employees;
	var $id;
	var $industry;
	var $name;
	var $ownership;
	var $parent_id;
	var $phone_alternate;
	var $phone_fax;
	var $phone_office;
	var $rating;
	var $register_address_street;
	var $register_address_city;
	var $register_address_state;
	var $register_address_country;
	var $register_address_postalcode;
    
    var $register_address_street_2;
    var $register_address_street_3;
    var $register_address_street_4;
    
    var $campaign_id;
    
	var $sic_code;
	var $ticker_symbol;
	var $account_type;
	var $website;
	var $website2;
	var $website3;
	var $custom_fields;

	var $created_by;
	var $created_by_name;
	var $modified_by_name;

	// These are for related fields
	var $opportunity_id;
	var $case_id;
	var $contact_id;
	var $task_id;
	var $note_id;
	var $meeting_id;
	var $call_id;
	var $email_id;
	var $member_id;
	var $parent_name;
	var $assigned_user_name;
	var $account_id = '';
	var $account_name = '';
	var $bug_id ='';
	var $module_dir = 'Accounts';
	var $emailAddress;

	// add mz@bim-it.pl 19.11.2023
	var $index_dbf;
	var $isAllegroUser;
	var $shop_user;
	var $to_vatid;
	var $iln;
	// end mz 


	var $table_name = "accounts";
	var $object_name = "Account";
	var $importable = true;
	var $new_schema = true;
	// This is used to retrieve related fields from form posts.
	var $additional_column_fields = Array('assigned_user_name', 'assigned_user_id', 'opportunity_id', 'bug_id', 'case_id', 'contact_id', 'task_id', 'note_id', 'meeting_id', 'call_id', 'email_id', 'parent_name', 'member_id'
	);
	var $relationship_fields = Array('opportunity_id'=>'opportunities', 'bug_id' => 'bugs', 'case_id'=>'cases',
									'contact_id'=>'contacts', 'task_id'=>'tasks', 'note_id'=>'notes',
									'meeting_id'=>'meetings', 'call_id'=>'calls', 'email_id'=>'emails','member_id'=>'members',
									'project_id'=>'project',
									);

    //Meta-Data Framework fields
    var $push_billing;
    var $push_register;

	function Account() {
        parent::Company();

        $this->setupCustomFields('Accounts');

		foreach ($this->field_defs as $field) 
		{
			if(isset($field['name']))
			{
				$this->field_name_map[$field['name']] = $field;
			}
		}


        //Email logic
		if (!empty($_REQUEST['parent_id']) && !empty($_REQUEST['parent_type']) && $_REQUEST['parent_type'] == 'Emails'
        	&& !empty($_REQUEST['return_module']) && $_REQUEST['return_module'] == 'Emails') {
			$_REQUEST['parent_name'] = '';
			$_REQUEST['parent_id'] = '';
		}
	}

	function get_summary_text()
	{
		return $this->name;
	}

	function get_contacts() {
		return $this->get_linked_beans('contacts','Contact');
	}



	function clear_account_case_relationship($account_id='', $case_id='')
	{
		if (empty($case_id)) $where = '';
		else $where = " and id = '$case_id'";
		$query = "UPDATE cases SET account_name = '', account_id = '' WHERE account_id = '$account_id' AND deleted = 0 " . $where;
		$this->db->query($query,true,"Error clearing account to case relationship: ");
	}

	/**
	* This method is used to provide backward compatibility with old data that was prefixed with http://
	* We now automatically prefix http://
	* @deprecated.
 	*/
	function remove_redundant_http()
	{	/*
		if(preg_match("@http://@", $this->website))
		{
			$this->website = substr($this->website, 7);
		}
		*/
	}

	function fill_in_additional_list_fields()
	{
		parent::fill_in_additional_list_fields();
	// Fill in the assigned_user_name
	//	$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);

	}

	function fill_in_additional_detail_fields()
	{
        parent::fill_in_additional_detail_fields();

        //rrs bug: 28184 - instead of removing this code altogether just adding this check to ensure that if the parent_name
        //is empty then go ahead and fill it.
        if(empty($this->parent_name) && !empty($this->id)){
			$query = "SELECT a1.name from accounts a1, accounts a2 where a1.id = a2.parent_id and a2.id = '$this->id' and a1.deleted=0";
			$result = $this->db->query($query,true," Error filling in additional detail fields: ");

			// Get the id and the name.
			$row = $this->db->fetchByAssoc($result);

			if($row != null)
			{
				$this->parent_name = $row['name'];
			}
			else
			{
				$this->parent_name = '';
			}
        }		
        
        // Set campaign name if there is a campaign id
		if( !empty($this->campaign_id)){
			
			$camp = new Campaign();
		    $where = "campaigns.id='{$this->campaign_id}'";
		    $campaign_list = $camp->get_full_list("campaigns.name", $where, true);
		    $this->campaign_name = $campaign_list[0]->name;
		}
		
		require_once("include/ECM/EcmFormatPhoneNumber/EcmFormatPhoneNumber.php");
		if($_REQUEST['action']=="DetailView"){
			$this->phone_office = EcmFormatPhoneNumber($this->phone_office, "Account", "Accounts", $this->id);
			$this->phone_alternate = EcmFormatPhoneNumber($this->phone_alternate, "Account", "Accounts", $this->id);
		}
		
		//create link to google maps
		global $mod_strings;
		$billing = '<a target="new" href="https://maps.google.com/?q='.$this->billing_address_country.'+'.$this->billing_address_city.'+'.$this->billing_address_street.'">Adres kontaktowy</a>';
		$shippping = '<a target="new" href="https://maps.google.com/?q='.$this->register_address_country.'+'.$this->register_address_city.'+'.$this->register_address_street.'">Adres rejestrowy</a>';
		$this->maps = $billing.'<br>'.$shippping;
	}

	function get_email_addresses($id,$module){
	
		$w=mysql_query("select email_addresses.email_address as addr from email_addresses inner join email_addr_bean_rel on email_addresses.id=email_addr_bean_rel.email_address_id where email_addr_bean_rel.bean_module='".$module."' and email_addr_bean_rel.bean_id='".$id."' and email_addr_bean_rel.deleted='0'");
		while($r=mysql_fetch_array($w)){
			$addrs[]=$r['addr'];
		}
		return $addrs;
	}
	
	function get_list_view_data(){

		$temp_array = parent::get_list_view_data();

		$temp_array["ENCODED_NAME"] = $this->name;

		if(!empty($this->register_address_state))
		{
			$temp_array["CITY"] = $this->register_address_city . ', '. $this->register_address_state;
		}
		else
		{
			$temp_array["CITY"] = $this->register_address_city;
		}
		$temp_array["REGISTER_ADDRESS_CITY"]=$temp_array["CITY"];
		$temp_array["REGISET_ADDRESS_STREET"]  = $this->register_address_street;
		$query = "SELECT register_address_street FROM accounts WHERE id='".$this->id."'";
		$r = $this->db->query($query);

        $result = $this->db->fetchByAssoc($r);
		global $app_list_strings;
		$temp_array["REGISTER_ADDRESS_LIST"] = $result['register_address_street'];

		$temp_array["ACCOUNT_TYPE"] = $app_list_strings['account_type_dom'][$this->account_type];
		
		require_once("include/ECM/EcmFormatPhoneNumber/EcmFormatPhoneNumber.php");
		if($_REQUEST['action']!="Popup"){
			$temp_array['PHONE_OFFICE'] = EcmFormatPhoneNumber($temp_array['PHONE_OFFICE'], "Account", "Accounts", $this->id);
			$temp_array['PHONE_ALTERNATE'] = EcmFormatPhoneNumber($temp_array['PHONE_ALTERNATE'], "Account", "Accounts", $this->id);
		}
    	
		return $temp_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 = $this->db->quote($the_query_string);
	array_push($where_clauses, "accounts.name like '$the_query_string%'");
	if (is_numeric($the_query_string)) {
		array_push($where_clauses, "accounts.phone_alternate like '%$the_query_string%'");
		array_push($where_clauses, "accounts.phone_fax like '%$the_query_string%'");
		array_push($where_clauses, "accounts.phone_office like '%$the_query_string%'");
	}

	$the_where = "";
	foreach($where_clauses as $clause)
	{
		if(!empty($the_where)) $the_where .= " or ";
		$the_where .= $clause;
	}

	return $the_where;
}


        function create_export_query(&$order_by, &$where, $relate_link_join='')
        {
            $custom_join = $this->getCustomJoin(true, true, $where);
            $custom_join['join'] .= $relate_link_join;
                         $query = "SELECT
                                accounts.*,email_addresses.email_address email_address,
                                accounts.name as account_name,
                                users.user_name as assigned_user_name ";
            $query .= $custom_join['select'];
						 $query .= " FROM accounts ";
                         $query .= "LEFT JOIN users
	                                ON accounts.assigned_user_id=users.id ";

						//join email address table too.
						$query .=  ' LEFT JOIN  email_addr_bean_rel on accounts.id = email_addr_bean_rel.bean_id and email_addr_bean_rel.bean_module=\'Accounts\' and email_addr_bean_rel.deleted=0 and email_addr_bean_rel.primary_address=1 ';
						$query .=  ' LEFT JOIN email_addresses on email_addresses.id = email_addr_bean_rel.email_address_id ' ;

            $query .= $custom_join['join'];

		        $where_auto = "( accounts.deleted IS NULL OR accounts.deleted=0 )";

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

                if(!empty($order_by))
                        $query .=  " ORDER BY ". $this->process_order_by($order_by, null);

                return $query;
        }

	function set_notification_body($xtpl, $account)
	{
		$xtpl->assign("ACCOUNT_NAME", $account->name);
		$xtpl->assign("ACCOUNT_TYPE", $account->account_type);
		$xtpl->assign("ACCOUNT_DESCRIPTION", $account->description);

		return $xtpl;
	}

	function bean_implements($interface){
		switch($interface){
			case 'ACL':return true;
		}
		return false;
	}
	function get_unlinked_email_query($type=array()) {

		return get_unlinked_email_query($type, $this);
	}
	function get_unlinked_product_query($type=array()) {
	
	    return get_unlinked_product_query($type, $this);
	}
	//save bank
	function savePositions4($pl) {
	    global $current_user;
	    $exists = array();
	    foreach ($pl as $p) {
	        if (!isset($p['name']) || $p['name']=='') continue;
	        if (isset($p['id']) && $p['id']!='') {
	            //update exists
	            $q = "
				UPDATE account_banks set
					name = '".addslashes($p['name'])."',
					date_modified = '".date("Y-m-d H:i:s")."',
					modified_user_id = '".$current_user->id."',
					account = '".addslashes($p['account'])."',
					position = '".addslashes($p['position'])."',
					WHERE id = '".$p['id']."'
				";
	            $GLOBALS['db']->query($q);
	            $exists[] = $p['id'];
	        } else {
	            //insert new record
	            $id = create_guid();
	            $t = array(
	                    $id,
	                    date("Y-m-d H:i:s"),
	                    $current_user->id,
	                    addslashes($p['account']),
	                    addslashes($p['position']),
	                    addslashes($p['name']),
	                    '0',
	                    $this->id,
	            );
	            $q = "INSERT INTO account_banks VALUES ('".implode("','", $t)."')";
	            $GLOBALS['db']->query($q);
	            $exists[] = $id;
	        }
	    }
	    //delete old
	    $GLOBALS['db']->query("UPDATE account_banks SET deleted='1', modified_user_id='".$current_user->id."',date_modified = '".date("Y-m-d H:i:s")."' WHERE account_id='".$this->id."' AND id NOT IN ('".implode("','",$exists)."')");
	}
	
	
	
		//start managing addresses
	function savePositions($pl) {
		global $current_user;
		$exists = array();
		foreach ($pl as $p) {
			if (!isset($p['name']) || $p['name']=='') continue;
		    if (isset($p['id']) && $p['id']!='') {
				//update exists
				$q = "
				UPDATE account_addresses set
					name = '".addslashes($p['name'])."',
					date_modified = '".date("Y-m-d H:i:s")."',
					modified_user_id = '".$current_user->id."',
					street = '".addslashes($p['street'])."',
					postalcode = '".addslashes($p['postalcode'])."',
					city = '".addslashes($p['city'])."',
					country = '".addslashes($p['country'])."',
					position = '".addslashes($p['position'])."',
					phone = '".addslashes($p['phone'])."',
					fax = '".addslashes($p['fax'])."'
					WHERE id = '".$p['id']."'
				";
				$GLOBALS['db']->query($q);
				$exists[] = $p['id'];				
			} else {
				//insert new record
				$id = create_guid();
					$t = array(
						$id,
						$this->id,
						addslashes($p['name']),
						date("Y-m-d H:i:s"),
						date("Y-m-d H:i:s"),
						$current_user->id,
						$current_user->id,
						addslashes($p['street']),
						addslashes($p['postalcode']),
						addslashes($p['city']),
						addslashes($p['country']),
						addslashes($p['position']),
						'0',
						addslashes($p['phone']),
						addslashes($p['fax']),
					);
				$q = "INSERT INTO account_addresses VALUES ('".implode("','", $t)."')";
				$GLOBALS['db']->query($q);
				$exists[] = $id;
			}
		}
		//delete old
		$GLOBALS['db']->query("UPDATE account_addresses SET deleted='1', modified_user_id='".$current_user->id."',date_modified = '".date("Y-m-d H:i:s")."' WHERE account_id='".$this->id."' AND id NOT IN ('".implode("','",$exists)."')");
	}
    function getPositionList($array = false) {
      if(isset($this->id) && $this->id != '') {
        $query = "SELECT * FROM account_addresses WHERE account_id='".$this->id."' AND deleted='0' ORDER BY position";
		$r = $this->db->query($query);
        $return_array = array();
        if($r) {
		  
          while($w = $this->db->fetchByAssoc($r)) {
            $return_array [] = $w;
          }
          $json = getJSONobj();
          return $array ? $return_array : $json->encode($return_array);
        }
      }
      return $array ? false : '[]';
    }
    
    function getFirstBankAccount(){
        $db=$GLOBALS['db'];
        $query = "SELECT account FROM account_banks WHERE account_id='".$this->id."' AND deleted='0' ORDER BY position desc";
        $r = $db->query($query);
      
        $w = $db->fetchByAssoc($r);
      
        return $w['account'];
 
    }
    
    function getPositionList4($array = false) {
        if(isset($this->id) && $this->id != '') {
            $query = "SELECT * FROM account_banks WHERE account_id='".$this->id."' AND deleted='0' ORDER BY position";
            $r = $this->db->query($query);
            $return_array = array();
            if($r) {
    
                while($w = $this->db->fetchByAssoc($r)) {
                    $return_array [] = $w;
                }
                $json = getJSONobj();
                return $array ? $return_array : $json->encode($return_array);
            }
        }
        return $array ? false : '[]';
    }
    
    function getTelephonesList($array = false) {
    	if(isset($this->id) && $this->id != '') {
    		$query = "SELECT * FROM accounts_telephones WHERE account_id='".$this->id."' AND deleted='0' ORDER BY position";
    		$r = $this->db->query($query);
    		$return_array = array();
    		if($r) {
    
    			while($w = $this->db->fetchByAssoc($r)) {
    				$return_array [] = $w;
    			}
    			$json = getJSONobj();
    			return $array ? $return_array : $json->encode($return_array);
    		}
    	}
    	return $array ? false : '[]';
    }
    
    function getWebSitesList($array = false) {
        if(isset($this->id) && $this->id != '') {
            $query = "SELECT * FROM accounts_websites WHERE account_id='".$this->id."' AND deleted='0' ORDER BY position";
            $r = $this->db->query($query);
            $return_array = array();
            if($r) {
        
                while($w = $this->db->fetchByAssoc($r)) {
                    $return_array [] = $w;
                }
                $json = getJSONobj();
                return $array ? $return_array : $json->encode($return_array);
            }
        }
        return $array ? false : '[]';
    }
    function ShowWebSitesList($array = false) {
        if(isset($this->id) && $this->id != '') {
            $query = "SELECT * FROM accounts_websites WHERE account_id='".$this->id."' AND deleted='0' ORDER BY position";
            $r = $this->db->query($query);
            $return_array = array();
            if($r) {
    
                while($w = $this->db->fetchByAssoc($r)) {
                    $return_array [] = $w;
                }
                $json = getJSONobj();
                return $array ? $return_array : $return_array;
            }
        }
        return $array ? false : '[]';
    }
    
    function ShowTelephonesList($array = false) {
    	if(isset($this->id) && $this->id != '') {
    		$query = "SELECT * FROM accounts_telephones WHERE account_id='".$this->id."' AND deleted='0' ORDER BY position";
    		$r = $this->db->query($query);
    		$return_array = array();
    		if($r) {
    
    			while($w = $this->db->fetchByAssoc($r)) {
    				$return_array [] = $w;
    			}
    			$json = getJSONobj();
    			return $array ? $return_array : $return_array;
    		}
    	}
    	return $array ? false : '[]';
    }
    
    function saveTelephonesList($pl) {
    	global $current_user;
    	$exists = array();
    	foreach ($pl as $p) {
    		if (!isset($p['telephone']) || $p['telephone']=='') continue;
    		if (isset($p['id']) && $p['id']!='') {
    			//update exists
    			$q = "
				UPDATE accounts_telephones set
					telephone = '".addslashes($p['telephone'])."',
					date_modified = '".date("Y-m-d H:i:s")."',
					modified_user_id = '".$current_user->id."'
					WHERE id = '".$p['id']."'
				";
    			$GLOBALS['db']->query($q);
    			$exists[] = $p['id'];
    		} else {
    			//insert new record
    			$id = create_guid();
    			$t = array(
    					$id,
    					$this->id,
    					'0',
    					date("Y-m-d H:i:s"),
    					'0',
    					addslashes($p['telephone']),
    					'0',
    					date("Y-m-d H:i:s"),
    					$current_user->id,
    			);
    			$q = "INSERT INTO accounts_telephones VALUES ('".implode("','", $t)."')";
    			 
    			$GLOBALS['db']->query($q);
    			$exists[] = $id;
    		}
    	}
    	//delete old
    	$GLOBALS['db']->query("UPDATE accounts_telephones SET deleted='1', modified_user_id='".$current_user->id."',date_modified = '".date("Y-m-d H:i:s")."' WHERE account_id='".$this->id."' AND id NOT IN ('".implode("','",$exists)."')");
    }
    
    function saveWebSitesList($pl) {
        global $current_user;
        $exists = array();
        foreach ($pl as $p) {
            if (!isset($p['www']) || $p['www']=='' || $p['www']=='http://') continue;
            if (isset($p['id']) && $p['id']!='') {
                //update exists
                $q = "
				UPDATE accounts_websites set
					www = '".addslashes($p['www'])."',
					date_modified = '".date("Y-m-d H:i:s")."',
					modified_user_id = '".$current_user->id."'
					WHERE id = '".$p['id']."'
				";
                $GLOBALS['db']->query($q);
                $exists[] = $p['id'];
            } else {
                //insert new record
                $id = create_guid();
                $t = array(
                        $id,
                        $this->id,
                        '0',
                        date("Y-m-d H:i:s"),
                        '0',
                        addslashes($p['www']),
                         '0',
                        date("Y-m-d H:i:s"),
                        $current_user->id,
                );
                $q = "INSERT INTO accounts_websites VALUES ('".implode("','", $t)."')";
           
                $GLOBALS['db']->query($q);
                $exists[] = $id;
            }
        }
        //delete old
        $GLOBALS['db']->query("UPDATE accounts_websites SET deleted='1', modified_user_id='".$current_user->id."',date_modified = '".date("Y-m-d H:i:s")."' WHERE account_id='".$this->id."' AND id NOT IN ('".implode("','",$exists)."')");
    }

	function showPositions(){
		$arr=$this->getPositionList(true);
		global $mod_strings;
		if(count($arr)>0){
						$table='
			<table cellpadding="0" cellspacing="0" border="0" class="list view">
			<tr class="oddListRowS1">
				<th><b>'.$mod_strings['LBL_ADDRESS_POSITION'].'</b></td>
				<th><b>'.$mod_strings['LBL_ADDRESS_NAME'].'</b></td>
				<th><b>'.$mod_strings['LBL_ADDRESS_STREET'].'</b></td>
				<th><b>'.$mod_strings['LBL_ADDRESS_CITY'].'</b></td>
				<th><b>'.$mod_strings['LBL_ADDRESS_POSTALCODE'].'</b></td>
				<th><b>'.$mod_strings['LBL_ADDRESS_COUNTRY'].'</b></td>
				<th><b>'.$mod_strings['LBL_ADDRESS_NIP'].'</b></td>
				<th><b>'.$mod_strings['LBL_ADDRESS_ILn'].'</b></td>
			</tr>
			';
			$i == 0;
			foreach($arr as $a){
				$i++;
				//create link to google map
				$name = '<a target="new" href="https://maps.google.com/?q='.$a['country'].'+'.$a['city'].'+'.$a['street'].'">'.$a['name'].'</a>';
				$table.='
				<tr class="oddListRowS1">
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['position'].'</td>
				
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$name.'</td>
					
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['street'].'</td>
					
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['city'].'</td>
					
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['postalcode'].'</td>
					
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['country'].'</td>
					
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['phone'].'</td>
					
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['fax'].'</td>
				';	
			}
			$table.='</table>';
		}
		
		return $table;
	}
	
	function showPositions4(){
	    $arr=$this->getPositionList4(true);
	    global $mod_strings;
	    if(count($arr)>0){
	        $table='
			<table cellpadding="0" cellspacing="0" border="0" class="list view">
			<tr class="oddListRowS1">
				<th><b>'.$mod_strings['LBL_BANK_POSITION'].'</b></td>
				<th><b>'.$mod_strings['LBL_BANK_NAME'].'</b></td>
				<th><b>'.$mod_strings['LBL_BANK_ACCOUNT'].'</b></td>
			</tr>
			';
	        $i == 0;
	        foreach($arr as $a){
	            $i++;
	            //create link to google map
	            $table.='
				<tr class="oddListRowS1">
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['position'].'</td>
	
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['name'].'</td>
			
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['account'].'</td>
			
				';
	        }
	        $table.='</table>';
	    }
	
	    return $table;
	}
	
	function getAddresses($account_id) {
		
		$db = $GLOBALS['db'];
		
		$res = $db->query("SELECT id, name FROM account_addresses WHERE account_id='$account_id' AND deleted='0' ORDER BY position");
		
		if ($res->num_rows==0) return 0;
		//echo "SELECT id, name FROM account_addresses WHERE account_id='$account_id' ORDER BY position";
		$options = '<select id="address_id" onchange="getAddress();">';
		$options .= '<option value=\'\'></option>';
		while ($row = $db->fetchByAssoc($res)) {
			$options.='<option value="'.$row['id'].'">'.$row['name'].'</option>';
		}
		$options.='</select>';
		
		return $options;
	}
	
	function getPayers($account_id) {
		
		$db = $GLOBALS['db'];
		
		$res = $db->query("SELECT id, name FROM account_addresses WHERE account_id='$account_id' AND deleted='0' ORDER BY position");
		
		if ($res->num_rows==0) return 0;
		//echo "SELECT id, name FROM account_addresses WHERE account_id='$account_id' ORDER BY position";
		$options = '<select id="address_id" onchange="getPayer();">';
		$options .= '<option value=\'\'></option>';
		while ($row = $db->fetchByAssoc($res)) {
			$options.='<option value="'.$row['id'].'">'.$row['name'].'</option>';
		}
		$options.='</select>';
		
		return $options;
	}
	
	function getAddress($id) {
	
		$db = $GLOBALS['db'];
		
		$row = $db->fetchByAssoc($db->query("SELECT name as description , street, postalcode, city, country,phone,fax FROM account_addresses WHERE id='$id'"));
		
		$ret[] = $row;

		return $ret;
		
	}
	//end managing addresses
	
	//start managing discounts
	function savePositions2($pl) {
		global $current_user;
		$exists = array();
		foreach ($pl as $p) {
			if (!isset($p['ecmproductcategory_id']) || $p['ecmproductcategory_id']=='') continue;
			if (!isset($p['discount']) || $p['discount']=='' || floatval($p['discount'])==0) continue;
		    if (isset($p['id']) && $p['id']!='') {
				//update exists
					$q = "
				UPDATE accounts_discounts set
					date_modified = '".date("Y-m-d H:i:s")."',
					modified_user_id = '".$current_user->id."',					
					account_id = '".addslashes($this->id)."',
					discount = '".addslashes($p['discount'])."',
					ecmproductcategory_id = '".addslashes($p['ecmproductcategory_id'])."',
					ecmproductcategory_name = '".addslashes($p['ecmproductcategory_name'])."'
					WHERE id = '".$p['id']."'
				";
				
				//$GLOBALS['db']->query("INSERT INTO log VALUES ('".addslashes($q)."')");
				$GLOBALS['db']->query($q);
				$exists[] = $p['id'];
				
			} else {
				//insert new record
				$id = create_guid();
					$t = array(
						$id,
						$this->id,
						addslashes($p['ecmproductcategory_id']),
						addslashes($p['discount']),
						date("Y-m-d H:i:s"),
						$current_user->id,
						'0',
					        addslashes($p['ecmproductcategory_name'])
					);
				$q = "INSERT INTO accounts_discounts VALUES ('".implode("','", $t)."')";
				$GLOBALS['db']->query($q);
				$exists[] = $id;
			}
			
		}
		//delete old
		$GLOBALS['db']->query("UPDATE accounts_discounts SET deleted='1', modified_user_id='".$current_user->id."',date_modified = '".date("Y-m-d H:i:s")."' WHERE account_id='".$this->id."' AND id NOT IN ('".implode("','",$exists)."')");
	}
	
    function getPositionList2($array = false) {
      if(isset($this->id) && $this->id != '') {
        $query = "SELECT * FROM accounts_discounts WHERE account_id='".$this->id."' AND deleted='0'";
		
		$r = $this->db->query($query);
        $return_array = array();
        if($r) {
		  
          while($w = $this->db->fetchByAssoc($r)) {
            $return_array [] = $w;
          }
          $json = getJSONobj();
		  
          return $array ? $return_array : $json->encode($return_array);
        }
      }
      return $array ? false : '[]';
    }
	function showPositions2(){
		$arr=$this->getPositionList2(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_PRODUCT_GROUP'].'</b></td>
				<th><b>'.$mod_strings['LBL_DISCOUNT'].'</b></td>
			</tr>
			';
			$i == 0;
			foreach($arr as $a){
				$i++;
				$table.='
				<tr class="oddListRowS1">
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.$a['ecmproductcategory_name'].'</td>
				
					<td valign="top" class="oddListRowS1" style="padding:5px !important;border-bottom:1px solid #cccccc;vertical-align:top;">'.format_number($a['discount']).'</td>
	
				';	
			}
			$table.='</table>';
		}
		
		return $table;
	}
	
	//start managing categories
	function savePositions3($pl) {
		global $current_user;
		$exists = array();
		
		//$GLOBALS['db']->query("INSERT INTO log VALUES ('".addslashes(json_encode($pl))."')");
		foreach ($pl as $p) {
			if (!isset($p['ecmaccountcategory_id']) || $p['ecmaccountcategory_id']=='') continue;
			if (isset($p['id']) && $p['id']!='') {
				//update exists
				$q = "
				UPDATE ecmaccountcategories_bean set
					date_modified = '".date("Y-m-d H:i:s")."',
					modified_user_id = '".$current_user->id."',
					bean_id = '".addslashes($this->id)."',
					ecmaccountcategory_id = '".addslashes($p['ecmaccountcategory_id'])."'
					WHERE id = '".$p['id']."'
				";
				
				//$GLOBALS['db']->query("INSERT INTO log VALUES ('".addslashes($q)."')");
				$GLOBALS['db']->query($q);
				$exists[] = $p['id'];
				
			} else {
				//insert new record
				$id = create_guid();
				$t = array(
						$id,
						addslashes($p['ecmaccountcategory_id']),
						$this->id,
						"Accounts",
						date("Y-m-d H:i:s"),
						date("Y-m-d H:i:s"),
						$current_user->id,
						$current_user->id,
						'0'
				);
				$q = "INSERT INTO ecmaccountcategories_bean VALUES ('".implode("','", $t)."')";
				$GLOBALS['db']->query($q);
				$exists[] = $id;
			}
			
		}
		//delete old
		$GLOBALS['db']->query("UPDATE ecmaccountcategories_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 ecmaccountcategories_bean WHERE bean_id='".$this->id."' AND deleted='0' AND bean_name='Accounts'";
			
			$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 ecmaccountcategories WHERE id='".$w['ecmaccountcategory_id']."'"));
					$w['ecmaccountcategory_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/EcmAccountCategories/files/'.$a['assigned_file'].'"/>';
						else
							$af = '<a href="modules/EcmAccountCategories/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=EcmAccountCategories&action=DetailView&record='.$a['ecmaccountcategory_id'].'">'.$a['ecmaccountcategory_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
	
	function AddGoogleContact() {
		global $current_user;
		if (!$current_user->google_login || $current_user->google_login=='' || !$current_user->google_p || $current_user->google_p=='') return -1; 
		
		require_once 'Zend/Loader.php';
		Zend_Loader::loadClass('Zend_Gdata');
		Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
		Zend_Loader::loadClass('Zend_Http_Client');
		Zend_Loader::loadClass('Zend_Gdata_Query');
		Zend_Loader::loadClass('Zend_Gdata_Feed');
		
		try {
			// perform login and set protocol version to 3.0
			$client = Zend_Gdata_ClientLogin::getHttpClient($current_user->google_login, $current_user->google_p, 'cp');
			
			$gdata = new Zend_Gdata($client);
			$gdata->setMajorProtocolVersion(3);
			
			//return serialize($gdata);
			
			// create new entry
			$doc  = new DOMDocument();
			$doc->formatOutput = true;
			$entry = $doc->createElement('atom:entry');
			$entry->setAttributeNS('http://www.w3.org/2000/xmlns/' , 'xmlns:atom', 'http://www.w3.org/2005/Atom');
			$entry->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:gd', 'http://schemas.google.com/g/2005');
			$doc->appendChild($entry);
			
			// add name element
			$name = $doc->createElement('gd:name');
			$entry->appendChild($name);
			$fullName = $doc->createElement('gd:fullName', $this->name);
			$name->appendChild($fullName);
  
			// add email element
			$email = $doc->createElement('gd:email');
			$email->setAttribute('address' ,$this->emailAddress->getPrimaryAddress($this));
			$email->setAttribute('rel' ,'http://schemas.google.com/g/2005#home');
			$entry->appendChild($email);
  
			// add org name element
			$org = $doc->createElement('gd:organization');
			$org->setAttribute('rel' ,'http://schemas.google.com/g/2005#work');
			$entry->appendChild($org);
			$orgName = $doc->createElement('gd:orgName', $this->name);
			$org->appendChild($orgName);
			
			if ($this->phone_office) {
				$phone = $doc->createElement('gd:phoneNumber', $this->phone_office);
				$phone->setAttribute('rel' ,'http://schemas.google.com/g/2005#work');
				$entry->appendChild($phone);
				//$phoneName = $doc->createElement('gd:phoneNumberName', $this->phone_office);
				//$phone->appendChild($phoneName);
			}
			// insert entry
			$entryResult = $gdata->insertEntry($doc->saveXML(), 'https://www.google.com/m8/feeds/contacts/default/full');
			
			return 1;
		} catch (Exception $e) {
			//return 4;
			return $e->getMessage();
			//return 0;
	}
		return 1;
	}	
	
	
	function getSalda($expired) {
		$db = $GLOBALS ['db'];
	
	$saldo = false;
	$settled = " t.settled!='1' AND ";
	
	switch ($expired) {
		case 0 :
			$payment_date = "1=1";
			break;
		case 1 :
			$date = new DateTime ( date ( "Y-m-d" ) );
			$d = $date->format ( 'Y-m-d' );
			$payment_date = " payment_date <= '$d'";
			$saldo=true;
			break;
		case 2 :
			$date_to = new DateTime ( date ( "Y-m-d" ) );
			$d_t = $date_to->format ( 'Y-m-d' );
			$date_from = new DateTime ( date ( "Y-m-d" ) );
			$date_from->modify ( '-30 days' );
			$d_f = $date_from->format ( 'Y-m-d' );
			$payment_date = " payment_date > '$d_f' AND payment_date < '$d_t'";
			break;
		case 3 :
			$date_to = new DateTime ( date ( "Y-m-d" ) );
			$date_to->modify ( '-31 days' );
			$d_t = $date_to->format ( 'Y-m-d' );
			$date_from = new DateTime ( date ( "Y-m-d" ) );
			$date_from->modify ( '-60 days' );
			$d_f = $date_from->format ( 'Y-m-d' );
			$payment_date = " payment_date > '$d_f' AND payment_date < '$d_t'";
			break;
		case 4 :
			$date_to = new DateTime ( date ( "Y-m-d" ) );
			$date_to->modify ( '-61 days' );
			$d_t = $date_to->format ( 'Y-m-d' );
			$date_from = new DateTime ( date ( "Y-m-d" ) );
			$date_from->modify ( '-90 days' );
			$d_f = $date_from->format ( 'Y-m-d' );
            $payment_date = " payment_date > '$d_f' AND payment_date < '$d_t'";
			break;
		case 5 :
			$date_to = new DateTime ( date ( "Y-m-d" ) );
			$date_to->modify ( '-91 days' );
			$d_t = $date_to->format ( 'Y-m-d' );
			$date_from = new DateTime ( date ( "Y-m-d" ) );
			$date_from->modify ( '-180 days' );
			$d_f = $date_from->format ( 'Y-m-d' );
		    $payment_date = " payment_date > '$d_f' AND payment_date < '$d_t'";
			break;
		case 6 :
			$date = new DateTime ( date ( "Y-m-d" ) );
			$date->modify ( '-181 days' );
			$d = $date->format ( 'Y-m-d' );
			$payment_date = " payment_date < '$d'";
			break;
		case 7 :
			$date = new DateTime ( date ( "Y-m-d" ) );
			$d = $date->format ( 'Y-m-d' );
			$payment_date = " payment_date >= '$d'";
			break;
		case 8 :
			$payment_date = " 1=1 ";
			$saldo = true;
			$settled = " 1=1 and";
			break;
		case 9:
			$date = new DateTime ( date ( "Y-m-d" ) );
			$d = $date->format ( 'Y-m-d' );
			$payment_date = " payment_date <= '$d'";
			$settled = " 1=1 AND ";
			$saldo = true;
			break;
	}


	//start WINIEN
	$r = $db->fetchByAssoc ( $db->query ( "
			SELECT 
				sum(
				t.value
				) AS sum
			FROM ecmtransactions AS t
			WHERE
				t.parent_id = '$this->id' AND
				t.deleted='0' AND
				" .$settled. "
				t.type='1' AND
				" . $payment_date . "
	" ) );

	//get part settled transactions
	/*
	if (!$saldo){
	$s = $db->fetchByAssoc($db->query("
			SELECT 
				sum(
					CASE WHEN t.currency_id='PLN' THEN t.value 
					ELSE t.value*t.currency_value
					END
				) AS sum
			FROM ecmtransactions AS t
			WHERE
				t.parent_id = '$id' AND
				t.deleted='0' AND
				" .$settled. "
				t.type='0' AND
				t.register_date > '2011-12-31' AND
				" . $payment_date . "
	
	"));

	}
	*/
	if (!$saldo){
	   return $r['sum'];
	}
	if (! is_numeric ( $r ['sum'] ))
		$r ['sum'] = 0;
	
	if (! is_numeric ( $s ['settled'] ))
		$s ['settled'] = 0;
	
	if (floatval($s['settled']) > 0) 
		$r['sum'] = floatval($r['sum']) - floatval($s['settled']);
	
	$sum = $r['sum'];
	//END WINIEN
	
	$r['sum'] = 0;
	if ($saldo) {
		$r = $db->fetchByAssoc ( $db->query ( "
			SELECT
				sum(
					t.value
				) AS sum
			FROM ecmtransactions AS t
			WHERE
				t.parent_id = '$this->id' AND
				t.deleted='0' AND
		        " .$settled. "
				t.type='0' AND
				" . $payment_date . "
		" ) );
	}
	$res=$sum - $r ['sum'];
	if($expired==1 && $res>0){
	    return 0;
	}
	//END MA
	return $res;
	}
	
	function create_new_list_query($order_by, $where, $filter = array(), $params = array(), $show_deleted = 0, $join_type = '', $return_array = false, $parentbean = null, $singleSelect = false) {
		global $current_user;
		$ret_array = parent::create_new_list_query($order_by, $where, $filter, $params, $show_deleted, $join_type, $return_array, $parentbean, $singleSelect);

		$ret_array['where'] = str_replace("(accounts.without_history = '" . $current_user->id . "')", "
			 accounts.id NOT IN (select parent_id from tasks where parent_type = 'Accounts' AND parent_id != '')
			AND accounts.id NOT IN (select parent_id from meetings where parent_type = 'Accounts' AND parent_id != '')
			AND accounts.id NOT IN (select parent_id from calls where parent_type = 'Accounts' AND parent_id != '')
			AND accounts.id NOT IN (select parent_id from notes where parent_type = 'Accounts' AND parent_id != '')
			AND accounts.id NOT IN (select parent_id from emails where parent_type = 'Accounts' AND parent_id != '')", $ret_array['where']);
		return $ret_array;
	}
}
