<?php  
$path_to_root="../../..";
$page_security = 'SA_OPEN';
include_once($path_to_root . "/includes/session.inc");
page(_($help_context = "Post Tickets"));
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/tickets/includes/ui/ticket_list.inc" );
global $systypes_array;
simple_page_mode(true);

check_db_has_customers(_("There are no customers defined in the system."));

check_db_has_suppliers(_("There are no suppliers defined in the system."));

$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);
// display_error(json_encode($_SESSION['wa_current_user']));
function can_process(){
	if (strlen($_POST['subject']) == 0)	{
		display_error(_("The subject cannot be empty."));
		set_focus('subject');
		return false;
	}
	if($_POST['user_type']==ST_CUSTOMER && isset($_POST['master_id']) && $_POST['master_id'] ==''){
		display_error(_("No Customer Selected"));
		set_focus('customer_id');
		return false;
	}
	if($_POST['user_type']==ST_SUPPLIER && isset($_POST['master_id']) && $_POST['master_id'] ==''){
		display_error(_("No Supplier Selected"));
		set_focus('supplier_id');
		return false;
	}
	if (strlen($_POST['description']) == 0)	{
		display_error(_("The description cannot be empty."));
		set_focus('description');
		return false;
	}
	return true;
}

function email_tickets($customer_id, $company_id, $details, $template='subscription'){
    // global $db;
	if($_SESSION['wa_current_user']->company ==0){
	    $res = db_query("SELECT user.*, deb.*, deb.name AS customer_name FROM  0_debtors_master AS deb 
	        LEFT JOIN 0_users AS user ON deb.user_id = user.id WHERE deb.debtor_no = ".$_POST['master_id'], '');

	    if($row = db_fetch($res))
	        $email = $row;
	    //echo $template;
	    $template = ['slug' => $template];
	    // $email['company_name'] = $company_id;
	    $template['details']['customer_name'] = $email['customer_name'];
	    $template['details']['subject'] = $details['subject'];
	    $template['details']['message'] = $details['message'];
	   // display_error(json_encode($template));
	     kv_mail($email, '', '', "html", array(), null, false, $template);
	}
}
      
if (isset($_POST["update"]) && can_process()) {
		if($is_customer || $is_supplier){
			$master_id =$_POST['to_role'];
		}else{
			if($_POST['user_type']==ST_CUSTOMER  && isset($_POST['master_id']) && $_POST['master_id'] !=''){
				$master_id =GetSingleValue("crm_persons",'user_id',array('id'=>$_POST['master_id']));
			}elseif($_POST['user_type']==ST_SUPPLIER && isset($_POST['master_id']) &&$_POST['master_id'] !=''){
				$master_id =GetSingleValue("crm_persons",'user_id',array('id'=>$_POST['master_id']));
			}
		}	

		$sub_ticket = array("subject"=>$_POST['subject'], "message"=>$_POST["description"],'to'=>$master_id,"type"=>$_POST['type'],'type_id'=>isset($_POST['type_id'])?input_num('type_id'):0);
		Update('kv_crm_tickets',array('id'=>$_POST['t_id']),$sub_ticket);
		meta_forward( $path_to_root.'/modules/KvcodesCRM/tickets/ticket_replies.php','t_id='.$_POST['t_id']);
}

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

	if($is_customer || $is_supplier){
			$master_id =$_POST['to_role'];
	}else{
		if($_POST['user_type']==ST_CUSTOMER  && isset($_POST['master_id']) && $_POST['master_id'] !=''){
				$master_id =GetSingleValue("crm_persons",'user_id',array('id'=>$_POST['master_id']));
			}elseif($_POST['user_type']==ST_SUPPLIER && isset($_POST['master_id']) &&$_POST['master_id'] !=''){
				$master_id =GetSingleValue("crm_persons",'user_id',array('id'=>$_POST['master_id']));
			}
		// $master_id =$_POST['person_user_id'];
	}

	if($is_customer || $is_supplier){	
		$from_user_type=$_SESSION['wa_current_user']->user_type;		
		$to_user_type= ST_EMPLOYEE;
	}else{
		$from_user_type=ST_EMPLOYEE;
		$to_user_type= $_POST['user_type'];		
	}
	
	$sub_ticket = array("master_id"=>$_SESSION['wa_current_user']->user,'to_user_type' => $to_user_type,'from_user_type' => $from_user_type, "subject"=>$_POST['subject'], "message"=>$_POST["description"],'to'=>$master_id,'type'=>$_POST['type'],'type_id'=>isset($_POST['type_id'])?input_num('type_id'):0);
	$ticket_id =Insert("kv_crm_tickets",$sub_ticket);

	$sub_ticket['subject'] = $_POST['subject'];
	$sub_ticket['message'] = $_POST['description'];

	if($is_customer || $is_supplier){
	  //   	foreach (GetAll('users',array('role'=>)) as $key => $value) {
	  //   		# code...
	  //   	}
	  //   	$row = GetRow('users', array('id'=>$_POST["to"]));
	  //       $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' => 'ticket-reply',  'details' => $contact );
		// $to = ['name' => $email['real_name'], 'email' => $email['email']];
		// kv_mail($to, '', '', "html", array(), null, false, $template);
	}else{
		$email = GetRow('users', array('id'=>$master_id));
        //$email = $row;
		if(isset($email['email'])){
			$ticket_department = GetSingleValue('security_roles', 'role', ['id' => $_SESSION['wa_current_user']->access]);
			$contact = array('customer_name' => (isset($email['real_name']) ? $email['real_name'] : $email['user_id']),"ticket_id"=>$ticket_id, 'ticket_subject' => $_POST['subject'], 'ticket_department' => $ticket_department, 'ticket_priority' => 'high', 
			'ticket_message' => $_POST['description']);
			$template = array('slug' => 'new-ticket-opened-admin',  'details' => $contact );
			$template['details']['subject'] = $sub_ticket['subject'];
			$template['details']['message'] = $sub_ticket['message'];
			$to = ['name' => (isset($email['real_name']) ? $email['real_name'] : $email['user_id']), 'email' => $email['email']];
			kv_mail($to, '', '', "html", array(), null, false, $template);
		}
	}
	meta_forward( $path_to_root.'/modules/KvcodesCRM/tickets/index.php?Added=yes' ); 

// $sub_ticket['subject'] = $_POST['subject'];
// $sub_ticket['message'] = $_POST['description'];
// 	email_tickets(0,$_SESSION['wa_current_user']->company, $sub_ticket,'new-ticket-created-staff');
 // if($_SESSION['wa_current_user']->company ==0){
// $res = db_query("SELECT * FROM 0_users WHERE role_id  <> 2", '');   
// display_error(db_num_rows($res));
//  if($row = db_fetch($res))
//  	$email = $row;
//  	display_error(json_encode($email));
// display_error(json_encode($res['email']));
//  //        $email = $res;
// display_error(json_encode($_SESSION['wa_current_user']->master_id));
// //  $template =['slug' => 'new-ticket-created-staff'];
// //  $email['company_name'] = $_SESSION['wa_current_user']->company;
// //  $email['subject'] = $_POST['subject'];
// //  $email['message'] = $_POST["description"];

// // $template['details']['company_name'] = $email['company_name'];
// // $template['details']['subject'] = $email['subject'];
// // $template['details']['message'] = $email['message'];
// $contact = array("master_id"=>$_SESSION['wa_current_user']->master_id,"company_id"=>$_SESSION['wa_current_user']->company,"subject"=>$_POST['subject'],"message"=>$_POST["description"]);
// $template = array('slug' => 'new-ticket-created-staff',  'details' => $contact );
// // $template = array('slug' => 'new-ticket-created-staff');
// display_error(json_encode($template));

// kv_mail($res, '', '', "html", array(), null, false, $template);

	display_notification(_('New ticket has been posted'));
}

start_form();
start_outer_table(TABLESTYLE2, "");
$has_replies =false;
if (isset($_GET['t_id'])) {
	$_POST['t_id'] =$_GET['t_id'];
	hidden('t_id',$_POST['t_id']);	
}
if (isset($_GET['t_id'])) {
	$result =GetRow('kv_crm_tickets',array('id'=>$_POST['t_id']));
	if($result){
		if(GetSingleValue('kv_crm_tickets_replies','ticket_id',array('ticket_id'=>$_POST['t_id']))){
			display_warning('Cannot Edit this Ticket!');
			exit();
		}
		if($result['master_id'] !=$_SESSION['wa_current_user']->user){
			display_warning('Ticket Not Found !');
			exit();
		}
		$_POST['subject']=$result['subject'];
		$_POST['description']=$result['message'];
		$_POST['to']=$result['to'];
		$_POST['to_role']=$result['to'];
		$_POST['type']=$result['type'];
		$_POST['type_id']=$result['type_id'];
		if($is_customer || $is_supplier){
			$_POST['to_role'] =$_POST['to'];
		}else{
			$_POST['user_type']=$result['to_user_type'];
			$_POST['master_id']=GetSingleValue('crm_persons','id',array('user_id'=>$result['to']));
		}
		table_section(1);
		
	}else{
		display_warning('Ticket Not Found !');
		end_outer_table();
		exit();		
	}
}

if(list_updated('user_type')){
	//$_POST['master_id']='';
	//$_POST['master_id']='';
	$_POST['type']='';
	$Ajax->activate('user_type_list');
	$Ajax->activate('type');
	// $Ajax->activate('type_id');
}
if(list_updated('master_id')){	
	//$_POST['master_id']='';
	// hidden('supplier_id',$_POST['master_id']);
	$Ajax->activate('type');
	$Ajax->activate('type_id');
	
 }//if(list_updated('supplier_id')){
// 	$_POST['master_id']='';
// 	// hidden('customer_id',$_POST['master_id']);
// 	$Ajax->activate('type');
// 	$Ajax->activate('type_id');
// }
if(list_updated('type')){
	$Ajax->activate('type_id_div');
}
if(!$has_replies){

	table_section(1);
	if(!$is_customer && !$is_supplier){
		start_row();
		user_types_cells(_('Ticket to : '),'user_type',null,true);	
	}else{
		
		crm_deparments_list_row(_("Department:"). "&nbsp;", 'to_role', false, false, false, check_value('show_inactive'));
		if($is_customer){
			$_POST['user_type'] = ST_CUSTOMER;
			$_POST['master_id'] = $is_customer;
		}
		elseif($is_supplier){
			$_POST['user_type'] = ST_SUPPLIER;		
			$_POST['master_id'] = $is_supplier;
		}
		hidden('user_type', $_POST['user_type']);
	}
		
	if((!$is_customer && !$is_supplier) ){

		if($_POST['user_type'] ==ST_CUSTOMER){
			table_section(2);
			div_start('user_type_list');
			start_row();
			$contact_type ='customer';

			$sql ="SELECT pr.id AS 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,'select_submit' =>true));
			 end_row();
			div_end();
		}
		if($_POST['user_type'] ==ST_SUPPLIER){
			table_section(2);
			div_start('user_type_list');
			start_row();
			$contact_type ='supplier';
			$sql ="SELECT pr.id AS 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 pr.user_id > 0 AND 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,'select_submit' =>true));
			 end_row();
			div_end();
		}
	}
	if($_POST['user_type']==ST_CUSTOMER && (isset($_POST['master_id']) && $_POST['master_id'] !='') ){
		table_section(3);
		div_start('type');
		start_row();
		customer_ticket_types_cells(_('Select a Type : '),'type',null,true,_('Select a Type'));
		end_row();
		div_end();
	}
	if((isset($_POST['master_id']) && $_POST['master_id'] !='' ) && $_POST['user_type']==ST_SUPPLIER ){

		table_section(3);
		div_start('type');
		start_row();
		supplier_ticket_types_cells(_('Select a Type : '),'type',null,true,_('Select a Type'));
		end_row();
		div_end();
	}

	if(!isset($_POST['type_id'])){
		$_POST['type_id']='';
		hidden('type_id',$_POST['type_id']);
	}
	if(!isset($_POST['type'])){
		$_POST['type']='';
		hidden('type',$_POST['type']);		
	}

	if(($_POST['user_type']==ST_CUSTOMER &&  (isset($_POST['type']) && $_POST['type'] !='' && $_POST['master_id'] > 0)) || $is_customer ){
		table_section(4);
		div_start('type_id_div');
		start_row();
		$debtor_no = $is_customer ?$is_customer:GetSingleValue('crm_contacts','entity_id',array('type'=>'customer','person_id'=>$_POST['master_id']));
			switch ($_POST['type']) {
				case ST_SALESINVOICE:
					$IV = $type_shortcuts[ST_SALESINVOICE];	
	                $ref = "reference";
	           
	                $sql = "SELECT ".TB_PREF."debtor_trans.trans_no AS TNO, concat('$IV ', ".TB_PREF."debtor_trans.$ref,' ', ".TB_PREF."debtors_master.name) as IName
							FROM ".TB_PREF."debtors_master, ".TB_PREF."debtor_trans WHERE ".TB_PREF."debtor_trans.debtor_no=".$debtor_no." AND type=".ST_SALESINVOICE." AND ".TB_PREF."debtors_master.debtor_no=".TB_PREF."debtor_trans.debtor_no ORDER BY ".TB_PREF."debtor_trans.trans_no DESC";
	                echo combo_input('type_id', '', $sql, 'TNO', 'IName',array('order'=>false));
					break;

				case ST_CUSTDELIVERY:
	                $DN = $type_shortcuts[ST_CUSTDELIVERY];
	                $ref = "reference";
	                $sql = "SELECT ".TB_PREF."debtor_trans.trans_no AS TNO, concat(".TB_PREF."debtor_trans.trans_no, ' $DN ',
						 ".TB_PREF."debtors_master.name) as IName 
							FROM ".TB_PREF."debtors_master, ".TB_PREF."debtor_trans
							WHERE ".TB_PREF."debtor_trans.debtor_no=".$debtor_no." AND type=".ST_CUSTDELIVERY." AND ".TB_PREF."debtors_master.debtor_no=".
	                    TB_PREF."debtor_trans.debtor_no ORDER BY ".TB_PREF."debtor_trans.trans_no DESC";
	                echo  combo_input('type_id', '', $sql, 'TNO', 'IName',array('order'=>false));
	                break;
	            case ST_SALESORDER:
	                $ref = "reference";
	                $sql = "SELECT ".TB_PREF."sales_orders.order_no, concat(".TB_PREF."sales_orders.$ref, '-',
							".TB_PREF."debtors_master.name) as IName
							FROM ".TB_PREF."debtors_master, ".TB_PREF."sales_orders WHERE ".TB_PREF."sales_orders.debtor_no=".$debtor_no." AND ".TB_PREF."debtors_master.debtor_no=".TB_PREF."sales_orders.debtor_no 
							AND ".TB_PREF."sales_orders.trans_type=".ST_SALESORDER." ORDER BY ".TB_PREF."sales_orders.order_no DESC";
	                echo combo_input('type_id', '', $sql, 'order_no', 'IName',array('order'=>false));
	                break;
				case ST_CUSTCREDIT:
	                $CN = $type_shortcuts[ST_CUSTCREDIT];
	                $ref = "reference";
	                $sql = "SELECT ".TB_PREF."debtor_trans.trans_no AS TNO, concat('$CN ', ".TB_PREF."debtor_trans.$ref,' ', ".TB_PREF."debtors_master.name) as IName
							FROM ".TB_PREF."debtors_master, ".TB_PREF."debtor_trans WHERE ".TB_PREF."debtor_trans.debtor_no=".$debtor_no." AND type=".ST_CUSTCREDIT." AND ".TB_PREF."debtors_master.debtor_no=".TB_PREF."debtor_trans.debtor_no ORDER BY ".TB_PREF."debtor_trans.trans_no DESC";
	                echo combo_input('type_id', '', $sql, 'TNO', 'IName',array('order'=>false));
	                break;
	            case ST_CUSTPAYMENT:
	                $CP = $type_shortcuts[ST_CUSTPAYMENT];
	                $ref =  "reference";
	                $sql = "SELECT ".TB_PREF."debtor_trans.trans_no AS TNO, concat(".TB_PREF."debtor_trans.$ref, if (type=".ST_BANKDEPOSIT.", ' $CP ', ' $CP '), ".TB_PREF."debtors_master.name) as IName
							FROM ".TB_PREF."debtors_master, ".TB_PREF."debtor_trans WHERE ".TB_PREF."debtor_trans.debtor_no=".$debtor_no." AND (type=".ST_BANKDEPOSIT." OR type=".ST_CUSTPAYMENT." OR type=".ST_CUSTCREDIT.") AND ".TB_PREF."debtors_master.debtor_no=".TB_PREF."debtor_trans.debtor_no ORDER BY ".TB_PREF."debtor_trans.trans_no DESC";
	                echo  combo_input('type_id', '', $sql, 'TNO', 'IName',array('order'=>false));
	                break;
				default:
					break;
			}
			
		end_row();
		div_end();
	}

	if(($_POST['user_type']==ST_SUPPLIER && (isset($_POST['type']) && $_POST['type'] !='' && $_POST['master_id'] > 0) ) ||$is_supplier){
		table_section(4);
		div_start('type_id_div');
		start_row();
		     $supplier_id = $is_supplier ?$is_supplier:GetSingleValue('crm_contacts','entity_id',array('type'=>'supplier','person_id'=>$_POST['master_id']));
			switch ($_POST['type']) {
				case ST_SUPPINVOICE:
					$IV = $type_shortcuts[ST_SUPPINVOICE];	
	                $ref = "reference";
	                
	                $sql = "SELECT ".TB_PREF."supp_trans.trans_no AS TNO, concat('$IV ', ".TB_PREF."supp_trans.$ref,' ', ".TB_PREF."suppliers.supp_name) as IName
							FROM ".TB_PREF."suppliers, ".TB_PREF."supp_trans WHERE ".TB_PREF."supp_trans.supplier_id=".$supplier_id." AND type=".ST_SUPPINVOICE." AND ".TB_PREF."suppliers.supplier_id=".TB_PREF."supp_trans.supplier_id ORDER BY ".TB_PREF."supp_trans.trans_no DESC";
	                echo combo_input('type_id', '', $sql, 'TNO', 'IName',array('order'=>false));
					break;

				case ST_SUPPRECEIVE:
	                $DN = $type_shortcuts[ST_SUPPRECEIVE];
	                $ref = "reference";
	                $sql = "SELECT ".TB_PREF."grn_batch.id AS TNO, concat(".TB_PREF."grn_batch.id, ' $DN ',
						 ".TB_PREF."suppliers.supp_name) as IName 
							FROM ".TB_PREF."suppliers, ".TB_PREF."grn_batch
							WHERE ".TB_PREF."grn_batch.supplier_id=".$supplier_id." AND ".TB_PREF."suppliers.supplier_id=".
	                    TB_PREF."grn_batch.supplier_id ORDER BY ".TB_PREF."grn_batch.id DESC";
	                echo  combo_input('type_id', '', $sql, 'TNO', 'IName',array('order'=>false));
	                break;
	            case ST_PURCHORDER:
	                $ref = "reference";
	                $sql = "SELECT ".TB_PREF."purch_orders.order_no, concat(".TB_PREF."purch_orders.$ref, '-',
							".TB_PREF."suppliers.supp_name) as IName
							FROM ".TB_PREF."suppliers, ".TB_PREF."purch_orders WHERE ".TB_PREF."purch_orders.supplier_id=".$supplier_id." AND ".TB_PREF."suppliers.supplier_id=".TB_PREF."purch_orders.supplier_id 
							ORDER BY ".TB_PREF."purch_orders.order_no DESC";
	                echo combo_input('type_id', '', $sql, 'order_no', 'IName',array('order'=>false));
	                break;
				case ST_SUPPCREDIT:
	                $CN = $type_shortcuts[ST_SUPPCREDIT];
	                $ref = "reference";
	                $sql = "SELECT ".TB_PREF."supp_trans.trans_no AS TNO, concat('$CN ', ".TB_PREF."supp_trans.$ref,' ', ".TB_PREF."suppliers.supp_name) as IName
							FROM ".TB_PREF."suppliers, ".TB_PREF."supp_trans WHERE ".TB_PREF."supp_trans.supplier_id=".$supplier_id." AND type=".ST_SUPPCREDIT." AND ".TB_PREF."suppliers.supplier_id=".TB_PREF."supp_trans.supplier_id ORDER BY ".TB_PREF."supp_trans.trans_no DESC";
	                echo combo_input('type_id', '', $sql, 'TNO', 'IName',array('order'=>false));
	                break;
	            case ST_SUPPAYMENT:
	                $CP = $type_shortcuts[ST_SUPPAYMENT];
	                $ref =  "reference";
	                $sql = "SELECT ".TB_PREF."supp_trans.trans_no AS TNO, concat(".TB_PREF."supp_trans.$ref, if (type=".ST_BANKDEPOSIT.", ' $CP ', ' $CP '), ".TB_PREF."suppliers.supp_name) as IName
							FROM ".TB_PREF."suppliers, ".TB_PREF."supp_trans WHERE ".TB_PREF."supp_trans.supplier_id=".$supplier_id." AND (type=".ST_BANKDEPOSIT." OR type=".ST_SUPPAYMENT." OR type=".ST_SUPPAYMENT.") AND ".TB_PREF."suppliers.supplier_id=".TB_PREF."supp_trans.supplier_id ORDER BY ".TB_PREF."supp_trans.trans_no DESC";
	                echo  combo_input('type_id', '', $sql, 'TNO', 'IName',array('order'=>false));
	                break;
				default:
					break;
			}			
		end_row();
		div_end();
	}	
}
end_outer_table(1);
start_table();	
table_section_title("Post Tickets");

text_row(_("Subject :"), 'subject', null, 60, 50);
label_row('', '&nbsp;');
textarea_row(_("Description :"), 'description', null, 60, 8);
end_table(0);
br();
if(isset($_POST['t_id'])){
	hidden('t_id',$_POST['t_id']);

		submit_center("update","Update");	

}else{
	submit_center("post","Submit");
}

end_form();
end_page();
?>