<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Kvcodes CRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
/*  Activity Inquiry
*****************************************/
$page_security = 'CRM_ACTIVITIES';
$path_to_root="../../..";
if(!isset($page_nested))
	include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
add_access_extensions();
include_once($path_to_root . "/admin/db/attachments_db.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/data_checks.inc");

include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );
include_once($path_to_root . "/modules/KvcodesCRM/includes/attachment.inc");

if (isset($_GET['vw']))
	$view_id = $_GET['vw'];
else
	$view_id = find_submit('view');
if ($view_id != -1){	//echo $view_id;
	//$row = GetRow('kv_crm_activities', array('id' => $view_id));
	if(in_ajax()) {
		$Ajax->popup('../tasks?view_task='.$view_id);		 
	}	
}

$version_id = get_company_prefs('version_id');

$js = '';
if($version_id['version_id'] == '2.4.1'){
	if ($SysPrefs->use_popup_windows) 
		$js .= get_js_open_window(900, 500);	

	if (user_use_date_picker()) 
		$js .= get_js_date_picker();
	
}else{
	if ($use_popup_windows)
		$js .= get_js_open_window(900, 500);
	if ($use_date_picker)
		$js .= get_js_date_picker();
}
$help_context = _("Reminders Inquiry");

if(isset($_GET['medium']) && $_GET['medium'] ==1)
	$help_context = _("Calls Inquiry");
elseif(isset($_GET['medium']) && $_GET['medium'] == 2)
	$help_context = _("Meetings Inquiry");

page($help_context, false, false, "", $js);
simple_page_mode(true);

//----------------------------------------------------------------------------------------
if (isset($_GET['type_id']))
	 $type_id = $_POST['type_id'] = $_GET['type_id'];
if (isset($_GET['type']))
	 $type = $_POST['type'] = $_GET['type'];
elseif(!isset($_POST['type']))
	$type = $_POST['type'] = -1; //default Leads.

if (($Mode == 'ADD_ITEM' || $Mode == 'UPDATE_ITEM') && !isset($_POST['title']) ) {
		
	$input_error = 0;
	if (strlen($_POST['name']) == 0) {
		display_error(_("The Activity Name cannot be empty."));
		set_focus('name');
		return false;
	}	
	if (strlen($_POST['description']) == 0) {
		display_error(_("The Activity Description Can't be empty."));
		set_focus('description');
		return false;
	}
	if ($input_error != 1){
		$Update = array( 'is_public' => $_POST['is_public'], 'priority' => $_POST['priority'], 'status' => $_POST['status'], 'billable' => $_POST['billable'], 'hourly_rate' => $_POST['hourly_rate'], 'name' => $_POST['name'], 'description' => $_POST['description'], 'addedfrom' => $_SESSION["wa_current_user"]->user, 'startdate' => array($_POST['startdate'], 'date'), 'duedate' => array($_POST['duedate'], 'date'), 'dateadded' => array(Today(), 'date'),  'staffid' => $_POST['staffid']);
		if(get_post('type_id'))
			$Update['type_id'] = $_POST['type_id'];
		if(get_post('type'))
			$Update['type'] = $_POST['type'];

		Update('kv_crm_activities', array('id' => $_POST['selected_id']), $Update); 
		if($selected_id != -1)
			display_notification(_("The Selected Activity has been updated!."));
		else
			display_notification(_("A New Activity has been added!."));
	}
	$Mode = 'RESET';
	$Ajax->activate('_page_body');
		
}

if ($Mode == 'Delete'){
	
	Delete('kv_crm_activities', array('id' => $selected_id));	
	display_notification(_("The Selected Activity has been deleted.")); 
	$Mode = 'RESET';
}

if ($Mode == 'RESET'){	
	unset($_POST['name'], $_POST['description'], $_POST['is_public'], $_POST['priority'],$_POST['status'],$_POST['billable'],$_POST['hourly_rate'],  $_POST['startdate'], $_POST['duedate']);
	$selected_id = -1;
}

function edit_link($row){
  	return button('Edit'.$row["id"], _("Edit"), _("Edit"), ICON_EDIT);
}

function view_link($row){
  	return button('view'.$row["id"], _("View"), _("View"), ICON_VIEW);
}

function download_link($row){
  	return button('download'.$row["id"], _("Download"), _("Download"), ICON_DOWN);
}

function delete_link($row){
  	return button('Delete'.$row["id"], _("Delete"), _("Delete"), ICON_DELETE);
}
/*function priority_fun($row) {
	global $crm_priorities_list; 
	return $crm_priorities_list[$row['priority']]; 
}*/

function display_rows($type){
	$filter = array('alert' => 1);
	if($type > 0 )
		$filter['`act`.`type`'] = $type;
	if(get_post('type_id'))
		$filter['`act`.`type_id`'] =  get_post('type_id');
	if(get_post('status')){
		$filter['`act`.`status`'] = get_post('status');
	}
	if(get_post('medium')){
		$filter['`act`.`medium_to`'] = get_post('medium');
	}elseif(isset($_GET['medium'])){
		$filter['`act`.`medium_to`'] = $_GET['medium'];
	}
	if(get_post('staffid'))
		$filter['`act`.`user`'] = get_post('staffid');
		
	$sql = GetDataJoin('kv_crm_activities AS act', array( 
					0 => array('join' => 'INNER', 'table_name' => 'kv_crm_picklist_values AS vales', 'conditions' => '`vales`.`id2` = `act`.`status` AND `vales`.`picklist_id` = 4'), 
					1 => array('join' => 'LEFT', 'table_name' => 'kv_crm_picklist_values AS medium', 'conditions' => '`medium`.`id2` = `act`.`medium` AND `medium`.`picklist_id` = 6'),
					2 => array('join' => 'LEFT', 'table_name' => 'kv_crm_picklist_values AS medium_to', 'conditions' => '`medium_to`.`id2` = `act`.`medium_to` AND `medium_to`.`picklist_id` = 6'),
					3 => array('join' => 'LEFT', 'table_name' => 'users AS usr', 'conditions' => '`usr`.`id` = `act`.`user`')	), 
			array('`act`.`id`, `act`.`name`, `act`.`description`, `act`.`date`, `act`.`reminder_date`, `medium_to`.`description` AS Medium_to, CONCAT(`real_name`, " ", `user_id`) AS user_name,  `vales`. `description` AS status'), 
			$filter, null, false, false, true);

	$sql .=' ORDER BY reminder_date ASC'; 
	$cols = array(
		_("ID") => array('name'=>'id', 'ord'=>'desc'),
		_("Type") => array('name'=>'type'),
		_("Activity Name") => array('name'=>'name'),
		_("Start Date") => array('name'=>'date', 'type'=>'date', 'ord'=>'desc'),	    	    
		_("Due Date") => array('name'=>'reminder_date', 'type'=>'date', 'ord'=>'desc'),	   
		_("Medium") => array('name'=>'medium_to'), 	 
		_("Staff") => array('name'=>'user_name'),	 
		_("Status") => array('name'=>'status'),   
	    	//array('insert'=>true, 'fun'=>'edit_link'),
	    	//array('insert'=>true, 'fun'=>'view_link'),	    	
	    	array('insert'=>true, 'fun'=>'delete_link')
	    );	
	if($type != 0)
		unset($cols[_("Type")]);
	$table =& new_db_pager('kv_activities', $sql, $cols);
	$table->width = "80%";
	display_db_pager($table);
}

//----------------------------------------------------------------------------------------
$action = $_SERVER['PHP_SELF'];
if(list_updated('type')){
	$type = get_post('type');
	$_POST['type_id'] =0;
	$Ajax->activate('ActivityTypes');	
	$Ajax->activate('type_id');
	$Ajax->activate('Activities');	
}
	
if ($page_nested)
	$action .= "?type_id=".get_post('type_id');
start_form(true, false, $action);
	div_start('ActivityTypes');	
	
	if(isset($_GET['view_task'])){
		global $crm_priorities_list;
		$row = GetRow('kv_crm_activities', array('id' => $_GET['view_task']));
		start_table(TABLESTYLE, "width='60%'");
			table_section_title(_("Activity Details"));
			label_row(_("Activity Title")." :", $row['name']);			
			label_row(_("Activity Description")." :", nl2br($row['description']));
			label_row(_("Activity Description")." :", $crm_priorities_list[$row['priority']]);
			label_row(_("Start Date")." :", sql2date($row['startdate']));
			label_row(_("Due Date")." :", sql2date($row['duedate']));
			label_row(_("Hourly Rate")." :", $row['hourly_rate']);
			label_row(_("Billable")." :", ($row['billable'] == 1 ? 'Yes' : 'No'));
			label_row(_("Assigned To")." :", GetSingleValue('users', "CONCAT(`real_name`, ' ', `user_id`) AS name", array('id' => $row['staffid'])));
			label_row(_("Public Activity")." :", ($row['is_public'] == 1 ? 'Yes' : 'No'));
		end_table();
	} else {
		start_table(TABLESTYLE_NOBORDER);
		start_row();
		
		$default_type =  _("Select Type");
		$current_user = false;
		if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER) {
			$current_user = 'customer';
			$default_type = false;
			if(get_post('type')== ST_CUSTOMER)
				$_POST['type_id'] = $_SESSION['wa_current_user']->person_id;
			//$_POST['type'] = 3;
			//echo '<style> #delete { display : none; } </style>';	
		} elseif(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_SUPPLIER) {
			if(isset($_SESSION['wa_current_user']->person_id)) {
				$_POST['type_id'] = $_SESSION['wa_current_user']->person_id;
				$_POST['type'] = ST_SUPPLIER;				
				//echo '<style> #delete { display : none; } </style>';	
			}
		} 		

		if(!$page_nested && (!isset($_SESSION['wa_current_user']->type) || $_SESSION['wa_current_user']->type != ST_SUPPLIER)){
			crm_task_types_list_cells(_("Select a Type"). " :", 'type', null, $default_type, true, false,  $current_user);
		} 
		if (isset($_POST['type']) && $_POST['type'] == ST_LEADS && db_has_leads()) {
			if (!$page_nested){			
				lead_list_cells(_("Select a Lead"). " :", 'type_id', null,  _("Select Lead"), true, check_value('show_inactive'), false, array());
				$new_item = get_post('type_id')=='';
			} else 
				hidden('type_id', get_post('lead_id'));
		} elseif(isset($_POST['type']) && $_POST['type'] == ST_PROJECT && db_has_projects()) {		
			if (!$page_nested){			
				if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER)		
					projects_list_cells(_("Select a Project"). " :", 'type_id', null,  false, true, check_value('show_inactive'), false, false, $_SESSION['wa_current_user']->person);
				else
					projects_list_cells(_("Select a Project"). " :", 'type_id', null,  _("Select Project"), true, check_value('show_inactive'));
				$new_item = get_post('type_id')=='';
			} else 
				hidden('type_id', get_post('project_id'));
		} elseif(isset($_POST['type']) && $_POST['type'] == ST_CUSTOMER && db_has_customers() && (!isset($_SESSION['wa_current_user']->type) || $_SESSION['wa_current_user']->type != ST_CUSTOMER)) {		
			if (!$page_nested){			
				customer_list_cells(_("Select a customer") ." :", 'type_id', null,	_('Select customer'), true, check_value('show_inactive'));
				check_cells(_("Show inactive:"), 'show_inactive', null, true);
				$new_item = get_post('type_id')=='';
			} else 
				hidden('type_id', get_post('customer_id'));
		} elseif(isset($_POST['type']) && $_POST['type'] == ST_SUPPLIER && db_has_suppliers()  &&  (!isset($_SESSION['wa_current_user']->type) || $_SESSION['wa_current_user']->type != ST_SUPPLIER)) {		
			if (!$page_nested){			
				supplier_list_cells(_("Select a Supplier") ." :", 'type_id', null,	_('Select Supplier'), true, check_value('show_inactive'));
				$new_item = get_post('type_id')=='';
			} else 
				hidden('type_id', get_post('supplier_id'));
		}else{				
			hidden('type_id', get_post('type_id'));		
		}	
		//if(isset($_POST['type']) && $_POST['type'] > 0 ){
			kv_common_type_cells(_('Status'), 'status', null,  _("All Status"), true, 4);
			if(isset($_GET['medium']))
				hidden('medium', $_GET['medium']);
			else
				kv_common_type_cells(_('Medium'), 'medium', null,  _("Select"), true, 6);
			kv_unassigned_staffs_cells(_('Assigned To'),'staffid', null, _("All Users"), true, false);
			
			//kv_common_type_cells(_('Opportunity Source') ,'lead_source',null, _("All Soruces"), true,1);
		//}
		if (list_updated('type_id')) {
			$type = get_post('type');
			$Ajax->activate('type_id');
			$Ajax->activate('Activities');	
			set_focus('type_id');
		}
		end_row();
		end_table();
	}
	div_end();	

	div_start('Activities');
	br(2);
	$type = get_post('type');
	if(isset($_GET['view_task'])){

	}else{
		display_rows($type);	
		br(2);		
	}
	

function task_open($selected_id, $type){
	global $Mode;

	if ($selected_id != -1 || (get_post('type_id') && get_post('type')) ){
		br(2);	
		start_table();
		
		if($type== ST_LEADS)
			$id_word = _("Lead ID");
		elseif($type==ST_PROJECT)			
			$id_word = _("Project ID");
		elseif($type==ST_CUSTOMER)
			$id_word = _("Customer ID");
		elseif($type==ST_SUPPLIER)
			$id_word = _("Supplier ID");
		if($Mode == 'Edit')	{
			$row = GetRow('kv_crm_activities', array('id' => $selected_id, 'type' => $type));
			$_POST['name']  = $row["name"];			
			$_POST['description'] = $row['description'];			
			$_POST['is_public'] = $row['is_public'];			
			$_POST['priority'] = $row['priority'];			
			$_POST['status'] = $row['status'];			
			$_POST['hourly_rate'] = $row['hourly_rate'];			
			$_POST['billable'] = $row['billable'];			
			$_POST['staffid'] = $row['staffid'];			
			label_row(_($id_word), $row['type_id']);
			$_POST['startdate'] = sql2date($row['startdate']);
			$_POST['duedate'] = sql2date($row['duedate']);
		} else {				
			
			unset($_POST['name'], $_POST['description'], $_POST['is_public'], $_POST['priority'],$_POST['status'],$_POST['billable'],$_POST['hourly_rate'],  $_POST['startdate'], $_POST['duedate']);
			if(!isset($_POST['staffid'])){
				$_POST['staffid'] = $_SESSION["wa_current_user"]->user;
			}
			label_row($id_word, get_post('type_id'));			
		}
		hidden('selected_id', $selected_id);
		text_row(_("Activity Name/Title").'* :', 'name', null, 80, 100);
		textarea_row(_("Description").'* :', 'description', null, 70, 15);

		end_table();

		start_outer_table(TABLESTYLE2);
		table_section(1);
		check_row(_("Public"), 'is_public', null);		
		date_row(_("Start Date"), 'startdate');		
		text_row(_("Hourly Rate"). ' :', 'hourly_rate', null, 10, 10);

		crm_priorities_list_row(_("Priority").' :', 'priority', null);
		
		table_section(2);
		check_row(_("Billable"), 'billable', null);
		date_row(_("Due Date"), 'duedate');	
		kv_user_list_row('Assigned To','staffid', null, _("Select an User"), '');	
		kv_common_type_row(_('Status'), 'status', null,  false, false, 3);
		end_outer_table(1);

		submit_add_or_update_center($selected_id == -1, '', 'process');
	}	
}
	div_end();
end_form();
end_page();
?>