<?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 icensed Software
 * d) Assert any patent clais against the Licensor or Contributors, or
 *    which would in any wa 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');
  
  class EcmGroupSale 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;
    var $description;

    //TABLE COLUMNS 


    // 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        = "EcmGroupSales";
    var $table_name        = "ecmgroupsales";
    var $object_name       = "EcmGroupSale";

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

    //RELATIONSHIP FIELDS 
    var $relationship_fields = Array (
    );

    function EcmGroupSale() {
      parent::SugarBean();
      $this->setupCustomFields('EcmGroupSales');
      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  .= "ecmgroupsales.*
                 ,users.user_name as assigned_user_name";
      if($custom_join) {
        $query .= $custom_join['select'];
      }
      $query   .= " FROM ecmgroupsales 
                   LEFT JOIN users
                   ON ecmgroupsales.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 ecmgroupsales.name";

      return $query;
    }
	
    function create_export_query($order_by, $where) {

      $custom_join = $this->custom_fields->getJOIN();
      $query       = "SELECT
                      ecmgroupsales.*,
                      users.user_name assigned_user_name";
      if($custom_join) {
        $query .=  $custom_join['select'];
      }
      $query   .= " FROM ecmgroupsales ";
      $query   .= " LEFT JOIN users
                  ON ecmgroupsales.assigned_user_id=users.id";
      if($custom_join) {
        $query .=  $custom_join['join'];
      }
      $query   .= "";
      $where_auto = " ecmgroupsales.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 ecmgroupsales.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);
    }

  

    function get_list_view_data(){
      global $current_language;
      $this->fill_in_additional_detail_fields();
      $app_list_strings = return_app_list_strings_language($current_language);
      $mod_strings      = return_module_language($current_language, 'EcmGroupSales');
      $the_array        = parent::get_list_view_data();
      // 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);
      $the_array['FORMATTED_NUMBER'] =  $this->formatted_number;
      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::groupsale(from_html($the_query_string));
      array_push($where_clauses, "ecmgroupsales.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("DESCRIPTION", $simplemodule->description);
      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);
      return $return_id;
    }


    static function getPositionList($table, $first_empty = false) {
      $query = "select `id`,`name` from `$table` where `deleted`='0' order by `name`";
      $result = $GLOBALS['db']->query($query);
      $arr = array();
	  if($first_empty) $arr[''] = ' ';
      if($result)
        while($row = $GLOBALS['db']->fetchByAssoc($result))
          $arr[$row['id']] = $row['name'];
      return $arr;
    } 

	static function saveSettings($array) {
	
		global $current_user;

		//save admin settings
		if(is_admin($current_user)) {
			$arr = array(
				'default_payment_condition' => $array['default_payment_condition'],
				'default_delivery_condition' => $array['default_delivery_condition'],
				'default_document_template' => $array['default_document_template'],
				'default_representative_role_id' => $array['default_representative_role_id'],
				'default_representative_extra_role_id' => $array['default_representative_extra_role_id'],
				'default_manager_role_id' => $array['default_manager_role_id'],
				'checkbox_demo' => ((isset($array['checkbox_demo']) && $array['checkbox_demo'] != '')?1:0),
				'show_images_on_offers' => ((isset($array['show_images_on_offers']) && $array['show_images_on_offers'] != '')?1:0),
				'creating_invoice_direct_from_quote' => ((isset($array['creating_invoice_direct_from_quote']) && $array['creating_invoice_direct_from_quote'] != '')?1:0),
				'rows_on_item_list_global'=>$array['rows_on_item_list_global'],
				'row_item_height_global'=>$array['row_item_height_global'],
				'row_item_height_selected_global'=>$array['row_item_height_selected_global'],
				'quick_product_item_adding_global'=>((isset($array['quick_product_item_adding_global']) && $array['quick_product_item_adding_global'] != '')?1:0),
				'show_pdf_in_div_global'=>((isset($array['show_pdf_in_div_global']) && $array['show_pdf_in_div_global'] != '')?1:0),
			);
			$str = "<?php\n\$ecmgroupsales_config = ".var_export($arr,true).";\n?>";
			$config = fopen("modules/EcmGroupSales/config.php", "w");
			fwrite($config,$str);
			fclose($config);
		}
		
		//save user settings
		if(!isset($array['rows_on_item_list']) || $array['rows_on_item_list'] == '') $array['rows_on_item_list'] = 6;
		$current_user->setPreference('rows_on_item_list', $array['rows_on_item_list'], 0, 'global', $current_user);
		
		if(!isset($array['row_item_height']) || $array['row_item_height'] == '') $array['row_item_height'] = 35;
		$current_user->setPreference('row_item_height', $array['row_item_height'], 0, 'global', $current_user);
		
		if(!isset($array['row_item_height_selected']) || $array['row_item_height_selected'] == '') $array['row_item_height_selected'] = 70;
		$current_user->setPreference('row_item_height_selected', $array['row_item_height_selected'], 0, 'global', $current_user);

  		if(isset($array['quick_product_item_adding']) && $array['quick_product_item_adding'])
			$current_user->setPreference('quick_product_item_adding', 1, 0, 'global', $current_user);
		else
			$current_user->setPreference('quick_product_item_adding', 0, 0, 'global', $current_user);
			
		//added 23.02.2009 michal
  		if(isset($array['show_pdf_in_div']) && $array['show_pdf_in_div'])
			$current_user->setPreference('show_pdf_in_div', 1, 0, 'global', $current_user);
		else
			$current_user->setPreference('show_pdf_in_div', 0, 0, 'global', $current_user);
			
		$current_user->setPreference('settings_user_save', 1, 0, 'global', $current_user);
		
	}

	static function loadSettings($user_roles = false) {
		$arr = array();
		error_reporting(0);
		$file = 'modules/EcmGroupSales/config.php';
		if(file_exists($file)) {
			include($file);
			if(isset($ecmgroupsales_config)) $arr = $ecmgroupsales_config;
			
			if(is_array($arr['default_representative_role_id']))       $arr['default_representative_role_id'] = array_values($arr['default_representative_role_id']);
			if(is_array($arr['default_representative_extra_role_id'])) $arr['default_representative_extra_role_id'] = array_values($arr['default_representative_extra_role_id']);
			if(is_array($arr['default_manager_role_id']))               $arr['default_manager_role_id'] = array_values($arr['default_manager_role_id']);
			
			if(!isset($arr['checkbox_demo'])) $arr['checkbox_demo'] = 0;
			if(!isset($arr['show_images_on_offers'])) $arr['show_images_on_offers'] = 0;
			if(!isset($arr['creating_invoice_direct_from_quote'])) $arr['creating_invoice_direct_from_quote'] = 0;
		}	
		
		global $current_user;
		
		$user_opt = $current_user->getPreference('rows_on_item_list');
		if(!$user_opt || $user_opt == 0 || $user_opt == '') $user_opt = 6;
		$arr['rows_on_item_list'] = $user_opt;
		
		$user_opt = $current_user->getPreference('row_item_height');
		if(!$user_opt || $user_opt == 0 || $user_opt == '') $user_opt = 35;
		$arr['row_item_height'] = $user_opt;
		
		$user_opt = $current_user->getPreference('row_item_height_selected');
		if(!$user_opt || $user_opt == 0 || $user_opt == '') $user_opt = 70;
		$arr['row_item_height_selected'] = $user_opt;
		
		$user_opt = $current_user->getPreference('quick_product_item_adding');
		if(!$user_opt || $user_opt == 0 || $user_opt == '') $user_opt = 0;
		$arr['quick_product_item_adding'] = $user_opt;
		
		$show_pdf = $current_user->getPreference('show_pdf_in_div');
		if(!$show_pdf || $show_pdf == 0 || $show_pdf == '') $show_pdf = 0;
		$arr['show_pdf_in_div'] = $show_pdf;
		
		$arr['settings_user_save']=$current_user->getPreference('settings_user_save');
		
		if($user_roles == true) {
		
			$arr['user_roles'] = EcmGroupSale::getUserRole($current_user->id);

			//is manager role
			$arr_tmp = array_diff($arr['default_manager_role_id'],$arr['user_roles']);
			if(is_array($arr_tmp)) $arr['user_manager_role'] = count($arr_tmp) < count($arr['default_manager_role_id']);

			//is representative role
			$arr_tmp = array_diff($arr['default_representative_role_id'],$arr['user_roles']);
			if(is_array($arr_tmp)) $arr['user_representative_role'] = count($arr_tmp) < count($arr['default_representative_role_id']);

			//is representative extra role
			$arr_tmp = array_diff($arr['default_representative_extra_role_id'],$arr['user_roles']);
			if(is_array($arr_tmp)) $arr['user_representative_extra_role'] = count($arr_tmp) < count($arr['default_representative_extra_role_id']);
			
		}
		
		return $arr;
	}
	
	static function getUserRole($id) {
		$arr = array();
		$query = "SELECT role_id FROM acl_roles_users WHERE user_id='$id' AND deleted='0'";
		$result = $GLOBALS['db']->query($query);
		if($result) {
			while($row = $GLOBALS['db']->fetchByAssoc($result))
				if($row && isset($row['role_id']) && $row['role_id'] != '') $arr[] = $row['role_id'];
		} 
		return $arr;
	}
	
  }

?>