<?php
/*********************************************************************************
 * 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 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 ********************************************************************************/
/*********************************************************************************
 * $Id: Meeting.php,v 1.94 2005/02/23 21:08:41 robert Exp $
 * Description:  TODO: To be written.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 * All Rights Reserved.
 * Contributor(s): ______________________________________..
 ********************************************************************************/

include_once('config.php');
require_once('include/logging.php');
require_once('include/database/PearDatabase.php');
require_once('data/SugarBean.php');
require_once('modules/Contacts/Contact.php');
require_once('modules/Users/User.php');
require_once('modules/Calendar/DateTime.php');

// Meeting is used to store customer information.
class Meeting extends SugarBean {
	// Stored fields
	var $id;
	var $date_entered;
	var $date_modified;
	var $assigned_user_id;
	var $modified_user_id;
	var $created_by;
	var $created_by_name;
	var $modified_by_name;



	var $description;
	var $name;
	var $location;
	var $status;
	var $date_start;
	var $time_start;
	var $date_end;
	var $duration_hours;
	var $duration_minutes;
	var $parent_type;
	var $parent_id;
	var $field_name_map;
	var $contact_id;
	var $user_id;

	var $parent_name;
	var $contact_name;
	var $contact_phone;
	var $contact_email;
	var $account_id;
	var $opportunity_id;
	var $case_id;
	var $assigned_user_name;




	var $default_meeting_name_values = array('Follow-up on proposal', 'Initial discussion', 'Review needs', 'Discuss pricing', 'Demo', 'Introduce all players', );
    var $minutes_values = array('0'=>'00','15'=>'15','30'=>'30','45'=>'45');

	var $table_name = "meetings";
	var $rel_users_table = "meetings_users";
	var $rel_contacts_table = "meetings_contacts";

	var $object_name = "Meeting";
	var $required_fields =  array("name"=>1, "date_start"=>2, "time_start"=>3, "duration_hours"=>4);
	var $column_fields = Array("id"
		, "date_entered"
		, "date_modified"
		, "assigned_user_id"
		, "modified_user_id"
		, "created_by"



		, "description"
		, "name"
		, "status"
		, "location"
		, "date_start"
		, "time_start"
		, "date_end"
		, "duration_hours"
		, "duration_minutes"
		, "parent_type"
		, "parent_id"
		);
/*
	DO NOT DEPEND ON THIS THIS DATA STRUCTURE
	IT IS ONLY TEMPORARY AND MAY NOT BE SUPPORTED IN FUTURE RELEASES
*/
	var $field_defs = array(
		array("name"=>"date_entered",
        		"vname"=>"LBL_DATE_ENTERED","type"=>"date","len"=>"255" ),
        array("name"=>"date_modified",
        		"vname"=>"LBL_DATE_MODIFIED","type"=>"date","len"=>"255" ),
        array("name"=>"description",
        		"vname"=>"LBL_DESCRIPTION","type"=>"varchar","len"=>"255" ),
        array("name"=>"name",
        		"vname"=>"LBL_SUBJECT","type"=>"varchar","len"=>"50" ),
        array("name"=>"status",
        		"vname"=>"LBL_STATUS","type"=>"enum","len"=>"25", 'options'=>'call_status_dom' ),
         array("name"=>"date_start",
        		"vname"=>"LBL_DATE","type"=>"date","len"=>"255" , 'rel_field'=>'time_start'),
         array("name"=>"time_start",
        		"vname"=>"LBL_TIME","type"=>"time","len"=>"255" , 'rel_field'=>'date_start'),
         array("name"=>"duration_hours",
        		"vname"=>"LBL_DURATION_HOURS","type"=>"int","len"=>"2" ),
         array("name"=>"duration_minutes",
        		"vname"=>"LBL_DURATION_MINUTES","type"=>"int","len"=>"2" ),
//         array('name'=> 'parent_name', 'parent_type'=>'record_type_display' , 'type_name'=>'parent_type','id_name'=>'parent_id', 'vname'=>'LBL_RELATED_TO', 'type'=>'parent'),
//        array('name'=>'contact_name','rname'=>'last_name','id_name'=>'contact_id','vname'=>'LBL_CONTACT_NAME','type'=>'relate','table'=>'contacts','isnull'=>'true','module'=>'Contacts'),
       array('name'=>'assigned_user_id','rname'=>'user_name',
			'id_name'=>'assigned_user_id','vname'=>'LBL_ASSIGNED_TO',
			'type'=>'assigned_user_name','table'=>'users',
			'isnull'=>'false'),



         array('name'=>'created_by','rname'=>'user_name',
              'id_name'=>'created_by','vname'=>'LBL_CREATED',
              'type'=>'assigned_user_name','table'=>'created_by_users',
              'isnull'=>'false'),
         array('name'=>'modified_user_id','rname'=>'user_name',
              'id_name'=>'modified_user_id','vname'=>'LBL_MODIFIED',
              'type'=>'assigned_user_name','table'=>'modified_user_id_users',
              'isnull'=>'false'),
        		);

	// This is used to retrieve related fields from form posts.
	var $additional_column_fields = Array('assigned_user_name', 'assigned_user_id', 'contact_id', 'user_id', 'contact_name');

	// This is the list of fields that are in the lists.
	var $list_fields = Array('id', 'location', 'duration_hours', 'name', 'status', 'parent_type', 'parent_name', 'parent_id', 'date_start', 'time_start', 'assigned_user_name', 'assigned_user_id', 'contact_name', 'contact_id','first_name','last_name'




		);

	// so you can run get_users() twice and run query only once
	var $cached_get_users = null;

	function Meeting() {
		$this->log = LoggerManager::getLogger('meeting');
		$this->db = new PearDatabase();
                $custom = new CustomFields();
                $custom->setFieldDefs($this); 
		foreach ($this->field_defs as $field)
		{
			$this->field_name_map[$field['name']] = $field;
		}



	}

	var $new_schema = true;

	function create_tables () {
		$query = 'CREATE TABLE '.$this->table_name.' ( ';
		$query .='id char(36) NOT NULL';
		$query .=', date_entered datetime NOT NULL';
		$query .=', date_modified datetime NOT NULL';
		$query .=', assigned_user_id char(36)';
		$query .=', modified_user_id char(36)';
		$query .=', created_by char(36)';



		$query .=', name char(50)';
		$query .=', location char(50)';
		$query .=', duration_hours char(2)';
		$query .=', duration_minutes char(2)';
		$query .=', date_start date';
		$query .=', time_start time';
		$query .=', date_end date';
		$query .=', parent_type char(25)';
		$query .=', status char(25)';
		$query .=', parent_id char(36)';
		$query .=', description TEXT';
		$query .=', deleted bool NOT NULL default 0';
		$query .=', PRIMARY KEY ( ID ) )';




		$this->db->query($query,true,"Error creating table: ");

		//TODO Clint 4/27 - add exception handling logic here if the table can't be created.

		$query = "CREATE TABLE $this->rel_users_table (";
		$query .='id char(36) NOT NULL';
		$query .=', meeting_id char(36)';
		$query .=', user_id char(36)';
		$query .=', deleted bool NOT NULL default 0';
		$query .=', PRIMARY KEY ( ID ) )';


		$this->db->query($query,true,"Error creating meeting/user relationship table: ");

		$query = "CREATE TABLE $this->rel_contacts_table (";
		$query .='id char(36) NOT NULL';
		$query .=', meeting_id char(36)';
		$query .=', contact_id char(36)';
		$query .=', deleted bool NOT NULL default 0';
		$query .=', PRIMARY KEY ( ID ) )';


		$this->db->query($query,true,"Error creating meeting/contact relationship table: ");

		// Create the indexes
		$this->create_index("create index idx_mtg_name on meetings (name)");
		$this->create_index("create index idx_usr_mtg_mtg on $this->rel_users_table (meeting_id)");
		$this->create_index("create index idx_usr_mtg_usr on $this->rel_users_table (user_id)");
		$this->create_index("create index idx_con_mtg_mtg on $this->rel_contacts_table (meeting_id)");
		$this->create_index("create index idx_con_mtg_con on $this->rel_contacts_table (contact_id)");

		$this->create_index("create index idx_meet_par_del on meetings ( parent_id , parent_type , deleted )");



	}

	function drop_tables () {
		$query = 'DROP TABLE IF EXISTS '.$this->table_name;



		$this->db->query($query);

		$query = 'DROP TABLE IF EXISTS '.$this->rel_users_table;



		$this->db->query($query);

		$query = 'DROP TABLE IF EXISTS '.$this->rel_contacts_table;



		$this->db->query($query);

		//TODO Clint 4/27 - add exception handling logic here if the table can't be dropped.

	}

	/** Returns a list of the associated contacts
	 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
	 * All Rights Reserved..
	 * Contributor(s): ______________________________________..
	*/
	function get_contacts()
	{
		// First, get the list of IDs.
		$query = "SELECT contact_id as id from meetings_contacts where meeting_id='$this->id' AND deleted=0";

		return $this->build_related_list($query, new Contact());
	}

	/** Returns a list of the associated users
	 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc..
	 * All Rights Reserved..
	 * Contributor(s): ______________________________________..
	*/
	function get_users()
	{
		// First, get the list of IDs.
		$query = "SELECT user_id as id from meetings_users where meeting_id='$this->id' AND deleted=0";
		return $this->build_related_list($query, new User());

		if ( $this->cached_get_users == null)
		{
		 	$this->cached_get_users = $this->build_related_list($query, new User());
		}

		return  $this->cached_get_users;
	}

	// save date_end by calculating user input
	// this is for calendar
	function save($check_notify = FALSE)
        {

		if ( isset($this->date_start)
			&& isset($this->time_start)
			&& isset($this->duration_hours)
			&& isset($this->duration_minutes)
		)
		{
			$date_time_start = DateTime::get_time_start($this->date_start,$this->time_start.":00");
			$date_time_end = DateTime::get_time_end($date_time_start,$this->duration_hours,$this->duration_minutes);
			$this->date_end = "{$date_time_end->year}-{$date_time_end->month}-{$date_time_end->day}";

		}

		parent::save($check_notify);
	}


	function save_relationship_changes($is_update)
    	{

	if($this->account_id != "")
    	{
    		$this->set_meetings_account_relationship($this->id, $this->account_id);
    	}
		if($this->opportunity_id != "")
    	{
    		$this->set_meetings_opportunity_relationship($this->id, $this->opportunity_id);
    	}
		if($this->case_id != "")
    	{
    		$this->set_meetings_case_relationship($this->id, $this->case_id);
    	}
		if($this->contact_id != "")
    	{
    		$this->mark_meeting_contact_relationship_deleted($this->contact_id, $this->id);
    		$this->set_meetings_contact_invitee_relationship($this->id, $this->contact_id);
    	}
		if($this->user_id != "")
    	{
    		$this->mark_meeting_user_relationship_deleted($this->user_id, $this->id);
    		$this->set_meetings_user_invitee_relationship($this->id, $this->user_id);
    	}
		if($this->assigned_user_id != "")
    	{
    		$this->mark_meeting_user_relationship_deleted($this->assigned_user_id, $this->id);
    		$this->set_meetings_user_invitee_relationship($this->id, $this->assigned_user_id);
    	}
    }

	function set_meetings_account_relationship($meeting_id, $account_id)
	{
		$query = "update $this->table_name set parent_id='$account_id', parent_type='Accounts' where id='$meeting_id'";
		$this->db->query($query,true,"Error setting account to meeting relationship: "."<BR>$query");
	}

	function set_meetings_opportunity_relationship($meeting_id, $opportunity_id)
	{
		$query = "update $this->table_name set parent_id='$opportunity_id', parent_type='Opportunities' where id='$meeting_id'";
		$this->db->query($query,true,"Error setting opportunity to meeting relationship: "."<BR>$query");
	}

	function set_meetings_case_relationship($meeting_id, $case_id)
	{
		$query = "update $this->table_name set parent_id='$case_id', parent_type='Cases' where id='$meeting_id'";
		$this->db->query($query,true,"Error setting case to meeting relationship: "."<BR>$query");
	}

	function set_meetings_contact_invitee_relationship($meeting_id, $contact_id)
	{
		$query = "insert into $this->rel_contacts_table set id='".create_guid()."', contact_id='$contact_id', meeting_id='$meeting_id'";
		$this->db->query($query,true,"Error setting meeting to contact relationship: "."<BR>$query");
	}

	function set_meetings_user_invitee_relationship($meeting_id, $user_id)
	{
		$query = "insert into $this->rel_users_table set id='".create_guid()."', user_id='$user_id', meeting_id='$meeting_id'";
		$this->db->query($query,true,"Error setting meeting to user relationship: "."<BR>$query");
	}

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

	function create_list_query(&$order_by, &$where)
	{
		$custom_fields = new CustomFields();
                $query = "SELECT ";
                $query .= $custom_fields->get_list_query_custom_select($this);

		$query .= "
				meetings.id,
				meetings.assigned_user_id,
				meetings.status,
				meetings.name,
				meetings.parent_type,
				meetings.parent_id,
				meetings.date_start,
				meetings.time_start,
				meetings.duration_hours,
				meetings.duration_minutes,
				contacts.first_name,
				contacts.last_name,
                users.user_name as assigned_user_name";



				$query .= " FROM meetings ";





		$query .= "				LEFT JOIN meetings_users
                            	ON meetings.id=meetings_users.meeting_id
								LEFT JOIN meetings_contacts
                            	ON meetings.id=meetings_contacts.meeting_id";



                            	$query .= " LEFT JOIN contacts
                            	ON meetings_contacts.contact_id=contacts.id
                            	LEFT JOIN users
                            	ON meetings.assigned_user_id=users.id ";
		$query .= $custom_fields->get_list_query_custom_from($this);

		$where_auto = " meetings.deleted=0
                                    AND (contacts.deleted IS NULL OR contacts.deleted=0) ";
		$where_auto .= " GROUP BY meetings.id";


		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 meetings.name";

		return $query;

	}

        function create_export_query(&$order_by, &$where)
        {
                $contact_required = ereg("contacts", $where);

                if($contact_required)
                {
                        $query = "SELECT meetings.*, contacts.first_name, contacts.last_name";



                        $query .= " FROM contacts, meetings, meetings_contacts ";
                        $where_auto = "meetings_contacts.contact_id = contacts.id AND meetings_contacts.meeting_id = meetings.id AND meetings.deleted=0 AND contacts.deleted=0";
                }
                else
                {
                        $query = 'SELECT meetings.*';



                        $query .= ' FROM meetings ';
                        $where_auto = "meetings.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 meetings.name";

                return $query;

        }



	function fill_in_additional_list_fields()
	{
		$this->fill_in_additional_detail_fields();
		//$this->fill_in_additional_parent_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);




		$query  = "SELECT contacts.first_name, contacts.last_name, contacts.phone_work, contacts.email1, contacts.id FROM contacts, meetings_contacts ";
		$query .= "WHERE meetings_contacts.contact_id=contacts.id AND meetings_contacts.meeting_id='$this->id' AND meetings_contacts.deleted=0 AND contacts.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);

		$this->log->info($row);

		if($row != null)
		{
			$this->contact_name = return_name($row, 'first_name', 'last_name');
			$this->contact_phone = $row['phone_work'];
			$this->contact_id = $row['id'];
			$this->contact_email = $row['email1'];
			$this->log->debug("Call($this->id): contact_name = $this->contact_name");
			$this->log->debug("Call($this->id): contact_phone = $this->contact_phone");
			$this->log->debug("Call($this->id): contact_id = $this->contact_id");
			$this->log->debug("Call($this->id): contact_email1 = $this->contact_email");
		}
		else {
			$this->contact_name = '';
			$this->contact_phone = '';
			$this->contact_id = '';
			$this->contact_email = '';
			$this->log->debug("Call($this->id): contact_name = $this->contact_name");
			$this->log->debug("Call($this->id): contact_phone = $this->contact_phone");
			$this->log->debug("Call($this->id): contact_id = $this->contact_id");
			$this->log->debug("Call($this->id): contact_email1 = $this->contact_email");
		}

		$this->created_by_name = get_assigned_user_name($this->created_by);
		$this->modified_by_name = get_assigned_user_name($this->modified_user_id);

		$this->fill_in_additional_parent_fields();
	}

	function fill_in_additional_parent_fields()
	{
		global $app_strings, $beanFiles, $beanList;

                if ( ! isset($beanList[$this->parent_type]))
                {
                        $this->parent_name = '';
                        return;
                }

	    $beanType = $beanList[$this->parent_type];
		require_once($beanFiles[$beanType]);
		$parent = new $beanType();
		if ($this->parent_type == "Leads") {
			$query = "SELECT first_name, last_name from $parent->table_name where id = '$this->parent_id'";
		}
		else {
			$query = "SELECT name from $parent->table_name where id = '$this->parent_id'";
		}
		$result = $this->db->query($query,true," Error filling in additional detail fields: ");

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


		if ($this->parent_type == "Leads" and $row != null)
		{
			$this->parent_name = '';
			if ($row['first_name'] != '') $this->parent_name .= stripslashes($row['first_name']). ' ';
			if ($row['last_name'] != '') $this->parent_name .= stripslashes($row['last_name']);
		}
		elseif ($this->parent_type == "Issues") {
        	require_once("modules/Issues/Issue.php");
            $parent = new Issue();

            $query = "SELECT name from $parent->table_name where id = '$this->parent_id'";
			$result = $this->db->query($query, TRUE, "Error filling in additional detail fields: ");
			$row = $this->db->fetchByAssoc($result);

			if (!is_null($row)) {
 				$this->parent_name = '';
				if (!empty($row['name'])) $this->parent_name .= stripslashes($row['name']);
			}
		}
		elseif($row != null)
		{
			$this->parent_name = stripslashes($row['name']);
		}
		else {
			$this->parent_name = '';
		}
	}

	function mark_relationships_deleted($id)
	{
		$query = "delete from $this->rel_users_table where meeting_id='$id'";
		$this->db->query($query,true,"Error marking record deleted: ");

		$query = "delete from $this->rel_contacts_table where meeting_id='$id'";
		$this->db->query($query,true,"Error marking record deleted: ");
	}

	function mark_meeting_contact_relationship_deleted($contact_id, $meeting_id)
	{
		$query = "delete from $this->rel_contacts_table where contact_id='$contact_id' and meeting_id='$meeting_id' and deleted=0";
		$this->db->query($query,true,"Error clearing meeting to contact relationship: ");
	}

	function mark_meeting_user_relationship_deleted($user_id, $meeting_id)
	{
		$query = "delete from $this->rel_users_table where user_id='$user_id' and meeting_id='$meeting_id' and deleted=0";
		$this->db->query($query,true,"Error clearing meeting to user relationship: ");
	}
	function get_list_view_data(){
		$meeting_fields = $this->get_list_view_array();
		global $app_list_strings, $focus, $action, $currentModule, $image_path;
		if (isset($this->parent_type))
			$meeting_fields['PARENT_MODULE'] = $this->parent_type;
		if ($this->status == "Planned") {
			$meeting_fields['SET_COMPLETE'] = "<a href='index.php?return_module=$currentModule&return_action=$action&return_id=$this->id&action=Save&module=Meetings&record=$this->id&status=Held'>".get_image($image_path."close_inline.png","alt='Close' border='0'")."</a>";
		}
		$today = date('Y-m-d', time());
		if( $meeting_fields['DATE_START']	< $today){
			$meeting_fields['DATE_START']= "<font class='overdueTask'>".$meeting_fields['DATE_START']."</font>";
		}else if( $meeting_fields['DATE_START']	== $today ){
			$meeting_fields['DATE_START'] = "<font class='todaysTask'>".$meeting_fields['DATE_START']."</font>";
		}else{
			$meeting_fields['DATE_START'] = "<font class='futureTask'>".$meeting_fields['DATE_START']."</font>";
		}
		$meeting_fields['CONTACT_NAME'] = return_name($meeting_fields,'FIRST_NAME','LAST_NAME');
		return $meeting_fields;
	}

	function parse_additional_headers(&$list_form, $xTemplateSection) {

	}

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

	function set_notification_body($xtpl, $meeting)
	{
		$xtpl->assign("MEETING_SUBJECT", $meeting->name);
		$xtpl->assign("MEETING_STATUS", $meeting->status);
		$xtpl->assign("MEETING_STARTDATE", $meeting->date_start . " " . $meeting->time_start);
		$xtpl->assign("MEETING_HOURS", $meeting->duration_hours);
		$xtpl->assign("MEETING_MINUTES", $meeting->duration_minutes);
		$xtpl->assign("MEETING_DESCRIPTION", $meeting->description);

		return $xtpl;
	}

}
?>
