<?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" => "");
$pageurl = strtr($pageurl,$trans);
$pageurl = str_replace('&&','&',$pageurl);
//====End ==============
define('TITLE','Inbox');
if(!isAdmin(getUser()) && (userData(getUser(),'phone') == '' || userData(getUser(),'first_name') == '') ) {
	header('location: profile?setting'); exit();
}
if(!isAdmin(getUser()) && userData($userID,'email_verified') != 0) {
	showVerify();
}
$today = date('Y-m-d'); $time = strtotime($today.'-1 months'); $lastMonth = date("Y-m", $time); $time = strtotime($today.'-1 years'); $lastYear = date("Y", $time);
?>
<?php
if(isset($_POST['bulk'])) { 
	foreach($_POST['bulk'] as $inbid) { 
		mysqli_query($server,"DELETE FROM `inbox` WHERE `id` = '$inbid' AND customer_id = '$userID'") or die(mysqli_error($server));
		logEvent($userID,'Deleted inbox message with ID '.$inbid);
	}	
	$_SESSION['message'] = $LANG['The selected message(s) has been deleted from your inbox'];
	header('location: inbox?err=0');
}

	$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[] = "message LIKE '%$term%' OR sender = '%$term%'  OR recipient = '%$term%'";
			} else {
				 $clauses[] = " id LIKE '%%' ";
			}
		}
		$added .= ' AND ('.implode(' OR ', $clauses).') ';		
	}
	if(isset($_GET['s'])) {
		switch($_GET['s']) {
			case 'd_o': $added .= " order by date ASC ";
			break;
			case 'd_n': $added .= " order by date DESC ";
			break;
			case 's_r': $added .= " order by is_read DESC ";
			break;
			case 's_u': $added .= " order by is_read ASC ";
			break;
		}
	} else {
		$added .= " order by id DESC ";	
	}

    $query="SELECT * FROM inbox WHERE customer_id = '$userID' $added limit $pageLimit,$setLimit";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));
	$x = mysqli_num_rows($result);
	if($x < 1 && !isset($_GET['sc']) && !isset($_GET['s'])) { ?>
<!-- Quick Navs ::::: You can customize this -->
 <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['inbox_tip']?></div>
        </div>
    </div>
 </div>
<?php } else { ?>
<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">
                </div>
                <div class="col s12 m8 l8">
                  <div class="col s12 m12 l12">
                    <div class="row no-m-t no-m-b">
                     <form action="inbox" 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">
       <div class="col s12 m12 l12">
         <div class="card card-white">
            <div class="card-content">
            <div class="card-title">
            	<ul>
                	<li><a class='dropdown-button btn btn-flat' href='#' data-activates='filter' data-beloworigin='true' data-constrainwidth='false'><?=$LANG['Sort']?></a></li>
                </ul>    
                <ul id='bulka' class='dropdown-content'>
                        <li><a href="#" onclick="bulkaction('delete','inbox-form','<?=$LANG['delete_confirm']?>');"> <i class="fa fa-trash"></i> <?=$LANG['Delete']?></a></li>
                        <li><a href="#"> <i class="fa fa-check"></i> <?=$LANG['Mark as Seen']?></a></li>
                </ul>
                <ul id='filter' class='dropdown-content'>
                    <li><a href="<?=$pageurl?>s=d_o" ><?=$LANG['Oldest First']?></a></li>
                    <li><a href="<?=$pageurl?>s=d_n" ><?=$LANG['Newest First']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_r" ><?=$LANG['Read First']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_u" ><?=$LANG['Unread First']?></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="from"><?=$LANG['From']?></th>
                        <th data-field="to"><?=$LANG['To']?></th>
                        <th data-field="message"><?=$LANG['Message']?></th>
                        <th data-field="date"><?=$LANG['Date']?></th>
                        <th data-field="act"></th>
                    </tr>
                 </thead>
            <?php } ?>     
                 <tbody>
                    <form action="inbox" method="post" id="inbox-form">
                    	<input type="hidden" id="bulkaction" name="action" value=""/>                    
<?php $xf=0;while ($rows = mysqli_fetch_assoc($result)) { $xf+=1; if($rows['is_read']<1) $class="amber lighten-5";?>
						<tr class="<?=@$class?>">
                             <td><input type="checkbox" class="filled-in bulk" value="<?=$rows['id']?>" id="bulk<?=$rows['id']?>" name="bulk[<?=$rows['id']?>]"/> <label for="bulk<?=$rows['id']?>"></label></td>
                             <td><?=$rows['sender']?></td>
                             <td><?=$rows['recipient']?></td>
                             <td><?=$rows['message']?></td>
                             <td><?=timeElapsed($rows['date'])?></td>
                             <td><a href="compose?t=sms&inbid=<?=$rows['id']?>"><i class="fa fa-reply"></i> <?=$LANG['Reply']?></a></td>
                        </tr>
       <?php mysqli_query($server,"UPDATE `inbox` SET is_read = 1 WHERE `id` = '$rows[id]'") or die(mysqli_error($server)); ?>
<?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>
  </div>
 <div class="row">
 	<div class="col s12 m12 l12" style="margin-top: 5px;">
        <?php displayPagination($setLimit,$page,$query);  ?>
    </div>
 </div>                       
<?php } ?>   