<?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_s" => "", "s=s_q" => "");
$pageurl = strtr($pageurl,$trans);
$pageurl = str_replace('&&','&',$pageurl);
//====End ==============
define('TITLE','Scheduled');
if(userRole()>2) {
	header('location: index.php');	
}
hasModulePermission('view scheduled');
$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'])) { 
	$userID = getUser();
  if($_POST['action']=='delete') {
	  hasModulePermission('delete scheduled');
	foreach($_POST['bulk'] as $inbid) { 
		mysqli_query($server,"DELETE FROM `scheduledmessages` WHERE `id` = '$inbid'") or die(mysqli_error($server));
		logEvent($userID,'Deleted scheduled message with ID '.$inbid);
	}	
	$_SESSION['message'] = $LANG['The selected message(s) has been deleted from your scheduled messages'];
	header('location: ascheduled?err=0');
  } else if($_POST['action']=='cancel') {
	foreach($_POST['bulk'] as $inbid) { 
		mysqli_query($server,"UPDATE `scheduledmessages` SET status = 'canceled' WHERE `id` = '$inbid' AND status != 'processed'") or die(mysqli_error($server));
		logEvent($userID,'Canceled scheduled message with ID '.$inbid);
	}	
	$_SESSION['message'] = $LANG['The selected message(s) has been canceled and will no longer be processed'];
	header('location: ascheduled?err=0');
  } else {
	  header('location: ascheduled');
  }
}

	$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 schedule_date ASC ";
			break;
			case 'd_n': $added .= " order by schedule_date DESC ";
			break;
			case 's_r': $added .= " order by sender_id DESC ";
			break;
			case 's_u': $added .= " order by sender_id ASC ";
			break;
			case 's_q': $added .= " and status = 'queued' order by id DESC ";
			break;
			case 's_s': $added .= " and status = 'processed' order by id DESC ";
			break;
		}
	} else {
		$added .= " order by id DESC ";	
	}

    $query="SELECT * FROM scheduledmessages 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['scheduled_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="ascheduled" 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>
                        <li><a href="#" onclick="bulkaction('cancel','inbox-form','<?=$LANG['cancel_confirm']?>');"> <i class="fa fa-times"></i> <?=$LANG['Cancel']?></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>
                    <li><a href="<?=$pageurl?>s=s_q" ><?=$LANG['Pending Only']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_s" ><?=$LANG['Processed Only']?></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="cust"><?=$LANG['Customer']?></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="crea"><?=$LANG['Created']?></th>
                        <th data-field="sch"><?=$LANG['Scheduled For']?></th>
                        <th data-field="date"><?=$LANG['Status']?></th>
                        <th data-field="act"></th>
                    </tr>
                 </thead>
               <?php } ?>  
                 <tbody>
                    <form action="ascheduled" 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';
$repeated = '';
if(strlen($rows['repeats'])>1) $repeated = '<br><small class="red-text">('.$LANG['Repeated'].' '.$LANG[ucwords($rows['repeats'])].')</small>';
//sum recipients
$recip = $rows['recipients'];
	foreach (explode( ",",$rows['phonebook_id']) as $list){
		$recip .= ','.getContacts($list,'phonebook');	
	}
	foreach (explode( ",",$rows['marketinglist_id']) as $list){
		$recip .= ','.getContacts($list,'marketing');	
	}
	if(!empty($rows['files'])) {
		$recip .= ','.getFileContacts($files);
	}
?>
						<tr 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><?=strtoupper($rows['type'])?></td>
                             <td><?=$customer?></td>
                             <td><?=$rows['sender_id']?></td>
                             <td><?=countRecipient($recip)?></td>
                             <td><?=$rows['message']?></td>
                             <td><?=timeElapsed($rows['date'])?></td>
                             <td><?=date('j M Y h:iA',strtotime($rows['schedule_date'])).$repeated?></td>
                             <td><?=ucfirst($rows['status'])?></td>
                             <td><a href="acompose?t=<?=$rows['type']?>&schedid=<?=$rows['id']?>"><i class="fa fa-envelope"></i> <?=$LANG['Resend']?></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 } ?>   