<?php
/****************************************
/*  Author 	: Kvvaradha
/*  Module 	: Kvcodes CRM
/*  E-mail 	: admin@kvcodes.com
/*  Version : 1.0
/*  Http 	: www.kvcodes.com
*****************************************/

$page_security = 'CRM_TASKS';
$path_to_root="../../..";
if(!isset($page_nested))
	include_once($path_to_root . "/includes/db_pager.inc");
include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/db/custom_fields_db.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/ui/custom_fields_ui.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");
include_once($path_to_root . "/modules/KvcodesCRM/includes/comments.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_tasks', array('id' => $view_id));
	if(in_ajax()) {
		$Ajax->popup('../tasks?view_task='.$view_id);		 
	}	
}?>
<style>
.nicEdit-selectTxt {line-height: 16px !important;}
</style>

<?php 

$version_id = get_company_prefs('version_id');

$js = '';
if($version_id['version_id'] == '2.4.1'){
	
	if (user_use_date_picker()) 
		$js .= get_js_date_picker();
	
}else{
	if ($use_date_picker)
		$js .= get_js_date_picker();
}
if ($SysPrefs->use_popup_windows)
	$js .= get_js_open_window(800, 500);

add_js_file('../modules/KvcodesCRM/js/nicEdit-latest.js');
if(isset($_GET['view_task']))
	page(_($help_context = "Tasks"), true, false, "", $js);
else
	page(_($help_context = "Tasks"), 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']) ) {
	global $crm_priorities_list;
	$input_error = 0;
	if (strlen($_POST['name']) == 0) {
		display_error(_("The Task Name cannot be empty."));
		set_focus('name');
		return false;
	}	
	if (strlen($_POST['description']) == 0) {
		display_error(_("The Task Description Can't be empty."));
		set_focus('description');
		return false;
	}
	if($Mode  =='UPDATE_ITEM'){
		if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER && $_SESSION['wa_current_user']->person > 0 ){
			display_warning('Permission denied ! Could not EDIT this task !');
			$input_error =1;
		}
	}
	if ($input_error != 1){
		$Update = array( 'is_public' => check_value('is_public'), 'priority' => $_POST['priority'], 'status' => $_POST['status'], 'billable' =>check_value('billable'), 'hourly_rate' => input_num('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'];

		if($selected_id != -1){
			$addedfrom = $Update['addedfrom'];
			unset($Update['addedfrom']);
		}

		Update('kv_crm_tasks', array('id' => $_POST['selected_id']), $Update); 
		custom_field_update('task',$_POST['selected_id']);
		if($selected_id != -1){
			display_notification(_("The Selected Task has been updated!."));
			if($_POST['old_status'] != $_POST['status']){

				$details = array( 'task_name' => $_POST['name'], 'name2' => '', 'task_startdate' => $_POST['startdate'], 'task_duedate' => $_POST['duedate'], 'task_priority' => $crm_priorities_list[$_POST['priority']], 'task_status' => GetSingleValue('kv_crm_picklist_values', 'description', array('id2' => $_POST['status'], 'picklist_id' => 5)));				

				if($_SESSION['wa_current_user']->user != $_POST['staffid']) { // Sent to Staff 
					$staff = GetRow('users', array('id' => $_POST['staffid']));
					$details['real_name'] = $staff['real_name'];
					
					$details['phone'] = $staff['phone'];
					$details['email'] = $staff['email'];
					$to =  array('name' => $staff['real_name'], 'email' => $staff['email']);
					$template = array('slug' => 'task-status-change-to-staff',  'details' => $details );			
					kv_mail($to, '', '', "html", array(), null, false, $template);
				}

				// To Administrator or Task creator
				$admin = GetRow('users', array('id' => $addedfrom));
				$details['real_name'] = $admin['real_name'];				
				$details['phone'] = $admin['phone'];
				$details['email'] = $admin['email'];
				$to =  array('name' => $admin['real_name'], 'email' => $admin['email']);	
				$template = array('slug' => 'task-status-change-to-staff',  'details' => $details );				
				kv_mail($to, '', '', "html", array(), null, false, $template);

				//To Customer

				/*$staff = GetRow('users', array('id' => $_POST['staffid']));
				$to =  array('name' => $staff['real_name'], 'email' => $staff['email']);

				$details = array('real_name' => $staff['real_name'], 'name2' => '',  'phone' => $staff['phone'], 'email' => $staff['email'], 'task_name' => $_POST['name'], 'task_startdate' => $_POST['startdate'], 'task_duedate' => $_POST['duedate'], 'task_priority' => $crm_priorities_list[$_POST['priority']]);

				$template = array('slug' => 'task-assigned',  'details' => $details );
				kv_mail($to, '', '', "html", array(), null, false, $template);*/

			}
		}
		else{
			$staff = GetRow('users', array('id' => $_POST['staffid']));
			$to =  array('name' => $staff['real_name'], 'email' => $staff['email']);

			$details = array('real_name' => $staff['real_name'], 'name2' => '',  'phone' => $staff['phone'], 'email' => $staff['email'], 'task_name' => $_POST['name'], 'task_startdate' => $_POST['startdate'], 'task_duedate' => $_POST['duedate'], 'task_status' => $_POST['status'], 'task_priority' => $crm_priorities_list[$_POST['priority']]);

			$template = array('slug' => 'task-assigned',  'details' => $details );
			kv_mail($to, '', '', "html", array(), null, false, $template);
			display_notification(_("A New Task has been added!."));

		}
	}
	refresh_pager('kv_tasks');
	$Ajax->activate('_page_body');
	$Mode = 'RESET';	
		
}

if ($Mode == 'Delete'){	
	$delete= 0;
	$addedfrom_value =GetSingleValue('kv_crm_tasks','addedfrom',array('id' => $selected_id));
	if(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER && $_SESSION['wa_current_user']->person > 0 ){
		if($_SESSION['wa_current_user']->user != $addedfrom_value){
			display_warning('Permission denied ! Could not DELETE this task !');
			$delete =1;
		}
	}
	if(crm_key_in_foreign_table($selected_id, 'kv_crm_attachments', 'type_id', ['type', ST_TASKS])){
		display_warning("This Task has some Attachments. Kindly remove them before deleting the task");
		$delete = 1;
	}
	if(crm_key_in_foreign_table($selected_id, 'kv_crm_comments', 'type_id', ['type', ST_TASKS])){
		display_warning("This Task has some Comments. Kindly remove them before deleting the task");
		$delete = 1;
	}
	if($delete !=1){
		Delete('kv_crm_tasks', array('id' => $selected_id));	
		display_notification(_("The Selected Task has been deleted.")); 
	}	
	
	$Mode = 'RESET';
	refresh_pager('kv_tasks');
	$Ajax->activate('Tasks');
}	

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;
	$Ajax->activate('TaskTypes');	
	$Ajax->activate('type_id');
	$Ajax->activate('Tasks');
	$Ajax->activate('_page_body');
	
}

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 (isset($crm_priorities_list[$row['priority']]) ? $crm_priorities_list[$row['priority']] : ''); 
}
function status_fun($row) {	
	return GetSingleValue('kv_crm_picklist_values', 'description', array('id2' => $row['status'], 'picklist_id' => 5)); 
}

function GetStaffName($row) {	
	return GetSingleValue('users', "CONCAT(`real_name`, ' ', `user_id`) AS name", array('id' => $row['staffid'])); 
}

function display_rows($type){
	$sql = 'SELECT id, name, startdate, duedate, priority, status, staffid FROM '.TB_PREF.'kv_crm_tasks WHERE 1';
	if($type > 0)
		$sql .=' AND type='.$type;

	if(get_post('type_id'))
		$sql .= ' AND type_id = '.get_post('type_id');

	if(get_post('filter_status')){
		$sql .= ' AND status='.get_post('filter_status');
	}
	if(get_post('filter_staffid'))
		$sql .= ' AND staffid='.get_post('filter_staffid');
	if(get_post('filter_priority'))
		$sql .= ' AND priority='.get_post('filter_priority');

	$sql .=' ORDER BY name DESC, duedate DESC'; 
	$cols = array(
		_("ID") => array('name'=>'id', 'ord'=>'desc'),
		_("Task Name") => array('name'=>'name'),
		_("Start Date") => array('name'=>'startdate', 'type'=>'date', 'ord'=>'desc'),	    	    
		_("Due Date") => array('name'=>'duedate', 'type'=>'date', 'ord'=>'desc'),	   
		_("Priority") => array('name'=>'priority', 'fun'=>'priority_fun'), 	 
		_("Staff") => array('name'=>'staffid', 'fun'=>'GetStaffName'), 	 
		_("Status") => array('name'=>'status', 'fun'=>'status_fun'),   
	    	array('insert'=>true, 'fun'=>'edit_link'),
	    	array('insert'=>true, 'fun'=>'view_link'),	    	
	    	array('insert'=>true, 'fun'=>'delete_link')
	    );	
		
	$table =& new_db_pager('kv_tasks', $sql, $cols);
	$table->width = "80%";
	display_db_pager($table);
}

//----------------------------------------------------------------------------------------
$action = $_SERVER['PHP_SELF'];
if (list_updated('customer_id')||list_updated('lead_id') ||list_updated('supplier_id')|| list_updated('project_id')){
	$selected_id =-1;	
	$_POST['filter_status']=0;
	$_POST['filter_staffid']='';
	$_POST['filter_priority']=0;
	$Ajax->activate('TaskTypes');
	$Ajax->activate('type_id');
	$Ajax->activate('Tasks');	

}
if(list_updated('type')){
	$type = get_post('type');
	$_POST['type_id'] =0;
	$selected_id =-1;
	$Ajax->activate('TaskTypes');	
	$Ajax->activate('type_id');
	$Ajax->activate('Tasks');	
}
	
if ($page_nested)
	$action .= "?type_id=".get_post('type_id');
start_form(true, false, $action);
	div_start('TaskTypes');	
	
	if(isset($_GET['view_task'])){
		global $crm_priorities_list;
		$row = GetRow('kv_crm_tasks', array('id' => $_GET['view_task']));
		start_table(TABLESTYLE2);
			table_section_title(_("Task Details"));
			label_row(_("Task Title")." :", $row['name']);			
			label_row(_("Task Description")." :", nl2br(htmlspecialchars_decode($row['description'])));
			label_row(_("Priority")." :", $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 Task")." :", ($row['is_public'] == 1 ? 'Yes' : 'No'));
		end_table();
	}else {
		start_table(TABLESTYLE_NOBORDER);
		start_row();
		$default_type =  _("Select Type");
		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;
				$_POST['type'] = ST_CUSTOMER;
			//echo '<style> #delete { display : none; } </style>';	
		} elseif(isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_SUPPLIER) {			
				$_POST['type_id'] = $_SESSION['wa_current_user']->person;
				$_POST['type'] = ST_SUPPLIER;
				$current_user = false;
				//echo '<style> #delete { display : none; } </style>';				
		} else 
			$current_user = false;
		if(!$page_nested && !isset($_SESSION['wa_current_user']->type)){
			crm_task_types_list_cells(_("Select a Type"). " :", 'type', null, $default_type, true, false, $current_user);
			// display_error(json_encode($_POST['type']));
		} 
		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 && $_SESSION['wa_current_user']->person > 0 )	
					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($_SESSION['wa_current_user']->type))
				hidden('type', get_post('type'));		
		}	
		br();
		kv_common_type_cells(_('Status'), 'filter_status', null,  _("All Status"), true, 5);
		if(!isset($_SESSION['wa_current_user']->type))
			kv_unassigned_staffs_cells(_('Assigned To'),'filter_staffid', null, _("All Users"), true, false);
		crm_priorities_list_cells(_("Priority").' :', 'filter_priority', null, _("Select a Priority"), true);

		if (list_updated('type_id')) {
			$type = get_post('type');
			$Ajax->activate('type_id');
			$Ajax->activate('Tasks');	
			set_focus('type_id');
			 $selected_id=-1;
		}
		if(list_updated('filter_status') || list_updated('filter_staffid') || list_updated('filter_priority')){
			$selected_id = -1;
		}
		end_row();
		end_table();
	}
	div_end();	

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

	}else{
		display_rows($type);	
		br(2);
		tabbed_content_start('tasktabs', array(
			'taskGeneral' => array(_('&Task Details'), $selected_id!=-1),
			'taskattachments' => array(_('&Attachments'), $selected_id!=-1),
			'comments' => array(_('&Comments'), $selected_id!=-1),
		));
		
		switch (get_post('_tasktabs_sel')) {
			default:
			case 'taskGeneral':
				task_open($selected_id, $type); 
				break;
			case 'taskattachments':
				/*$_GET['type_id'] = $selected_id;
				$_GET['type']= 4;  //tasks type
				$_GET['page_level'] = 1;
				include_once($path_to_root."/modules/KvcodesCRM/manage/attachments.php");*/
				$_GET['type_id'] = $selected_id;	
				$_GET['task_type']= ST_TASKS;  //task type
				$attachments = new attachments('attachment', $selected_id, 'leads');
				$attachments->show();

				break;
			case 'comments':
				$_GET['type_id'] = $selected_id;	
				$_GET['task_type']= ST_TASKS;  //task type
				$comments = new crm_comments('comments', $selected_id, 'leads');
				$comments->show();

				break;

		};
		hidden('branch_code');
		hidden('selected_id', $selected_id);
	br();
	tabbed_content_end();
	}
	

function task_open($selected_id, $type){
	global $Mode;
	//display_error($selected_id);
	if ($selected_id != -1 || (get_post('type_id') && get_post('type')) ){
		br(2);	
		start_table();
		
		if($type== ST_LEADS){
			$id_word = _("Lead ");
			$id_name = GetSingleValue('kv_crm_leads', 'CONCAT(`first_name`, " ", `last_name`) AS name', array('lead_id' => get_post('type_id')));
		}elseif($type==ST_PROJECT){			
			$id_word = _("Project ");
			$id_name = GetSingleValue('kv_crm_projects', 'name', array('id' => get_post('type_id')));
		}elseif($type==ST_CUSTOMER || (isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER)){
			$id_word = _("Customer ");
			$id_name = GetSingleValue('debtors_master', 'name', array('debtor_no' => get_post('type_id')));
		}elseif($type==ST_SUPPLIER || (isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_SUPPLIER)){
			$id_word = _("Supplier ");
			$id_name = GetSingleValue('suppliers', 'supp_name', array('supplier_id' => get_post('type_id')));
		}
		if($Mode == 'Edit' || $selected_id != -1 )	{
			$row = GetRow('kv_crm_tasks', 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'];		
			$crm_type_id = $row['type_id']	;
			
			if($row['type']== ST_LEADS){
				$id_word = _("Lead ");
				$id_name = GetSingleValue('kv_crm_leads', 'CONCAT(`first_name`, " ", `last_name`) AS name', array('lead_id' => $row['type_id']));
			}elseif($row['type']==ST_PROJECT){			
				$id_word = _("Project ");
				$id_name = GetSingleValue('kv_crm_projects', 'name', array('id' => $row['type_id']));
			}elseif($row['type']==ST_CUSTOMER || (isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER)){
				$id_word = _("Customer ");
				$id_name = GetSingleValue('debtors_master', 'name', array('debtor_no' => $row['type_id']));
			}elseif($row['type']==ST_SUPPLIER || (isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_SUPPLIER)){
				$id_word = _("Supplier ");
				$id_name = GetSingleValue('suppliers', 'supp_name', array('supplier_id' => $row['type_id']));
			}
			label_row(_($id_word), $id_name);
			$_POST['startdate'] = sql2date($row['startdate']);
			$_POST['duedate'] = sql2date($row['duedate']);
			hidden('mode', $Mode);
			hidden('old_status', $row['status']);
		} 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, $id_name);		
			$crm_type_id = get_post('type_id');	
		}
		hidden('selected_id', $selected_id);
		text_row(_("Task Name/Title").'* :', 'name', null, 80, 100);
		kv_crm_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');	
		if($type != 2)
			kv_user_list_row('Assigned To','staffid', null, _("Select an User"), '');	
		else 
			kv_project_members_row('Assigned To','staffid', null, _("Select a Member"), false, $crm_type_id);	
		kv_common_type_row(_('Status'), 'status', null,  false, false, 5);
		table_section(3);
		
		end_outer_table(1);
		start_outer_table(TABLESTYLE2);
		table_section(1);
		//for custom fields
		custom_field_section('task',$selected_id,1);
		//end custom fields
		table_section(2);
		//for custom fields
		custom_field_section('task',$selected_id,2);
		//end custom fields
		end_outer_table(1);
		
			submit_add_or_update_center($selected_id == -1, '', 'process');
		// }
	}	
}
	div_end();
end_form();
echo "<script type='text/javascript'> kvcodes_crm_nicEditor();  </script> \n";
end_page();
?>