<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
global $configverssion_id; global $configapp_version; global $userID; global $server; global $LANG; $resellerID = getReseller();
//=== List page stuffs =============
$page = 1; $setLimit = 30;
if(isset($_GET["page"])) $page = (int)$_GET["page"];
$pageLimit = ($page * $setLimit) - $setLimit; 
$pageurl=$_SERVER['REQUEST_URI']."?";
if(count($_GET)) { $pageurl = $_SERVER['REQUEST_URI'].'&'; }
$trans = array("s=d_o" => "", "s=d_n" => "", "s=r_h" => "", "s=r_l" => "", "s=s_r" => "", "s=s_u" => "", "s=s_q" => "", "s=s_c" => "", "s=s_f" => "", "s=s_p" => "");
$pageurl = strtr($pageurl,$trans);
$pageurl = str_replace('&&','&',$pageurl);
//====End ==============
define('TITLE','Tickets');
if(!isAdmin(getUser()) && (userData(getUser(),'phone') == '' || userData(getUser(),'first_name') == '') ) {
	header('location: profile?setting'); exit();
}
if(!isAdmin(getUser()) && userData($userID,'email_verified') != 0) {
	showVerify();
}
if(userRole()==4) {
	header('location: index.php');	
}

$today = date('Y-m-d'); $time = strtotime($today.'-1 months'); $lastMonth = date("Y-m", $time); $time = strtotime($today.'-1 years'); $lastYear = date("Y", $time);

if(isset($_GET['close'])) {
	$userID = getUser();
	$idd = mysqli_real_escape_string($server,$_GET['close']);
	mysqli_query($server, "UPDATE tickets SET status = 'closed' WHERE id = '$idd' AND reseller = '$userID'") or die(mysqli_error($server));
	logEvent($userID,'Closed Ticket ID '.$idd);
	$_SESSION['message'] = $LANG['ticket_close'];
	header('location: rticket?err=0');	
	exit;
}


if(!isset($_GET['ti'])) {
	if(isset($_POST['bulk'])) { 
	  $userID = getUser();
	  if($_POST['action']=='delete') {
		foreach($_POST['bulk'] as $inbid) { 
			mysqli_query($server,"DELETE FROM `tickets` WHERE `id` = '$inbid' AND reseller = '$userID'") or die(mysqli_error($server));
			mysqli_query($server,"DELETE FROM `tickets` WHERE `parent_id` = '$inbid' AND reseller = '$userID'") or die(mysqli_error($server));
			logEvent($userID,'Deleted ticket with ID '.$inbid);
		}	
		$_SESSION['message'] = $LANG['ticket_delete'];
		header('location: rticket?err=0');
	  } else if($_POST['action']=='close') {
		foreach($_POST['bulk'] as $inbid) { 
			mysqli_query($server, "UPDATE tickets SET status = 'closed' WHERE id = '$inbid' AND reseller = '$userID'") or die(mysqli_error($server));
			logEvent($userID,'Closed Ticket ID '.$inbid);
		}	
		$_SESSION['message'] = $LANG['ticket_close'];
		header('location: rticket?err=0');
	  } else {
		  header('location: rticket');
	  }
	}

?>

<div class="row no-m-t no-m-b">
 	<div class="col s12 m12 l12">
        <div class="card blue">
            <div class="card-content white-text"><?=$LANG['rti_intro']?></div>
        </div>
    </div>
 </div>

<div class="row no-m-t no-m-b">
 	<div class="col s12 m12 l12">
        <div class="card card-transparent">
            <div class="card-content">
            	<div class="col s12 m4 l4">
                      <a class='waves-effect waves-light btn green white-text' href='#' onclick="addPB();"><i class="fa fa-plus-circle"></i> <?=$LANG['Create New Ticket']?></a>                
                </div>
                <div class="col s12 m8 l8">
                  <div class="col s12 m12 l12">
                    <div class="row no-m-t no-m-b">
                     <form action="rticket" method="get">
                     <div class="input-field col s12">
                        <i class="material-icons prefix">search</i>
                        <input type="text" name="sc" value="<?=@$_GET['sc']?>" placeholder="<?=$LANG['Search...']?>">
                     </div>
                     </form>  
                    </div>
                  </div> 
                </div>
            </div>
        </div>
    </div>
 </div>
 
 <div class="row no-m-t no-m-b">
       
<?php
	$added  = '';
	if(isset($_GET['sc'])) {
		$keywords = mysqli_real_escape_string($server,$_GET['sc']);
		$ser = explode(' ', $keywords);
		$clauses = array();
		foreach($ser as $look){
			$term = trim($look);   
			if (!empty($term)){
				 $clauses[] = "t.message LIKE '%$term%' OR t.id LIKE '%$term%' OR t.subject LIKE '%$term%' OR t.date LIKE '%$term%' OR t.status LIKE '%$term%'";
			} else {
				 $clauses[] = " t.id LIKE '%%' ";
			}
		}
		$added .= ' AND ('.implode(' OR ', $clauses).') ';		
	}
	if(isset($_GET['s'])) {
		switch($_GET['s']) {
			case 'd_o': $added .= " AND t.status LIKE '%open%' order by t.id DESC ";
			break;
			case 'd_n': $added .= " AND t.status LIKE '%answered%' order by t.id DESC ";
			break;
			case 's_r': $added .= " AND t.status LIKE '%customer-reply%' order by t.id DESC ";
			break;
			case 's_u': $added .= " AND t.status LIKE '%closed%' order by t.id DESC ";
			break;
		}
	} else {
		$added .= " order by t.id DESC ";	
	}

    $query="SELECT t.* FROM tickets t JOIN users u ON t.customer_id = u.id WHERE t.parent_id = 0 AND u.reseller = '$userID' $added limit $pageLimit,$setLimit";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));
	$x = mysqli_num_rows($result);
?>     
     <div class="col s12 m12 l12">
         <div class="card card-white">
         	<div class="card-content">
            	<div class="card-options">
                    <ul>
                        <li><a class='dropdown-button btn btn-flat' href='#' data-activates='filter' data-beloworigin='true' data-constrainwidth='false'><i class="fa fa-sort"></i> <?=$LANG['Filter']?></a></li>
                    </ul>    
                    <ul id='filter' class='dropdown-content'>
                        <li><a href="<?=$pageurl?>" ><?=$LANG['All']?></a></li>
                        <li><a href="<?=$pageurl?>s=d_o" ><?=$LANG['Open']?></a></li>
                        <li><a href="<?=$pageurl?>s=d_n" ><?=$LANG['Answered']?></a></li>
                        <li><a href="<?=$pageurl?>s=s_r" ><?=$LANG['Customer-Reply']?></a></li>
                        <li><a href="<?=$pageurl?>s=s_u" ><?=$LANG['Closed']?></a></li>
                    </ul>
                </div>
            </div>
            <div class="card-content">
            	<div class="card-title">
                    <ul id='bulka' class='dropdown-content'>
                            <li><a href="#" onclick="bulkaction('delete','inbox-form','<?=$LANG['ticket_delete_confirm']?>');"> <i class="fa fa-trash"></i> <?=$LANG['Delete']?></a></li>
                            <li><a href="#" onclick="bulkaction('close','inbox-form','<?=$LANG['ticket_close_confirm']?>');"> <i class="fa fa-times"></i> <?=$LANG['Close']?></a></li>
                    </ul>
                </div>
                <span class="card-title">
                <a class='dropdown-button btn light-blue darken-4' href='#' data-activates='bulka' data-beloworigin='true' data-constrainwidth='false'><?=$LANG['With Selected']?></a>
                </span>
                <table class="highlight responsive-table">
                <?php if($x>0) { ?>
                <thead>
                	<tr>
                    	<th><input type="checkbox" class="filled-in" id="selectall" /><label for="selectall"></label></th>
                        <th data-field="date"><?=$LANG['Date']?></th>
                        <th data-field="user"><?=$LANG['Customer']?></th>
                        <th data-field="to"><?=$LANG['Subject']?></th>
                        <th data-field="credit"><?=$LANG['Status']?></th>
                        <th data-field="cost"><?=$LANG['Last Updated']?></th>
                        <th></th>
                    </tr>
                 </thead>
                 <?php } ?>
                 <tbody>
                 <form action="rticket" method="post" id="inbox-form">
                    	<input type="hidden" id="bulkaction" name="action" value=""/>
<?php $xf=0; while ($rows = mysqli_fetch_assoc($result)) { $xf+=1;
$link = '';
$id = $rows['id'];
$class = '';
$link = '<a href="rticket?ti='.$id.'"><i class="fa fa-search"></i> '.$LANG['View'].'</a>';	
if( ucfirst($rows['status']) != 'Answered' && ucfirst($rows['status']) != 'Closed') {
$class = 'amber lighten-4';	
}
?>
						<tr class="<?=$class?>">
                        	 <td><input type="checkbox" class="filled-in bulk" id="bulk<?=$rows['id']?>" value="<?=$rows['id']?>" name="bulk[<?=$rows['id']?>]"/> <label for="bulk<?=$rows['id']?>"></label></td>
                             <td class=""><?=date('M j, Y h:iA',strtotime($rows['date']))?></td>
                             <td class=""><a href="rcustomer?v=<?=$rows['customer_id']?>"><?=userData($rows['customer_id'],'first_name').' '.userData($rows['customer_id'],'last_name')?></a></td>
                             <td class="">#<?=$id.' - '.$rows['subject']?></td>
                             <td class=""><?=ucfirst($rows['status'])?></td>
                             <td class=""><?=date('M j, Y h:iA',strtotime($rows['last_updated']))?></td>
                             <td><?=$link?></td>
                        </tr>
<?php } ?>
<?php if($xf<1) echo '<tr class="orange lighten-5"><td colspan=10><h5 class="center-align">'.$LANG['No records found!'].'</h5></td></tr>' ?>	
					</form>
                 </tbody>
            </table>          
     	</div>
  	</div>
    <div class="row">
        <div class="col s12 m12 l12" style="margin-top: 5px;">
            <?php displayPagination($setLimit,$page,$query);  ?>
        </div>
    </div>                       
 </div>     
 
 <div id="add_new" style="display: none;overflow-x: hidden; width: 99.99%; height: 99.99%; z-index: 1000; position: fixed; top: 0; left: 0; background: rgba(0,0,0,0.7);">
   	 <div class="row"><br><br>
       	<div class="col s12 m1 l2"> </div>
           <div class="col s12 m10 l8 white"> 
             <h5><?=$LANG['Open New Ticket']?> <span class="right"><a href="#" class="red-text" onclick="$('#add_new').hide('slow');"><i class="fa fa-times"></i></a></span></h5>
             <form action="" method="post" id="add_tick"  onSubmit="return false;">
             <div class="card ">
                 <div class="card-content">
                 	<div class="row no-m-t no-m-b">
                    	<div class="input-field col s12">
                            <select id="customer" required class="js-states browser-default"  style="width: 100%">
                                <option value="0" disabled selected><?=$LANG['Select Customer']?></option>
                                <?php $query="SELECT * FROM users WHERE reseller = '$userID'";
                                $result = mysqli_query($server,$query) or die(mysqli_error($server));
                                while ($rws = mysqli_fetch_assoc($result)) { 
                                    echo '<option value="'.$rws['id'].'">'.$rws['first_name'].' '.$rws['last_name'].'</option>';
                                }
                               ?> 
                            </select>
                            <label class="active"><?=$LANG['Customer']?></label>
                        </div>
                     </div>   
                     <div class="row no-m-t no-m-b">
                         <div class="input-field col s12">
                               <input id="subject" autofocus type="text" class="validate" required value="">
                               <label for="subject"><?=$LANG['Subject']?></label>
                         </div>
                       </div>
                     <div class="row no-m-t no-m-b">
                        <div class="input-field col s12">
                             <textarea id="message"></textarea>
                        </div>			
					</div>
                    <div class="row no-m-t no-m-b">       
                        <div class="file-field input-field col m6 s12">
                            <div class="btn light-blue darken-4">
                                <span><i class="fa fa-paperclip"></i></span>
                                <input id="files" type="file" name="files">
                            </div>
                            <div class="file-path-wrapper">
                               <input class="file-path validate" type="text" placeholder="<?=$LANG['Attach File']?>">
                               <input type="hidden" id="files_holder">
                            </div>
                        </div> 
                    </div>	
                   <div class="card-action">
                        <input type="hidden" id="ticket" value="0">
                    	<a class="btn waves-effect waves-light red" href="rticket"><?=$LANG['Cancel']?></a>
                    	<button id="send-button" class="btn green" type="submit"><?=$LANG['Send']?> </button>
                    	<span id="send-spin" class="btn-flat" style="display: none;"><i class="fa fa-spinner fa-spin"></i> <strong><?=$LANG['Please wait']?>...</strong></span>
                        <span id="upload-spin" class="btn-flat" style="display: none;"><i class="fa fa-spinner fa-spin"></i> <strong><?=$LANG['Uploading your files']?> <span id="progress-wrp">0%</span>...</strong></span>
                	</div>   
                 </div>
             </div>
             </form>
           </div>
       <div class="col s12 m2 l2"> </div>
	 </div>
 </div>                
  
<?php } else {
	$did = mysqli_real_escape_string($server,$_GET['ti']);
	$query="SELECT t.* FROM tickets t JOIN users u ON t.customer_id = u.id WHERE t.id = '$did' AND u.reseller = '$userID'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	if($row['id'] > 0) {
		$id = $row['id'];	
		if($row['parent_id']>0) {
			$query="SELECT * FROM tickets WHERE id = '$row[parent_id]'"; 
			$result = mysqli_query($server,$query) or die(mysqli_error($server));  
			$row = mysqli_fetch_assoc($result); 
			$id = $row['id'];	
		}
	} else {
		header('location: rticket');	
	}	
?>	
 <div class="row no-m-t no-m-b">
     <div class="col s12 m12 l12">
         <div class="card card-white">
            <div class="card-content">
           		<span class="card-title"><h5>#<?=$id.' - '.$row['subject']?></h5> </span>					
           		<span class="card-title"><i class="fa fa-pencil"></i> <?=$LANG['Add a Reply']?> <a class="btn waves-effect waves-light blue right" href="rticket"><?=$LANG['Back to Tickets']?></a> <a class="btn waves-effect waves-light red right" href="aticket?close=<?=$row['id']?>"><?=$LANG['Close Ticket']?></a></span>		
                <form action="" method="post" id="add_tick"  onSubmit="return false;">
					<div class="row no-m-t no-m-b">
                        <div class="input-field col s12">
                             <textarea id="message"></textarea>
                        </div>			
                    </div> 
                    <div class="row no-m-t no-m-b">       
                        <div class="file-field input-field col m6 s12">
                            <div class="btn light-blue darken-4">
                                <span><i class="fa fa-paperclip"></i></span>
                                <input id="files" type="file" name="files">
                            </div>
                            <div class="file-path-wrapper">
                               <input class="file-path validate" type="text" placeholder="<?=$LANG['Attach File']?>">
                               <input type="hidden" id="files_holder">
                            </div>
                        </div> 
                    </div>
                   <div class="card-action">
                   		<input type="hidden" id="subject" value="<?=$row['subject']?>">
                        <input type="hidden" id="customer" value="<?=$row['customer_id']?>">
                        <input type="hidden" id="ticket" value="<?=$row['id']?>">
                    	<a class="btn waves-effect waves-light red" href="rticket"><i class="fa fa-times"></i> <?=$LANG['Cancel']?></a>
                    	<button id="send-button" class="btn green" type="submit"><i class="fa fa-send"></i> <?=$LANG['Send Reply']?> </button>
                    	<span id="send-spin" class="btn-flat" style="display: none;"><i class="fa fa-spinner fa-spin"></i> <strong><?=$LANG['Please wait']?>...</strong></span>
                        <span id="upload-spin" class="btn-flat" style="display: none;"><i class="fa fa-spinner fa-spin"></i> <strong><?=$LANG['Uploading your files']?> <span id="progress-wrp">0%</span>...</strong></span>
                	</div>   
                    </form>
				</div>                
                
                <div class="row no-m-t no-m-b">
                    <div class="col s12 m12 l12">
                	    <div class="mailbox-list">
                            <ul>
<?php
	$query="SELECT * FROM tickets WHERE parent_id = ".$row['id']." order by date DESC";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));
	 while ($rows = mysqli_fetch_assoc($result)) { 
		 $class="lime lighten-5"; $from = 'Support'; $syn = '<i class="material-icons circle green">supervisor_account</i>';
		if($rows['customer_reply']>0)  { $class='yellow lighten-5'; $from = userData($rows['customer_id'],'first_name').' '.userData($rows['customer_id'],'last_name'); $syn = '<i class="material-icons circle orange ">person_pin</i>';}
		if(!empty($rows['media'])) {
		$mails = "<p>---</p><p><b>".$LANG['Attached File']."</b>: <a target='_blank' href='".home_base_url().'files/temp/'.$row['media']."'>".home_base_url().'files/temp/'.$row['media']."</a></p>";
		}
?>                                
                                <li class="collection-item avatar <?=$class?>">
                                     	 <?=$syn?>
                                          <span class="title"><?=$from?></span>
                                          <div style="margin-top:10px;padding:10px;border-top:1px solid #eee"><?=removeHTML($rows['message']).$mails?></div>
                                          <div class="position-top-right p f-12 mail-date" style="font-size: 14px;"><?=date('M j, Y h:ia',strtotime($rows['date']))?></div>
                                 </li>
<?php
	}
$class="lime lighten-5"; $from = 'Support'; $syn = '<i class="material-icons circle green">supervisor_account</i>';
if($row['customer_reply']>0)  { $class='yellow lighten-5'; $from = userData($row['customer_id'],'first_name').' '.userData($row['customer_id'],'last_name'); $syn = '<i class="material-icons circle orange">person_pin</i>';}
if(!empty($row['media'])) {
	$mails = "<p>---</p><p><b>".$LANG['Attached File']."</b>: <a target='_blank' href='".home_base_url().'files/temp/'.$row['media']."'>".home_base_url().'files/temp/'.$row['media']."</a></p>";
}
?>                                 
                                   <li class="collection-item avatar <?=$class?>">
                                     	 <?=$syn?>
                                          <span class="title"><?=$from?></span>
                                          <div style="margin-top:10px;padding:10px;border-top:1px solid #eee"><?=removeHTML($row['message']).$mails?></div>
                                          <div class="position-top-right p f-12 mail-date" style="font-size: 14px;"><?=date('M j, Y h:ia',strtotime($row['date']))?></div>
                                 </li>
                                 
                             </ul>
                    </div>    
                </div>    

         </div>
     </div>
 </div>           
<?php } ?>	