<?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 . "/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);

$is_customer =GetSingleValue('debtors_master','debtor_no',array('user_id'=>$_SESSION['wa_current_user']->user));
$is_supplier =GetSingleValue('suppliers','supplier_id',array('user_id'=>$_SESSION['wa_current_user']->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['customer_id']) && $_POST['customer_id'] ==''){
		display_error(_("No Customer Selected"));
		set_focus('customer_id');
		return false;
	}
	if($_POST['user_type']==ST_SUPPLIER && isset($_POST['supplier_id']) && $_POST['supplier_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['customer_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));
	    echo 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(isset($_POST['customer_id']) && $_POST['customer_id'] !=''){
				$master_id =GetSingleValue("debtors_master",'user_id',array('debtor_no'=>$_POST['customer_id']));
			}elseif(isset($_POST['supplier_id']) &&$_POST['supplier_id'] !=''){
				$master_id =GetSingleValue("suppliers",'user_id',array('supplier_id'=>$_POST['supplier_id']));
			}
		}
			

		$sub_ticket = array("subject"=>$_POST['subject'], "message"=>$_POST["description"],'to'=>$master_id,"type"=>$_POST['type'],'type_id'=>$_POST['type_id']);
		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['ticket_id']);
}

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


	if($is_customer || $is_supplier){
			$master_id =$_POST['to_role'];
	}else{
		if(isset($_POST['customer_id']) && $_POST['customer_id'] !=''){
			$master_id =GetSingleValue("debtors_master",'user_id',array('debtor_no'=>$_POST['customer_id']));
		}elseif(isset($_POST['supplier_id']) &&$_POST['supplier_id'] !=''){
			$master_id =GetSingleValue("suppliers",'user_id',array('supplier_id'=>$_POST['supplier_id']));
		}
	}

	$sub_ticket = array("master_id"=>$_SESSION['wa_current_user']->user,"company_id"=>$_SESSION['wa_current_user']->company,'customer_id' => 0, "subject"=>$_POST['subject'], "message"=>$_POST["description"],'to'=>$master_id,'type'=>$_POST['type'],'type_id'=>$_POST['type_id']);
	$ticket_id =Insert("kv_crm_tickets",$sub_ticket);

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

	if($is_supplier || $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{
		$row = GetRow('users', array('id'=>$master_id));
        $email = $row;

		$contact = array('customer_name' => $email['real_name'],"ticket_id"=>$ticket_id,"from"=>$_SESSION['wa_current_user']->user,"to"=>$email["to"]);
		$template = array('slug' => 'new-ticket-opened-admin',  'details' => $contact );
		 $template['details']['subject'] = $sub_ticket['subject'];
	    $template['details']['message'] = $sub_ticket['message'];
		$to = ['name' => $email['real_name'], 'email' => $email['email']];
		kv_mail($to, '', '', "html", array(), null, false, $template);

		}
	// meta_forward( $path_to_root.'/modules/KvcodesCRM/tickets/ticket_replies.php','t_id='.$ticket_id ); 


// $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($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{
			if($customer_id=GetSingleValue('debtors_master','debtor_no',array('user_id'=>$_POST['to']))){
					$_POST['user_type'] =ST_CUSTOMER;
					$_POST['customer_id']=$customer_id;
					hidden('customer_id',$_POST['customer_id']);
				}
				elseif($supplier_id=GetSingleValue('suppliers','supplier_id',array('user_id'=>$_POST['to']))){
					$_POST['user_type'] =ST_SUPPLIER;
					$_POST['supplier_id']=$supplier_id;
					hidden('supplier_id',$_POST['supplier_id']);

			}
		}
		table_section(1);
		if(GetSingleValue('kv_crm_tickets_replies','ticket_id',array('ticket_id'=>$_POST['t_id']))){
			$has_replies =true;
			hidden('type_id',$_POST['type_id']);
			hidden('type',$_POST['type']);
			hidden('to_role',$_POST['to']);

				if(isset($_POST['customer_id'])){
					label_row('Tiket To : ',GetSingleValue('users','real_name',array('id'=>$_POST['to']))."  (Customer)");
					
					hidden('customer_id',$customer_id);
					hidden('supplier_id','');
				}
				elseif(isset($_POST['supplier_id'])){
					label_row('Tiket To : ',GetSingleValue('users','real_name',array('id'=>$_POST['to']))."  (Supplier)");
					
					hidden('supplier_id',$supplier_id);
					hidden('customer_id','');
				}

			label_row('Ticket Type :',$systypes_array[ST_SALESINVOICE]);
		}
	}else{
		display_warning('Ticket Not Found !');
		end_outer_table();
		exit();		
	}
}


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

	table_section(1);
	if(!$is_customer && !$is_supplier){
		start_row();
		user_types_cells(_('Ticket to : '),'user_type',null,true);	
		table_section(2);
		div_start('user_type_list');
		start_row();
		 	if($_POST['user_type']==ST_CUSTOMER){
				customer_list_cells(_("Select a Customer : "), 'customer_id',null,_('Select Customer'),true);
		 	}elseif($_POST['user_type']==ST_SUPPLIER){
				supplier_list_cells(_("Select a Supplier : "), 'supplier_id',null, _("Select a Supplier"),true);

		 	}
		end_row();
		div_end();
	}else{
		
		crm_deparments_list_row(_("Department:"). "&nbsp;", 'to_role', false, false, false, check_value('show_inactive'));
	}
	
	
	if(isset($_POST['customer_id']) && $_POST['customer_id'] !='' || $is_customer ){
		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['supplier_id']) && $_POST['supplier_id'] !='' || $is_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['supplier_id'])){
		$_POST['supplier_id']='';
		// hidden('supplier_id',$_POST['supplier_id']);
	}
	if(!isset($_POST['customer_id'])){
		$_POST['customer_id']='';
		// hidden('customer_id',$_POST['customer_id']);	
	}
	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((isset($_POST['type']) && $_POST['type'] !='' && $_POST['supplier_id'] ==''&& $_POST['customer_id'] !='' )|| $is_customer ){
		table_section(4);
		div_start('type_id');
		start_row();
			switch ($_POST['type']) {
				case ST_SALESINVOICE:
					$IV = $type_shortcuts[ST_SALESINVOICE];	
	                $ref = "reference";
	                $debtor_no = $is_customer ?$is_customer:$_POST['customer_id'];
	                $sql = "SELECT concat(".TB_PREF."debtor_trans.trans_no, '-',
							".TB_PREF."debtor_trans.type) 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 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";
	               	$debtor_no = $is_customer ?$is_customer:$_POST['customer_id'];
	                $sql = "SELECT concat(".TB_PREF."debtor_trans.trans_no, '-', ".TB_PREF."debtor_trans.type) 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 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";
	                $debtor_no = $is_customer ?$is_customer:$_POST['customer_id'];
	                $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 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";
	               $debtor_no = $is_customer ?$is_customer:$_POST['customer_id'];
	                $sql = "SELECT concat(".TB_PREF."debtor_trans.trans_no, '-',
							".TB_PREF."debtor_trans.type) 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 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];
	                $debtor_no = $is_customer ?$is_customer:$_POST['customer_id'];
	                $ref =  "reference";
	                $sql = "SELECT concat(".TB_PREF."debtor_trans.trans_no, '-',
							".TB_PREF."debtor_trans.type) 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 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((isset($_POST['type']) && $_POST['type'] !='' && $_POST['customer_id'] =='' && $_POST['supplier_id'] !='') ||$is_supplier){
		table_section(4);
		div_start('type_id');
		start_row();
		 //    define('ST_PURCHORDER', 18);
			// define('ST_SUPPINVOICE', 20);
			// define('ST_SUPPCREDIT', 21);
			// define('ST_SUPPAYMENT', 22);
			// define('ST_SUPPRECEIVE', 25);
			switch ($_POST['type']) {
				case ST_SUPPINVOICE:
					$IV = $type_shortcuts[ST_SUPPINVOICE];	
	                $ref = "reference";
	                $supplier_id =$_POST['supplier_id'];
	                $sql = "SELECT concat(".TB_PREF."supp_trans.trans_no, '-',
							".TB_PREF."supp_trans.type) 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 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";
	                $supplier_id =$_POST['supplier_id'];
	                $sql = "SELECT concat(".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 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";
	               	$supplier_id =$_POST['supplier_id'];
	                $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 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";
	                $supplier_id =$_POST['supplier_id'];
	                $sql = "SELECT concat(".TB_PREF."supp_trans.trans_no, '-',
							".TB_PREF."supp_trans.type) 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 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];
	                $supplier_id =$_POST['supplier_id'];
	                $ref =  "reference";
	                $sql = "SELECT concat(".TB_PREF."supp_trans.trans_no, '-',
							".TB_PREF."supp_trans.type) 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 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");
// label_row('', '&nbsp;');

// if(!GetSingleValue('debtors_master','user_id',array('user_id'=>$_SESSION['wa_current_user']->user))){
// if ( isset($_GET['t_id'])) {
// 	if(GetSingleValue('kv_crm_tickets_replies','ticket_id',array('ticket_id'=>$_GET['t_id']))){
// 		label_row('Customer',GetSingleValue('users','real_name',array('id'=>$_POST['to'])));
// 		label_row('Company',$db_connections[$_POST['company_id']]['name']);
// 		hidden('company_id',$_POST['company_id']);
// 		hidden('customer_id',$_POST['customer_id']);
// 	}else{
// 		customer_list_cells(_("Select a Customer: "), 'customer_id',5, false,true);
// 		// Companies_list_overall_row(_("Company"), 'company_id', null, true, GetSingleValue("debtors_master",'user_id',array('debtor_no'=>get_post('customer_id'))));
// 		hidden('company_id',$_POST['company_id']); 
// 		hidden('customer_id',$_POST['customer_id']);
// 	}
// }else{
// 	// customer_list_cells(_("Select a Customer: "), 'customer_id',0, true,true);
// }

// }
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'])){
	// if ($result['company_id']==$_SESSION['wa_current_user']->company||$_SESSION['wa_current_user']->company ==0) {
		submit_center("update","Update");	
	// }
}else{
	submit_center("post","Submit");
}


end_form();
end_page();
?>
