<?php  
$path_to_root="../../..";
$page_security = 'SA_OPEN';
include_once($path_to_root . "/includes/session.inc");
page(_($help_context = "Tickets"));
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/modules/KvcodesCRM/includes/crm.inc" );
include_once($path_to_root . "/modules/KvcodesCRM/tickets/includes/ui/ticket_list.inc" );
global $systypes_array;
simple_page_mode(true);
// display_error(json_encode($_SESSION['wa_current_user']));

if(isset($_GET['Added']) && $_GET['Added'] == 'yes')
	display_notification(_("New Ticket Created Successfully"));

$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);

function get_tickets($is_supplier, $is_customer){
		
		$userid = $_SESSION['wa_current_user']->user;
		$master_role =GetSingleValue('kv_crm_option','option_value',array('option_name'=>'master_role'));

		$filters=array();
		if (isset($_POST["status"]) && $_POST['status'] > 0 ) {
			$filters["tickets.inactive"] = $_POST['status']-1;			
		} 

		$sql ="SELECT IF(tickets.from_user_type=".ST_CUSTOMER.",debtors_master.name,(IF(tickets.from_user_type=".ST_SUPPLIER.",suppliers.supp_name,''))) AS deb_name, ";

		$sql .="IF(tickets.to_user_type=".ST_EMPLOYEE.",security_roles.role,user.real_name) AS role,

		tickets.id  AS id,tickets.date,tickets.subject AS subject,tickets.master_id AS master_id,tickets.from_user_type AS from_user_type,tickets.to_user_type AS to_user_type, tickets.inactive AS status,COUNT(treplies.ticket_id) AS replies,users.real_name AS real_name FROM ".TB_PREF."kv_crm_tickets AS tickets  
		LEFT JOIN ".TB_PREF."kv_crm_tickets_replies AS treplies ON tickets.id =treplies.ticket_id 
		LEFT JOIN ".TB_PREF."users AS users ON tickets.master_id = users.id  
		LEFT JOIN ".TB_PREF."security_roles AS security_roles ON security_roles.id =tickets.to  
		LEFT JOIN ".TB_PREF."users AS user ON user.id =tickets.to  ";

		$sql.="LEFT JOIN ".TB_PREF."crm_persons AS crm_persons ON crm_persons.user_id =tickets.master_id  
		LEFT JOIN ".TB_PREF."crm_contacts AS crm_contacts ON crm_persons.id =crm_contacts.person_id AND  (crm_contacts.type='customer' OR crm_contacts.type='supplier')
		LEFT JOIN ".TB_PREF."debtors_master AS debtors_master ON debtors_master.debtor_no =crm_contacts.entity_id 
		LEFT JOIN ".TB_PREF."suppliers AS suppliers ON suppliers.supplier_id =crm_contacts.entity_id ";

		if($is_customer || $is_supplier){				
			$filter['tickets.to']=$_SESSION['wa_current_user']->user;
			$filter['tickets.master_id']=$_SESSION['wa_current_user']->user;
			
			$sql .="WHERE (tickets.to =".$filter['tickets.to']." OR tickets.master_id =".$filter['tickets.master_id'].")";
		}else{

			if($master_role == $_SESSION['wa_current_user']->access){
				$condition = '1';
			} else {
				$filter['tickets.to']=$_SESSION['wa_current_user']->access;
				$condition = "tickets.to =".$filter['tickets.to'];
			}
			if(isset($_POST['user_type']) && $_POST['user_type']>0){

				if(isset($_POST['master_id']) && $_POST['master_id'] !=''){
					$filter['tickets.master_id'] =$_POST['master_id'];
					$filter['tickets.to'] =$_SESSION['wa_current_user']->access;
					if($master_role == $_SESSION['wa_current_user']->access){
						$sql .="WHERE ((tickets.master_id =".$filter['tickets.master_id'].") OR (tickets.to =".$filter['tickets.master_id']."))";	
					}else{

						$sql .="WHERE (( tickets.to =".$filter['tickets.to']." AND  tickets.master_id =".$filter['tickets.master_id'].") OR (tickets.master_id =".$_SESSION['wa_current_user']->user." AND tickets.to =".$filter['tickets.master_id']."))";
					}

				}else{
					$filter['tickets.from_user_type']=ST_EMPLOYEE;
					$filter['tickets.to_user_type']=$_POST['user_type'];

					if($master_role == $_SESSION['wa_current_user']->access){
						$sql .="WHERE (( tickets.from_user_type =".$filter['tickets.to_user_type'].") OR ( tickets.to_user_type =".$filter['tickets.to_user_type']."))" ;
					}else{
						$sql .="WHERE (( tickets.from_user_type =".$filter['tickets.from_user_type']." AND  tickets.to_user_type =".$filter['tickets.to_user_type'].") OR (tickets.from_user_type =".$filter['tickets.to_user_type']." AND  tickets.to_user_type =".$filter['tickets.from_user_type']."))" ;	
					}
				}

			}else{
				//$filter['tickets.to']=$_SESSION['wa_current_user']->access;
				$filter['tickets.master_id']=$_SESSION['wa_current_user']->user;
					$sql .="WHERE ( ".$condition." OR tickets.master_id =".$filter['tickets.master_id'].")";
			}
		}

		if (isset($_POST["status"]) && $_POST['status'] > 0 ) {
			// display_error($filters["tickets.inactive"]);
			$sql .=" AND tickets.inactive =".$filters["tickets.inactive"];
		}
		$sql .=" GROUP BY  tickets.id ORDER BY  tickets.date DESC, treplies.date DESC LIMIT 100";
		$result = db_query($sql, "Could not get data!");
        $data = array();
        if(db_num_rows($result) > 0 ) {
            while($row = db_fetch($result)) {
                $data[] = $row;
            }
            return $data;
        } else {
            return false;
        }
}

start_form();
// if(list_updated('user_type')){
// 	$_POST['customer_id']='';
// 	$_POST['supplier_id']='';
// 	$Ajax->activate('DetailsListing');
// 	// $Ajax->activate('type_id');
// }
if(list_updated('master_id') || list_updated('status')){
	$Ajax->activate('TicketDetails');
}
div_start('DetailsListing');
// start_table(TABLESTYLE_NOBORDER, "width='80%'");
start_outer_table(TABLESTYLE2, "");
table_section(1);
	if(!$is_customer && !$is_supplier){
		start_row();
		user_types_cells(_('Ticket From : '),'user_type',null,true,_("All"));	
		end_row();
		table_section(2);
		// div_start('user_type_list');
		start_row();
		if(false)
			$id_ = 'pr.user_id AS id';
		else 
			$id_ = 'pr.id AS id';
		if($_POST['user_type'] ==ST_CUSTOMER){		
			$contact_type ='customer';
			
			$sql ="SELECT $id_, concat(pr.name,' - ',deb.name )AS name  FROM ".TB_PREF."crm_persons as pr LEFT JOIN ".TB_PREF."crm_contacts as cn ON pr.id = cn.person_id AND cn.type='customer' LEFT JOIN ".TB_PREF."debtors_master as deb ON cn.entity_id = deb.debtor_no WHERE  cn.type= '".$contact_type."' ";
			if(false)
				$sql .= "AND pr.user_id > 0 ";
			$sql .= " GROUP BY pr.id";
			echo combo_input('master_id', null, $sql, 'id', 'name',array('order'=>false,'spec_option' =>_('No Customer Selected'),'select_submit' =>true));
		}
		if($_POST['user_type'] ==ST_SUPPLIER){
			$contact_type ='supplier';
			$sql ="SELECT $id_, concat(pr.name,' - ',sup.supp_name )AS name  FROM ".TB_PREF."crm_persons as pr LEFT JOIN ".TB_PREF."crm_contacts as cn ON pr.id = cn.person_id AND cn.type='supplier' LEFT JOIN ".TB_PREF."suppliers as sup ON cn.entity_id = sup.supplier_id WHERE  cn.type= '".$contact_type."' ";
			if(false)
				$sql .= "AND pr.user_id > 0 ";
			$sql .= " GROUP BY pr.id";
			echo combo_input('master_id', null, $sql, 'id', 'name',array('order'=>false,'spec_option' =>_('No Supplier Selected'),'select_submit' =>true));
		}
		end_row();		
	}
table_section(2);
start_row();  
     ticket_status_list_cells("Status","status",null, true, true);    

end_row();
table_section(3);
start_row();
echo '<td> <a href="'.$path_to_root.'/modules/KvcodesCRM/tickets/new_ticket.php" > Create New Ticket </a> </td> ';
end_row();
end_outer_table(1);
div_end();
br();
div_start("TicketDetails");
start_table(TABLESTYLE, "width='80%'");
$k=0;
$th = array (_('Posted By'),_('Tickets'), _('Replies'),_('Status'));
$master_role =GetSingleValue('kv_crm_option','option_value',array('option_name'=>'master_role'));
table_header($th);
$result=get_tickets($is_supplier,$is_customer);
if(! empty($result)){
foreach ($result as $row) {
	start_row();
		if($row['status'] == 0 )
		$bg = 'opened';
	else
	if($row['status'] ==1 )
		$bg = 'Closed';
	else
		if($row['status'] ==2 )
		$bg = 'Replied';
	else
		$bg = null;
	alt_table_row_color($k, $bg);
	if($master_role == $_SESSION['wa_current_user']->access){
			$role="<br><span style='font-size:10px;'> Posted To :- ".$row['role']." (".$systypes_array[$row['to_user_type']].") </span>";
	}else{
		$role='';
	}

	label_cell('<p><b>'.$row['deb_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");
		if($row["status"]==0){
			hyperlink_params_td("ticket_replies.php","<b>".$row["subject"].$role."</b>","t_id=".$row['id']);
		}else{
			hyperlink_params_td("ticket_replies.php",$row["subject"].$role,"t_id=".$row['id']);
		}	

		label_cell($row["replies"],'align=center');
		if($row["status"]==0) label_cell(_('Opened'), 'align=center');
		if($row["status"]==1) label_cell(_('Closed'), 'align=center');
		if($row["status"]==2) label_cell(_('Replied'), 'align=center');
	end_row();	
	}
}else{
	label_cell("No tickets found !","colspan='4';");
}	
end_table(1);
div_end();
div_end();
end_form();
end_page();
?>
<style>
tr.opened td:nth-child(4){  color: #ff0000 !important;}
tr.Replied td:nth-child(4){  color: #3854d1 !important;}
p {    margin: 0;    line-height: 20px;}
</style>