<?php  
$path_to_root="../../..";
$page_security = 'SA_OPEN';
include_once($path_to_root . "/includes/session.inc");
page(_($help_context = "Ticket replies"));
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );

if(isset($_GET['t_id']) && $_GET['t_id'] > 0 ){
	$_POST['ticket_id'] = $_GET['t_id'];
	$to ="";
	$title ="";
	$ticket_company ="-10";
}

$is_customer =((isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_CUSTOMER ) ? $_SESSION['wa_current_user']->person : 0);

$is_supplier =((isset($_SESSION['wa_current_user']->type) && $_SESSION['wa_current_user']->type == ST_SUPPLIER ) ? $_SESSION['wa_current_user']->person : 0);
global $admin_users;
// simple_page_mode(true);
simple_page_mode_crm(true);
function simple_page_mode_crm($numeric_id = true){
	global $Ajax, $Mode, $selected_id;

	$default = $numeric_id ? -1 : '';
	$selected_id = get_post('selected_id', $default);
	foreach (array('ADD_ITEM', 'UPDATE_ITEM', 'RESET', 'CLONE') as $m) {
		if (isset($_POST[$m])) {
			$Ajax->activate('_page_body');
			if ($m == 'RESET'  || $m == 'CLONE') 
				$selected_id = $default;
			unset($_POST['_focus']);
			$Mode = $m; return;
		}
	}
	foreach (array('Edit', 'Delete', 'Reply') as $m) {
		foreach ($_POST as $p => $pvar) {
			if (strpos($p, $m) === 0) {
				unset($_POST['_focus']); // focus on first form entry
				$selected_id = quoted_printable_decode(substr($p, strlen($m)));
				$Ajax->activate('_page_body');
				$Mode = $m;
				return;
			}
		}
	}
	$Mode = '';
}
if(isset($_POST['closed'])){
	Update("kv_crm_tickets",array("id"=>$_POST["ticket_id"]),array("inactive"=>1));

	if(trim($_POST['reply']) != ''){
		Insert("kv_crm_tickets_replies",array("ticket_id"=>$_POST["ticket_id"],"comment"=>$_POST['reply'],"from"=>$_SESSION['wa_current_user']->master_id,"to"=>$_POST["to"]));
	}

 	if($is_supplier || $is_supplier){
	 	$row = GetRow('users', array('id'=>$_POST["to"]));
	    // if($row = db_fetch($res))
	    $email = $row;
	    $row1 = GetRow('kv_crm_tickets', array('id'=>$_POST["ticket_id"]));
	  
	    $email1 = $row1;
	    $contact = array('customer_name' => $email['real_name'],"ticket_id"=>$email1['subject'],"from"=>$_SESSION['wa_current_user']->user,"to"=>$_POST["to"]);
		$template = array('slug' => 'auto-close-ticket',  'details' => $contact );
		$to = ['name' => $email['real_name'], 'email' => $email['email']];
		// kv_mail($to, '', '', "html", array(), null, false, $template);
		display_notification(_('Ticket has been closed'));
		$_POST['reply'] ="";
	}else{
		$row = GetRow('users', array('id'=>$_POST["to"]));
	    // if($row = db_fetch($res))
	    $email = $row;
	    $row1 = GetRow('kv_crm_tickets', array('id'=>$_POST["ticket_id"]));	  
	    $email1 = $row1;
	    $contact = array('customer_name' => $email['real_name'],"ticket_id"=>$email1['subject'],"from"=>$_SESSION['wa_current_user']->user,"to"=>$_POST["to"]);
		$template = array('slug' => 'auto-close-ticket',  'details' => $contact );
		$to = ['name' => $email['real_name'], 'email' => $email['email']];
		// kv_mail($to, '', '', "html", array(), null, false, $template);
		display_notification(_('Ticket has been closed'));
		$_POST['reply'] ="";
	}	
}

if (isset($_POST["replied"]) && can_process()) {

	if(!$is_customer || $is_supplier){
		$from_user_type=ST_EMPLOYEE;
		// $to_user_type= $_SESSION['wa_current_user']->user_type;
	}else{
		$from_user_type=$_SESSION['wa_current_user']->user_type;		
		// $to_user_type= ST_EMPLOYEE;
	}

	$reply_id =Insert("kv_crm_tickets_replies",array("ticket_id"=>$_POST["ticket_id"],"comment"=>$_POST['reply'],"from"=>$_SESSION['wa_current_user']->user,"to"=>$_POST["to"],'replies'=>$_POST['reply_id'],'from_user_type'=>$from_user_type));

    if($is_customer || $is_supplier){

	}else{
		$ticket_details =GetRow('kv_crm_tickets',array('id'=>$_POST["ticket_id"]));
		if($ticket_details['from_user_type'] == ST_EMPLOYEE){
			// display_error('ticket from admin');
			$row = GetRow('users', array('id'=>$ticket_details['to']));
			// display_error(json_encode($row));
		}elseif($ticket_details['to_user_type'] == ST_EMPLOYEE){
			// display_error('ticket to admin');
			$row = GetRow('users', array('id'=>$ticket_details['master_id']));
			// display_error(json_encode($row));
		}
        $email = $row;

        // $row1 = GetRow('kv_crm_tickets', array('id'=>$_POST["ticket_id"]));
        $email1 = $ticket_details;
		if(isset($email['email'])){
			$contact = array('customer_name' => (isset($email['real_name']) ? $email['real_name'] : $email['user_id']), 'ticket_url' =>$email1["id"],    'subject'=>$email1['subject'],"from"=>$_SESSION['wa_current_user']->user,"to"=>$_POST["to"]);
			$template = array('slug' => 'ticket-reply',  'details' => $contact );
			$to = ['name' => (isset($email['real_name']) ? $email['real_name'] : $email['user_id']), 'email' => $email['email']];
			// display_error(json_encode($to));
			kv_mail($to, '', '', "html", array(), null, false, $template);
		}
	}

	// if($_SESSION['wa_current_user']->user_type == ST_EMPLOYEE){
		Update("kv_crm_tickets",array("id"=>$_POST["ticket_id"]),array("inactive"=>2));
	// }	
	unset($_POST['reply']);
	$Ajax->activate('_page_body');
	display_notification(_('New Reply has been added'));
}
if(isset($_POST['cancel'])){
	meta_forward($_SERVER['PHP_SELF'], "t_id=".$_POST['ticket_id']);
}

if (isset($_POST['update'])){
	Update("kv_crm_tickets_replies", array('id' => $selected_id) , array("comment" =>$_POST['reply']));
	display_notification(_('Selected reply has been updated'));
	$Mode = 'RESET';
	$_POST['reply'] ="";
}


if ($Mode == 'Delete'){
	if($selected_id =='ticket'){
		Delete('kv_crm_tickets',array('id'=>$_POST['ticket_id']),'0_');
		meta_forward( $path_to_root.'/modules/KvcodesCRM/tickets/');
	}else{
		Delete("kv_crm_tickets_replies",array('id'=>$selected_id));
	}
	display_notification(_('Selected reply has been deleted'));
	$Mode = 'RESET';
}

function can_process(){
	$return = CheckEmpty_nicEdit('reply');
	return $return;
}

if(isset($_POST['submit_reply']) && CheckEmpty_nicEdit('ticket_reply')){
	if($is_customer || $is_supplier){
		$from_user_type=$_SESSION['wa_current_user']->user_type;			
		// $to_user_type= $_SESSION['wa_current_user']->user_type;
	}else{
		$from_user_type=ST_EMPLOYEE;
		// $to_user_type= ST_EMPLOYEE;
	}
	Insert("kv_crm_tickets_replies",array("ticket_id"=>$_POST["ticket_id"],"comment"=>$_POST['ticket_reply'],"from"=>$_SESSION['wa_current_user']->user,"to"=>$_POST["to"], 'replies' => $_POST['reply_id'],'from_user_type'=>$from_user_type));
	// display_error(json_encode($_POST["ticket_id"]));
	 $res = db_query("SELECT user.*, user.real_name AS name FROM ".TB_PREF."users AS user WHERE user.id = ".$_POST["to"], '');   
    if($row = db_fetch($res))
        $email = $row;

    $res1 =db_query("SELECT tickets.*, tickets.subject FROM ".TB_PREF."kv_crm_tickets AS tickets WHERE tickets.id = ".$_POST["ticket_id"], '');   
    if($row1 = db_fetch($res1))
        $email1 = $row1;

	$template = array('slug' => 'ticket-reply',  'details' => ['Click_link' => $_POST["ticket_id"], 'customer_name' => $email['name'],"ticket_id"=>$email1['subject'],"from"=>$_SESSION['wa_current_user']->user,"to"=>$_POST["to"]] );
	// kv_mail($email, '', '', "html", array(), null, false, $template);
}

function CheckEmpty_nicEdit($name){
	if (trim($_POST[$name]) == '')	{
		display_error(_("The $name cannot be empty."));
		set_focus($name);
		return false;
	}
	return true;
}

if (isset($_POST['ticket_id'])) {
start_form();
div_start('Ticket_Details');
start_table(TABLESTYLE_NOBORDER, "width='80%'");

$result = GetDataJoin("kv_crm_tickets AS tickets",array(0=>array("join"=>"LEFT","table_name"=>"users AS users","conditions"=>"tickets.master_id = users.id")),array("tickets.*","users.real_name AS username"),array("tickets.id"=>$_POST['ticket_id']));
$replies = GetDataJoin("kv_crm_tickets_replies AS treplies",array(
	0=>array("join"=>"LEFT","table_name"=>"kv_crm_tickets AS tickets","conditions"=>"tickets.id=treplies.ticket_id"),
	1=>array("join"=>"LEFT","table_name"=>"users AS users","conditions"=>"treplies.from=users.id")),
array("treplies.*","users.real_name AS real_name"),
array("treplies.ticket_id"=>$_POST['ticket_id'],"replies"=>0),
array("treplies.date"=>"ASC"));

$sub_replies  = GetDataJoin("kv_crm_tickets_replies AS treplies",array(
	0=>array("join"=>"LEFT","table_name"=>"kv_crm_tickets AS tickets","conditions"=>"tickets.id=treplies.ticket_id"),
	1=>array("join"=>"LEFT","table_name"=>"users AS users","conditions"=>"treplies.from=users.id")),
array("treplies.*","users.real_name AS real_name"),
array("treplies.ticket_id"=>$_POST['ticket_id'],"replies"=>['0', '', '!=']),
array("treplies.date"=>"ASC"));
$k=0;
$is_closed=false;
$master_role =GetSingleValue('kv_crm_option','option_value',array('option_name'=>'master_role'));
if(! empty($result)){	
	$row = $result[0]; //foreach ($result as $row) {
		if($row['inactive'] ==1){
			$is_closed=true;
		}
		
		if (($row['master_id']==$_SESSION['wa_current_user']->user || ($row['to']== (($is_supplier || $is_customer) ?$_SESSION['wa_current_user']->user:$_SESSION['wa_current_user']->access))) || $master_role == $_SESSION['wa_current_user']->access) {

			if($row['type'] || $row['type_id']){
				global $systypes_array;
				$ref=GetSingleValue('refs','reference',array('type'=>$row['type'],'id'=>$row['type_id']));
				if($ref){
					$view=$systypes_array[$row['type']]." | ".get_trans_view_str($row['type'], $row['type_id'], $ref)." | ";
				}else{
					
					$view=$systypes_array[$row['type']]." | ";
				}
			}else{
				$view ='';
			}

			table_section_title("Replies", 5);
			$title =$row["subject"];
			$to =$row["master_id"];
			start_row();
			alt_table_row_color($k,"");	

			if($row['from_user_type'] ==ST_CUSTOMER){		
				$contact_type ='customer';
				$debtor=GetDataJoinRow('crm_persons', array( 0 => array('join' => 'LEFT', 'table_name' =>'crm_contacts','conditions'=>'crm_persons.id = crm_contacts.person_id'),1=>array('join' => 'LEFT', 'table_name' =>'debtors_master','conditions'=>'crm_contacts.entity_id = debtors_master.debtor_no')), array('debtors_master.name'), array('crm_persons.user_id'=>$row['master_id'],'crm_contacts.type'=>$contact_type));
				$debtor_name=$debtor['name']." - ";
			}elseif($row['from_user_type'] ==ST_SUPPLIER){		
				$contact_type ='supplier';
				$debtor=GetDataJoinRow('crm_persons', array( 0 => array('join' => 'LEFT', 'table_name' =>'crm_contacts','conditions'=>'crm_persons.id = crm_contacts.person_id'),1=>array('join' => 'LEFT', 'table_name' =>'suppliers','conditions'=>'crm_contacts.entity_id = suppliers.supplier_id')), array('suppliers.supp_name'), array('crm_persons.user_id'=>$row['master_id'],'crm_contacts.type'=>$contact_type));
				$debtor_name=$debtor['supp_name']." - ";
			}else{
				$contact_type=null;
				$debtor_name='';
			}

			// label_cell('<b>'.$debtor_name."</b><br> <span style='font-size:12px;'>".$row["username"]."</span><br> <span style='font-size:11px;'>".$systypes_array[$row['from_user_type']].'</span><br>'.sql2date($row['date']).' '.date('h:i a', strtotime($row['date'])),"width = 20% align= center");
			label_cell('<p><b>'.$debtor_name."</b> <span style='font-size:12px;'>".$row["username"]."</span></p><p> <span style='font-size:11px;'>".$systypes_array[$row['from_user_type']].'</span></p><p>'.sql2date($row['date']).' '.date('h:i a', strtotime($row['date']))."</p>","width = 20% align= center");

			label_cell("Topic : <b>".$view.$row["subject"].'</b><br><P>'.htmlspecialchars_decode($row["message"])."</P>");
			if($_SESSION['wa_current_user']->user == $row['master_id'] && !$is_closed && !GetSingleValue('kv_crm_tickets_replies','ticket_id',array('ticket_id'=>$row['id']))){	
				label_cell('');
				edit_button_cell("Edit".'ticket', _("Edit"));
				if(!GetSingleValue('kv_crm_tickets_replies','ticket_id',array('ticket_id'=>$row['id']))){
					delete_button_cell("Delete".'ticket', _("Delete"));
				}else{
					label_cell('');
				}
			}else{
				label_cell('');label_cell('');label_cell('');
			}
			end_row();
		} else{ 
			display_warning(_("You don't have permission to open this ticket."));
			exit();
		}	
}

$k=3;
if(! empty($replies)){
	foreach ($replies as $row) {

		$hr ="<hr>";
		$thr="";
		if(!next($replies)){
			$hr="";
			$thr="<hr >";
		}
		if (true) {
			if($row["id"]>0){
				start_row("id ='".$row['id']."'");
				alt_table_row_color($k,"t_replies");

				if($row['from_user_type'] ==ST_CUSTOMER){		
					$contact_type ='customer';
					$debtor=GetDataJoinRow('crm_persons', array( 0 => array('join' => 'LEFT', 'table_name' =>'crm_contacts','conditions'=>'crm_persons.id = crm_contacts.person_id'),1=>array('join' => 'LEFT', 'table_name' =>'debtors_master','conditions'=>'crm_contacts.entity_id = debtors_master.debtor_no')), array('debtors_master.name'), array('crm_persons.user_id'=>$row['from'],'crm_contacts.type'=>$contact_type));
					$debtor_name=$debtor['name']." - ";
				}elseif($row['from_user_type'] ==ST_SUPPLIER){		
					$contact_type ='supplier';
					$debtor=GetDataJoinRow('crm_persons', array( 0 => array('join' => 'LEFT', 'table_name' =>'crm_contacts','conditions'=>'crm_persons.id = crm_contacts.person_id'),1=>array('join' => 'LEFT', 'table_name' =>'suppliers','conditions'=>'crm_contacts.entity_id = suppliers.supplier_id')), array('suppliers.supp_name'), array('crm_persons.user_id'=>$row['from'],'crm_contacts.type'=>$contact_type));
					$debtor_name=$debtor['supp_name']." - ";
				}else{
					$contact_type=null;
					$debtor_name='';
				}
				label_cell('<p><b>'.$debtor_name."</b> <span style='font-size:12px;'>".$row["real_name"]."</span></p><p> <span style='font-size:11px;'>".$systypes_array[$row['from_user_type']].'</span></p><p>'.sql2date($row['date']).' '.date('h:i a', strtotime($row['date']))."</p>","width = 20% align= center");
				// label_cell('<b>'.$debtor_name."</b><br> <span style='font-size:12px;'>".$row["real_name"]."</span><br> <span style='font-size:11px;'>".$systypes_array[$row['from_user_type']].'</span><br>'.sql2date($row['date']).' '.date('h:i a', strtotime($row['date'])),"width = 20% align= center");
				label_cell("Re : <b>".$title."</b><br><P>".htmlspecialchars_decode($row["comment"])."</P>".$hr,"width=60%");
				
				if( $Mode == 'Reply' &&  $selected_id == $row['id'] ){
					label_cell('');
				} else if(!$is_closed){
					button_cell("Reply".$row['id'],"Reply");
				}else{
					label_cell('');
				}
				if($_SESSION['wa_current_user']->user == $row['from'] && !$is_closed){
					edit_button_cell("Edit".$row['id'], _("Edit"));
					if(GetSingleValue('kv_crm_tickets_replies','ticket_id',array('ticket_id'=>$_POST['ticket_id'],'replies'=>'0'))){
						delete_button_cell("Delete".$row['id'], _("Delete"));
					}else{
						label_cell('');
					}		 				
		 		} else {
		 			label_cell('');
		 			label_cell('');
		 		}
				end_row();
				//for sub replies
				if(!empty($sub_replies)){
					foreach ($sub_replies as $sub_row) {
						if($row['id'] == $sub_row['replies']){							
							start_row();
							alt_table_row_color($k,"t_sub_replies");
							if($row['from_user_type'] ==ST_CUSTOMER){		
								$contact_type ='customer';
								$debtor=GetDataJoinRow('crm_persons', array( 0 => array('join' => 'LEFT', 'table_name' =>'crm_contacts','conditions'=>'crm_persons.id = crm_contacts.person_id'),1=>array('join' => 'LEFT', 'table_name' =>'debtors_master','conditions'=>'crm_contacts.entity_id = debtors_master.debtor_no')), array('debtors_master.name'), array('crm_persons.user_id'=>$row['from'],'crm_contacts.type'=>$contact_type));
								$debtor_name=$debtor['name']." - ";
							}elseif($row['from_user_type'] ==ST_SUPPLIER){		
								$contact_type ='supplier';
								$debtor=GetDataJoinRow('crm_persons', array( 0 => array('join' => 'LEFT', 'table_name' =>'crm_contacts','conditions'=>'crm_persons.id = crm_contacts.person_id'),1=>array('join' => 'LEFT', 'table_name' =>'suppliers','conditions'=>'crm_contacts.entity_id = suppliers.supplier_id')), array('suppliers.supp_name'), array('crm_persons.user_id'=>$row['from'],'crm_contacts.type'=>$contact_type));
								$debtor_name=$debtor['supp_name']." - ";
							}else{
								$contact_type=null;
								$debtor_name='';
							}
							label_cell('<p><b>'.$debtor_name."</b> <span style='font-size:12px;'>".$sub_row["real_name"]."</span></p><p> <span style='font-size:11px;'>".$systypes_array[$sub_row['from_user_type']].'</span></p><p>'.sql2date($sub_row['date']).' '.date('h:i a', strtotime($sub_row['date']))."</p>","width = 20% align= center");

							// label_cell('<b>'.$debtor_name."</b><br> <span style='font-size:12px;'>".$sub_row["real_name"]."</span><br> <span style='font-size:11px;'>".$systypes_array[$sub_row['from_user_type']].'</span><br>'.sql2date($sub_row['date']).' '.date('h:i a', strtotime($sub_row['date'])),"width = 20% align= center");

							label_cell($thr."<P>".htmlspecialchars_decode($sub_row["comment"])."</P>".$hr,"width=60%");

							if($_SESSION['wa_current_user']->user == $sub_row['from'] && !$is_closed){
								label_cell('');
								edit_button_cell("Edit".$sub_row['id'], _("Edit"));
					 			delete_button_cell("Delete".$sub_row['id'], _("Delete"));	
					 		} else {
					 			label_cell('');
					 			label_cell('');
					 			label_cell('');
					 		}
							end_row();
						}
					}	
				}
				if( $Mode == 'Reply' &&  $selected_id == $row['id']){					
					$sub_reply_id=$selected_id;
					$to=$row['from'];
					start_row();
					textarea_cells(_("Reply :"),'ticket_reply',null,90,8);
					echo '<td colspan="3">' .submit("submit_reply","Submit Reply", false).submit("cancel_reply","Cancel", false).'</td>';
					end_row();
				}					
			}
		}	
	}
}
	if ($Mode == 'Edit') {
		if($selected_id =='ticket'){
			meta_forward( $path_to_root.'/modules/KvcodesCRM/tickets/new_ticket.php','t_id='.$_POST['ticket_id']);
		}
		$myrow = GetRow('kv_crm_tickets_replies AS t_replies', array('t_replies.id' => $selected_id, 't_replies.from' => $_SESSION['wa_current_user']->user));
		if($myrow && is_array($myrow)){
			$_POST['reply']  = $myrow["comment"];
		} else 
			display_warning(_("You can't edit this comment(reply)"));
			
		$Ajax->activate('Ticket_Details');
	}
	if($Mode == 'Edit_ticket'){}
	if ($Mode == 'Reply') {
		$Ajax->activate('Ticket_Details');
	}
	hidden('reply_id', (isset($sub_reply_id)? $sub_reply_id  : 0));
	hidden('selected_id', $selected_id);
	hidden('ticket_id', $_POST['ticket_id']);
	hidden('to', $to);

	if (!$is_closed) {
		label_row('', '&nbsp;');
		textarea_row(_("Reply :"),'reply',null,90,8);
		end_table(1);
		div_end();
		if ($Mode == 'Edit') {
			submit_center_first("update","Update");
			submit_center_last("cancel","Cancel");	
		} else {
			submit_center_first("replied","Reply");
			submit_center_last("closed","Close");	
		}
		end_form();
	}
}
end_page();

?>
<style>
	tr.t_sub_replies td:nth-child(1)	p {line-height: 12px;}
	tr.t_replies td:nth-child(1)	p{line-height: 12px;}

	tr.t_sub_replies td:nth-child(2)	p {line-height: 1.5em;text-align: justify;}
	tr.t_replies td:nth-child(2)	p{line-height: 1.5em;text-align: justify;}

	tr.t_sub_replies td:nth-child(2){ background-color: #edf1f5 !important;padding-left: 7%;}
	tr.t_sub_replies td:nth-child(3){ background-color: #edf1f5 !important;}
	tr.t_sub_replies td:nth-child(4){ background-color: #edf1f5 !important;}
	tr.t_sub_replies td:nth-child(5){ background-color: #edf1f5 !important;}		

	tr.t_replies td:nth-child(2){ background-color: #edf1f5 !important;padding-left: 3%;}
	tr.t_replies td:nth-child(3){ background-color: #edf1f5 !important;}
	tr.t_replies td:nth-child(4){ background-color: #edf1f5 !important;}
	tr.t_replies td:nth-child(5){ background-color: #edf1f5 !important;}	
}	
</style>
