<?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','Draft');

if(userRole()>2) {
	header('location: index.php');	
}
hasModulePermission('view draft');	
$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) { 
		$inbid = mysqli_real_escape_string($server,$inbid);
		mysqli_query($server,"DELETE FROM `draftmessages` WHERE `id` = '$inbid'") or die(mysqli_error($server));
		logEvent($userID,'Deleted draft message with ID '.$inbid);
	}	
	$_SESSION['message'] = $LANG['The selected message(s) has been deleted from your draft'];
	header('location: adraft?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[] = "sender_id LIKE '%$term%' OR message = '%$term%'  OR date = '%$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 sender_id DESC ";
			break;
			case 's_u': $added .= " order by sender_id ASC ";
			break;
		}
	} else {
		$added .= " order by id DESC ";	
	}

    $query="SELECT * FROM draftmessages WHERE 1 $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['draft_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="adraft" 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" style="float: right">
                <a class='dropdown-button btn btn-flat' href='#' data-activates='filter' data-beloworigin='true' data-constrainwidth='false'><?=$LANG['Sort']?></a>
                <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>
                </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['Sender ID Z-A']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_u" ><?=$LANG['Sender ID A-Z']?></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="to"><?=$LANG['Type']?></th>
                        <th data-field="from"><?=$LANG['Sender ID']?></th>
                        <th data-field="to"><?=$LANG['Recipients']?></th>
                        <th data-field="message"><?=$LANG['Message']?></th>
                        <th data-field="date"><?=$LANG['Customer']?></th>
                        <th data-field="act"></th>
                    </tr>
                 </thead>
                 <?php } ?>
                 <tbody>
                    <form action="adraft" method="post" id="inbox-form">
                    	<input type="hidden" id="bulkaction" name="action" value=""/>                    
<?php $xf=0; while ($rows = mysqli_fetch_assoc($result)) { $xf+=1; 
$customer = '<a href="acustomer?v='.$rows['customer_id'].'">'.userData($rows['customer_id'],'first_name').' '.userData($rows['customer_id'],'last_name').'</a>';
if($rows['customer_id']==0) $customer = 'Administrator';
?>
						<tr 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><?=strtoupper($rows['type'])?></td>
                             <td><?=$rows['sender_id']?></td>
                             <td><?=countRecipient($rows['recipients'])?></td>
                             <td><?=$rows['message']?></td>
                             <td><?=$customer?></td>
                             <td><a href="acompose?t=<?=$rows['type']?>&draftid=<?=$rows['id']?>"><i class="fa fa-envelope"></i> <?=$LANG['Send']?></a></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>
  </div>
 <div class="row">
 	<div class="col s12 m12 l12" style="margin-top: 5px;">
        <?php displayPagination($setLimit,$page,$query);  ?>
    </div>
 </div>                       
<?php } ?>   