<?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['ti'])) {
?>
<?php
		
?>
<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(preg_replace('/[^a-z0-9]/i', '', $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 status LIKE '%open%' order by t.id DESC ";
			break;
			case 'd_n': $added .= " AND status LIKE '%answered%' order by t.id DESC ";
			break;
			case 's_r': $added .= " AND status LIKE '%customer-reply%' order by t.id DESC ";
			break;
			case 's_u': $added .= " AND 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">
                <table class="highlight responsive-table">
                <?php if($x>0) { ?>
                <thead>
                	<tr>
                        <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>
<?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') {
$class = 'amber lighten-4';	
}
?>
						<tr class="<?=$class?>">
                             <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 s1 m2 l3"> </div>
           <div class="col s10 m8 l6 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>
             <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="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>
                	</div>   
                 </div>
             </div>
           </div>
       <div class="col s1 m2 l3"> </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></span>		
                
                <div class="row no-m-t no-m-b">
                    <div class="input-field col s12">
                         <textarea id="message" autofocus></textarea>
                    </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>
                	</div>   
				</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>';}
?>                                
                                <li class="collection-item avatar <?=$class?>">
                                     	 <?=$syn?>
                                          <span class="title"><?=$from?></span>
                                          <p><?=removeHTML($rows['message'])?></p>
                                          <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>';}
?>                                 
                                   <li class="collection-item avatar <?=$class?>">
                                     	 <?=$syn?>
                                          <span class="title"><?=$from?></span>
                                          <p><?=removeHTML($row['message'])?></p>
                                          <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>
                                 
                             </ul>
                    </div>    
                </div>    
                              
            </div>
         </div>
     </div>
 </div>           
<?php } ?>	