<?php
/**
 * MassUpdate for ListViews
 *
 * The contents of this file are subject to the SugarCRM Public License Version
 * 1.1.3 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by SugarCRM" logo and
 *    (ii) the SugarCRM copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: SugarCRM Open Source
 * The Initial Developer of the Original Code is SugarCRM, Inc.
 * Portions created by SugarCRM are Copyright (C) 2004-2005 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 */

// $Id: MassUpdate.php,v 1.44 2005/09/22 21:28:02 roger Exp $

require_once('include/JSON.php');

class MassUpdate
{
	var $sugarbean = null;

	function setSugarBean(&$sugar)
	{
		$this->sugarbean = $sugar;
	}

	function getDisplayMassUpdateForm($bool)
	{
		require_once('include/formbase.php');
		
		$form = '<form action="index.php" method="post" name="displayMassUpdate">' . "\n";
		
		if($bool)
		{
			$form .= '<input type="hidden" name="mu" value="false" />' . "\n";
		}
		else
		{
			$form .= '<input type="hidden" name="mu" value="true" />' . "\n";
		}
		
		$form .= getAnyToForm('mu');
		$form .= "</form>\n";
		
		return $form;
	}

	function getMassUpdateFormHeader()
	{
		return "<script type=\"text/javascript\" src=\"include/javascript/popup_parent_helper.js\"></script>\n"
			. "<form action='index.php' method='post' name='MassUpdate' onsubmit=\"return check_form('MassUpdate');\">\n"
			. "<input type='hidden' name='module' value='{$_REQUEST['module']}' />\n"
			. "<input type='hidden' name='action' value='index' />\n"
			. "<input type='hidden' name='massupdate' value='true' />\n"
			. "<input type='hidden' name='delete' value='false' />\n";
	}

function handleMassUpdate(){
	require_once('include/formbase.php');
	global $current_user;
	
	
	foreach($_POST as $post=>$value){
			if(empty($value)){
				unset($_POST[$post]);
			}
	}
	if(isset($_POST['mass']) && is_array($_POST['mass'])){
	foreach($_POST['mass'] as $id){
		if(isset($_POST['Delete'])){
			$this->sugarbean->mark_deleted($id);
		}
		else if(isset($_POST['Sync'])){
			$this->sugarbean->retrieve($id);
			if($this->sugarbean->object_name == 'Contact'){
			 		$this->sugarbean->contacts_users_id = $current_user->id;
			 		$this->sugarbean->save(false);
			}		
		}
		else if(isset($_POST['Unsync'])){
			$this->sugarbean->retrieve($id);
			if($this->sugarbean->object_name == 'Contact'){
			 		if (!isset($this->sugarbean->users))
					{
	      	  			$this->sugarbean->load_relationship('user_sync');
					}
	      			$this->sugarbean->contacts_users_id = null;
					$this->sugarbean->user_sync->delete($this->sugarbean->id, $current_user->id);
			}		
		}
		else{
			$this->sugarbean->retrieve($id);
		$_POST['record'] = $id;
		$_GET['record'] = $id;
		$_REQUEST['record'] = $id;
		$newbean = populateFromPost('', $this->sugarbean);
		$newbean->save_from_post = false;
		$check_notify = FALSE;
		if (isset( $this->sugarbean->assigned_user_id)) {
			$old_assigned_user_id = $this->sugarbean->assigned_user_id;
			if (!empty($_POST['assigned_user_id']) 
				&& ($old_assigned_user_id != $_POST['assigned_user_id']) 
				&& ($_POST['assigned_user_id'] != $current_user->id)) {
				$check_notify = TRUE;
			}
		}
		
		$newbean->save($check_notify);
	}	}
	}
}

function getMassUpdateForm(){
	$lang_delete = translate('LBL_DELETE');
	$lang_update = translate('LBL_UPDATE');
	$lang_confirm= translate('NTC_DELETE_CONFIRMATION_MULTIPLE');
	$lang_sync = translate('LBL_SYNC');
	$lang_unsync = translate('LBL_UNSYNC');


	if ( ! isset($this->sugarbean->field_defs) || count($this->sugarbean->field_defs) == 0)
	{
		$html = "<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td><input type='submit' name='Delete' value='{$lang_delete}' onclick=\"return confirm('{$lang_confirm}')\" class='button'></td></tr></table>";
		return $html;
	}
	$should_use = false;
	$html = "<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td style='padding-bottom: 2px;'><input type='submit' name='Update' value='{$lang_update}' class='button'> <input type='submit' name='Delete' value='{$lang_delete}' onclick=\"return confirm('{$lang_confirm}')\" class='button'>";
	
	if($this->sugarbean->object_name == 'Contact'){
		$html .= " <input type='submit' name='Sync' value='{$lang_sync}' class='button'> <input type='submit' name='Unsync' value='{$lang_unsync}' class='button'>";
	}
	$html .= "</td></tr></table><table cellpadding='0' cellspacing='0' border='0' width='100%' class='tabForm'><tr><td><table width='100%' border='0' cellspacing='0' cellpadding='0'>";

	$even = true;
	  static $banned = array('date_modified'=>1, 'date_entered'=>1, 'created_by'=>1, 'modified_user_id'=>1);
      foreach($this->sugarbean->field_defs as $field){
      	if(!isset($banned[$field['name']]) && (!isset($field['massupdate']) || (isset($field['massupdate']) && $field['massupdate']))){
      		$newhtml = '';
      		if($even){
      			$newhtml .= "<tr>";
      		}
      		if(isset($field['vname'])){
      			$displayname = translate($field['vname']);
      		}else{
      			$displayname = '';	
      			
      		}
      		
			if(isset($field['type']))
			{
      			switch($field["type"]){

      				case "relate": $even = !$even; $newhtml .= $this->handleRelationship($displayname, $field); break;
      				case "parent":$even = !$even; $newhtml .=$this->addParent($displayname, $field); break;
      				case "contact_id":$even = !$even; $newhtml .=$this->addContactID($displayname, $field["name"]); break;
      				case "assigned_user_name":$even = !$even; $newhtml .= $this->addAssignedUserID($displayname,  $field["name"]); break;
      				case "account_id":$even = !$even; $newhtml .= $this->addAccountID($displayname,  $field["name"]); break;
      				case "account_name":$even = !$even; $newhtml .= $this->addAccountID($displayname,  $field["id_name"]); break;
      				case "enum":$even = !$even; $newhtml .= $this->addStatus($displayname,  $field["name"], translate($field["options"])); break;
      				case "date":$even = !$even; $newhtml .= $this->addDate($displayname,  $field["name"]); break;



      			}
			}
      		if($even){
      			$newhtml .="</tr>";
      		}else{
      			$should_use = true;
      		}
      		if($newhtml != '<tr>' && $newhtml != '</tr>' && $newhtml != '<tr></tr>'){

      			$html.=$newhtml;
      		}


      	}


      }
      $html .="</table></td></tr></table>";
      if($should_use){
      return $html;
      }else{
      	return "<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td><input type='submit' name='Delete' value='Delete' onclick=\"return confirm('{$lang_confirm}')\" class='button'></td></tr></table>";
      }
}

function endMassUpdateForm(){
	return '</form>';
}

function handleRelationship($displayname, $field)
{

	if(isset($field['module']))
	{
		switch($field['module'])
		{
			case 'Accounts':
				return  $this->addAccountID($displayname, $field['name'], $field['id_name']);
			case 'Contacts':
				return $this->addContactID($displayname, $field['name'], $field['id_name']);
		}

		return '<td></td><td>Not Implemented</td>';
	}

	return '<td></td><td></td>';
}
function addParent($displayname, $field){
	global $app_strings, $app_list_strings;

	///////////////////////////////////////
	///
	/// SETUP POPUP
	
	$popup_request_data = array(
		'call_back_function' => 'set_return',
		'form_name' => 'MassUpdate',
		'field_to_name_array' => array(
			'id' => "parent_id",
			'name' => "parent_name",
			),
		);
	
	$json = new JSON(JSON_LOOSE_TYPE);
	$encoded_popup_request_data = $json->encode($popup_request_data);
	
	//
	///////////////////////////////////////

	$change_parent_button = " <input title='".$app_strings['LBL_SELECT_BUTTON_TITLE']."' accessKey='".$app_strings['LBL_SELECT_BUTTON_KEY']."'  type='button' class='button' value='".$app_strings['LBL_SELECT_BUTTON_LABEL']
		."' name='button' onclick='open_popup(document.MassUpdate.{$field['type_name']}.value, 600, 400, \"\", true, false, {$encoded_popup_request_data});'  />";
	$parent_type = $field['parent_type'];
	$types = get_select_options_with_id($app_list_strings[$parent_type], '');
	return "<td width='25%' class='dataField' valign='top'><select name='{$field['type_name']}'>$types</select></td><td width='25%' class='dataField'><input name='{$field['id_name']}' type='hidden' value=''><input name='parent_name' readonly type='text' value=''>$change_parent_button</td>";
}

function addContactID($displayname, $varname, $id_name=''){
		global $app_strings;

		if(empty($id_name))
			$id_name = "contact_id";

		///////////////////////////////////////
		///
		/// SETUP POPUP
		
		$popup_request_data = array(
			'call_back_function' => 'set_return',
			'form_name' => 'MassUpdate',
			'field_to_name_array' => array(
				'id' => "{$id_name}",
				'name' => "{$varname}",
				),
			);
		
		$json = new JSON(JSON_LOOSE_TYPE);
		$encoded_popup_request_data = $json->encode($popup_request_data);
		
		//
		///////////////////////////////////////

		return "<td width='15%' class='dataLabel'>$displayname</td><td width='35%' class='dataField'><input name='{$varname}' readonly type='text' value=''><input name='{$id_name}' type='hidden' value=''>&nbsp;<input title=\"{$app_strings['LBL_SELECT_BUTTON_TITLE']}\" accessKey='{$app_strings['LBL_SELECT_BUTTON_KEY']}'  type='button' class='button' value='{$app_strings['LBL_SELECT_BUTTON_LABEL']}' name='button'"
			. " onclick='open_popup(\"Contacts\", 600, 400, \"\", true, false, {$encoded_popup_request_data});' /></td>";
}

function addAccountID($displayname, $varname, $id_name=''){
		global $app_strings;

		if(empty($id_name))
			$id_name = "account_id";

		///////////////////////////////////////
		///
		/// SETUP POPUP

		$popup_request_data = array(
			'call_back_function' => 'set_return',
			'form_name' => 'MassUpdate',
			'field_to_name_array' => array(
				'id' => "{$id_name}",
				'name' => "{$varname}",
				),
			);

		$json = new JSON(JSON_LOOSE_TYPE);
		$encoded_popup_request_data = $json->encode($popup_request_data);
		
		//
		///////////////////////////////////////

		return '<td class="dataLabel">' . $displayname . " </td>\n"
			. '<td><input type="text" name="' . $varname . '" readonly="readonly" value="" /><input type="hidden" name="'
			. $id_name . '" value="" />&nbsp;<input type="button" name="btn1" class="button" title="'
			. $app_strings['LBL_SELECT_BUTTON_LABEL'] . '" accesskey="' 
			. $app_strings['LBL_SELECT_BUTTON_KEY'] . '" value="' . $app_strings['LBL_SELECT_BUTTON_LABEL'] . '" onclick='
			. "'open_popup(\"Accounts\",600,400,\"\",true,false,{$encoded_popup_request_data});' /></td>\n";
}












function addAssignedUserID($displayname, $varname){
	$user_array = get_user_array(TRUE, "Active", "");
	$userlist = get_select_options_with_id($user_array, "");
	
$html = <<<EOQ
	<td width="15%" class="dataLabel">$displayname</td>
	<td width="35%" class="dataField"><select name="$varname">$userlist</select></td>
EOQ;
return $html;

}

function addStatus($displayname, $varname, $options){
	global $app_strings, $app_list_strings;

	if(!isset($options['']) && !isset($options['0']))
		$options = array_merge(array(''=>''), $options);
	$options = get_select_options_with_id($options, '');

	 $html = <<<EOQ
	<td class="dataLabel" width="15%">$displayname</td>
	<td ><select name='$varname'>$options</select></td>
EOQ;
return $html;
}

function addDate($displayname, $varname){
	require_once('include/TimeDate.php');
	$timedate = new TimeDate();
	$userformat = '('. $timedate->get_user_date_format().')';
	$cal_dateformat = $timedate->get_cal_date_format();
	global $app_strings, $app_list_strings, $theme;

	$javascriptend = <<<EOQ
		 <script type="text/javascript">
		Calendar.setup ({
			inputField : "${varname}jscal_field", ifFormat : "$cal_dateformat", showsTime : false, button : "${varname}jscal_trigger", singleClick : true, step : 1
		});
		</script>
EOQ;

	 $html = <<<EOQ
	<td class="dataLabel" width="20%">$displayname</td>
	<td class='dataField' width="30%"><input type="text" name='$varname' size="12" id='{$varname}jscal_field' maxlength='10' value=""> <img src="themes/$theme/images/jscalendar.gif" id="{$varname}jscal_trigger" align="absmiddle" alt="Select Date">&nbsp;<span class="dateFormat">$userformat</span>$javascriptend</td>
		<script> addToValidate('MassUpdate','$varname','date',false,'$displayname');</script>
EOQ;
return $html;

}
}

?>
