<?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','History');
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');	
}
$billingModel = checkBillingModel($userID);
if($billingModel == 'unit') { }
$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') {
	foreach($_POST['bulk'] as $inbid) { 
		$inbid = mysqli_real_escape_string($server,$inbid);
		mysqli_query($server,"DELETE FROM `sentmessages` WHERE `id` = '$inbid' AND customer_id = '$userID'") or die(mysqli_error($server));
		mysqli_query($server,"DELETE FROM `messagedetails` WHERE `message_id` = '$inbid' AND status != 'sent'") or die(mysqli_error($server));
		logEvent($userID,'Deleted message with ID '.$inbid.' from history');
	}	
	$_SESSION['message'] = $LANG['The selected message(s) has been deleted from your message history'];
	header('location: rsent?err=0');
  } else if($_POST['action']=='cancel') {
	foreach($_POST['bulk'] as $inbid) { 
		$inbid = mysqli_real_escape_string($server,$inbid);
		mysqli_query($server,"UPDATE `sentmessages` SET status = 'canceled' WHERE `id` = '$inbid' AND customer_id = '$userID' AND status != 'completed'") or die(mysqli_error($server));
		mysqli_query($server,"UPDATE `messagedetails` SET status = 'canceled' WHERE `message_id` = '$inbid' AND status != 'sent'") or die(mysqli_error($server));
		logEvent($userID,'Canceled message with ID '.$inbid.' from queued messages');
	}	
	$_SESSION['message'] = $LANG['The selected message(s) has been canceled and will no longer be processed'];
	header('location: rsent?err=0');
  } else {
	  header('location: rsent');
  }
}
if(isset($_REQUEST['view'])&&$_REQUEST['view']>0) {
	$did = mysqli_real_escape_string($server,$_REQUEST['view']);
	
	if(isset($_GET['export'])) {
	exportToCSV('Recipients_','messagedetails','id,datetime,type,recipient,operator,status,cost'," WHERE message_id = '".$did."'");
	exit;
	}		
	$query="SELECT * FROM sentmessages WHERE id = '$did'"; 
	$result = mysqli_query($server,$query) or die(mysqli_error($server));  
	$row = mysqli_fetch_assoc($result); 
	if($row['id'] > 0) {
		$id = $row['id'];	
		$owner = $row['customer_id'];
		$reseller = userData($owner,'reseller');
		$row2['type'] = $row['type'];
		if($row['type']=='sms') $row2['type'] = 'text';
		if($reseller != $userID) {
			header('location: rsent');		
		}
		$recip = $row['recipients'];
	} else {
		header('location: rsent');	
	}
?>
<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="btn waves-effect waves-light light-blue darken-5" href="rsent"><?=$LANG['Back to History']?></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="rsent?view=<?=$id?>" 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 Recipients...']?>">
                     </div>
                     </form>  
                    </div>
                  </div> 
                </div>
            </div>
        </div>
    </div>
 </div>

 <div class="row no-m-t no-m-b">
     <div class="col s12 m6 l5">
         <div class="card card-white">
            <div class="card-content">
           		<span class="card-title"><?=$LANG['Message Overview']?></span>
					<div style="position:absolute;left:15px;top:50px;width:40%;background:rgba(255,255,255,0.6);">
                        <h6 class="blue-text"><i class="fa fa-square"></i> Pending</h6>
                        <h6 class="green-text"><i class="fa fa-square"></i> Sent</h6>
                        <h6 class="red-text"><i class="fa fa-square"></i> Failed</h6>
                        <h6 class="grey-text"><i class="fa fa-square"></i> Canceled</h6>
                    </div>
                    <canvas id="chart4" width="400" height="200"></canvas>
            </div>
            <div class="card-content">
				<ul class="collection">
                    <li class="collection-item"><h6><b><?=$LANG['Message ID']?></b></h6><p><?=$row['id']?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Customer']?></b></h6><p><?=userData($row['customer_id'],'first_name').' '.userData($row['customer_id'],'last_name')?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Status']?></b></h6><p><?=ucfirst($row['status'])?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Type']?></b></h6><p><?=strtoupper($row2['type'])?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Sent On']?></b></h6><p><?=date('j M, Y h:iA',strtotime($row['date']))?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Sent From']?></b></h6><p><?=strtoupper($row['sent_from'])?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['IP Address']?></b></h6><p><a target="_blank" href="http://www.geoiptool.com/en/?IP=<?=$row['ip']?>"><?=$row['ip']?></a></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Sender ID']?></b></h6><p><?=$row['sender_id']?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Message']?></b></h6><p><?=$row['message']?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Characters']?></b></h6><p><?=countCharacters($row['message'])?> <?=$LANG['character(s)']?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Pages']?></b></h6><p><?=countPage($row['message'],$row['type'],$row['duration'])?> <?=$LANG['pages']?></p></li>
                    <li class="collection-item"><h6><b><?=$LANG['Total Recipients']?></b></h6><p><?=number_format($row['to_count'])?> <?=$LANG['Recipient(s)']?></p></li>
<?php
	$cosuL = round(messageCost($row['id'])/userExchangeRate($row['customer_id']),userCurrencyZero($userID));
	$cosrU = $cosuL*userExchangeRate($userID);
?>                    
                    <li class="collection-item"><h6><b><?=$LANG['Cost']?></b></h6><p><?=$billingModel=='unit'?'':userCurrencySymbol($userID)?><?=number_format($cosrU,4)?></p></li>
                    <?php if($row['type']=='voice') { ?>
                    <li class="collection-item"><h6><b><?=$LANG['Voice File']?></b></h6><p><?php if(!empty($row['media'])) { echo $row['media']; } else { echo 'None'; } ?>?></p></li>
                    <?php } ?>
                    <?php if($row['type']=='voice') { ?>
                    <li class="collection-item"><h6><b><?=$LANG['Duration']?></b></h6><p><?=$row['duration']?> <?=$LANG['seconds']?></p></li>
                    <?php } ?>
                    <?php if($row['type']=='mms' || $row['type']=='whatsapp') { ?>
                    <li class="collection-item"><h6><b><?=$LANG['Media File']?></b></h6><p><?php if(!empty($row['media'])) { echo $row['media']; } else { echo 'None'; } ?></p></li>
                    <?php } ?>
                </ul>
            </div>
         </div>
     </div>

<?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[] = "recipient LIKE '%$term%' OR id = '$term' OR status = '$term' ";
			} else {
				 $clauses[] = " id LIKE '%%' ";
			}
		}
		$added .= ' AND ('.implode(' OR ', $clauses).') ';		
	}
	if(isset($_GET['s'])) {

	} else {
		$added .= " order by id DESC ";	
	}

    $query="SELECT * FROM messagedetails WHERE message_id = '$id' $added limit $pageLimit,$setLimit";
	$result = mysqli_query($server,$query) or die(mysqli_error($server));
	$x = mysqli_num_rows($result);
?>     
     <div class="col s12 m6 l7">
         <div class="card card-white">
            <div class="card-content">
             	<span class="card-title"><?=$LANG['Recipients']?></span>
               <div class="col s12 m12 l12">

           		</div>         
            </div>    
            <div class="card-content">
            	<div class="card-options">
                      <a class='waves-effect waves-light btn green white-text' href='rsent?export&view=<?=$id?>'>Export</a>
                </div>
                <table class="highlight responsive-table">
                <?php if($x>0) { ?>
                <thead>
                	<tr>
                        <th data-field="to"><?=$LANG['To']?></th>
                        <th data-field="message"><?=$LANG['Destination']?></th>
                        <th data-field="message"><?=$LANG['Operator']?></th>
                        <th data-field="cost"><?=$LANG['Cost']?></th>
                        <th data-field="status"><?=$LANG['Status']?></th>
                        <th data-field="act"></th>
                    </tr>
                 </thead>
                 <?php } ?>
                 <tbody>
                    <form action="rsent?view=<?=$id?>" method="post" id="inbox-form">
                    	<input type="hidden" id="bulkaction" name="action" value=""/>
<?php $xf=0; while ($rows = mysqli_fetch_assoc($result)) { $xf+=1;
$stats = ''; 
$status_1 = ucfirst($rows['status']);
if($rows['notice'] != '') {
	$stats = '<a class="hoverable tooltipped failed_reason" data-position="left" data-delay="50" data-tooltip="'.str_replace('"','',$rows['notice']).'"><i class="fa fa-exclamation-triangle red-text"></i></a>';	
} 

if(	strtolower($rows['status'])=='sent' && strtolower($rows['dlr'])!='sent') {
	$status_1 = ucfirst($rows['dlr']);
}

$to = $rows['recipient'];
if( ($rows['marketinglist_id']>0) && (marketinglistData($rows['marketinglist_id'],'customer_id') != $userID) ) {
	$to = substr($rows['recipient'],0,-5) . '*****';
}
	$cosuL = round($rows['cost']/userExchangeRate($rows['customer_id']),userCurrencyZero($userID));
	$cosrU = $cosuL*userExchangeRate($userID);
?>
						<tr class="">
                             <td><?=$to?></td>
                             <td><?=countryName($rows['country_id'])?></td>
                             <td><?=$rows['operator']?></td>
                             <td><?=number_format($cosrU,userCurrencyZero($userID))?></td>
                             <td><?=$status_1?> <?=@$stats?></td>
                             <td>
                             <a class="hoverable" href="compose?smid=<?=$rows['id']?>"><?=$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 class="row">
        <div class="col s12 m12 l12" style="margin-top: 5px;">
            <?php displayPagination($setLimit,$page,$query);  ?>
        </div>
    </div>                       
 </div>           
<?php	
} else {
	if(isset($_GET['export'])) {
		$from_date = mysqli_real_escape_string($server,$_GET['from_date']);
		$to_date = mysqli_real_escape_string($server,$_GET['to_date']);
		$from_date = date("Y-m-d H:i:s",strtotime($from_date));
		$to_date = date("Y-m-d H:i:s",strtotime($to_date));
		exportToCSV('Sent_messages_','m.sentmessages','m.id,m.customer_id,m.date,m.type,m.sender_id,m.message,m.to_count,m.status',"  m JOIN users u ON m.customer_id = u.id WHERE m.date >= '$from_date' AND m.date <= '$to_date' AND u.reseller = '".getUser()."'");
		exit;
	}
	//show list
	$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[] = "m.sender_id LIKE '%$term%' OR m.message = '%$term%'  OR m.date LIKE '%$term%'  OR m.status LIKE '%$term%' ";
			} else {
				 $clauses[] = " m.id LIKE '%%' ";
			}
		}
		$added .= ' AND ('.implode(' OR ', $clauses).') ';		
	}
	if(isset($_GET['s'])) {
		switch($_GET['s']) {
			case 'd_o': $added .= " order by m.date ASC ";
			break;
			case 'd_n': $added .= " order by m.date DESC ";
			break;
			case 's_r': $added .= " order by m.sender_id DESC ";
			break;
			case 's_u': $added .= " order by m.sender_id ASC ";
			break;
			case 's_q': $added .= " and m.status = 'queued' order by m.id DESC ";
			break;
			case 's_c': $added .= " and m.status = 'completed' order by m.id DESC ";
			break;
			case 's_f': $added .= " and m.status = 'canceled' order by m.id DESC ";
			break;
			case 's_p': $added .= " and m.status = 'processing' order by m.id DESC ";
			break;
		}
	} else {
		$added .= " order by m.id DESC ";	
	}

    $query="SELECT m.* FROM sentmessages m JOIN users u ON m.customer_id = u.id WHERE u.reseller = '$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['rjob_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="rsent" 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['Queued Only']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_p" ><?=$LANG['Processing Only']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_c" ><?=$LANG['Completed Only']?></a></li>
                    <li><a href="<?=$pageurl?>s=s_f" ><?=$LANG['Canceled Only']?></a></li>
                </ul>
            </div>
            <span class="card-title"><a class='waves-effect waves-light btn green white-text'  href='#'  onclick="$('#add_new').show();">Export</a> 
<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="id"><?=$LANG['ID']?></th>
                        <th data-field="type"><?=$LANG['Customer']?></th>
                        <th data-field="date"><?=$LANG['Sent On']?></th>
                        <th data-field="message"><?=$LANG['Message']?></th>
                        <th data-field="to"><?=$LANG['Recipients']?></th>
                        <th data-field="cost"><?=$LANG['Cost']?></th>
                        <th data-field="status"><?=$LANG['Status']?></th>
                        <th data-field="act"></th>
                    </tr>
                 </thead>
             <?php } ?>    
                 <tbody>
                    <form action="rsent" method="post" id="inbox-form">
                    	<input type="hidden" id="bulkaction" name="action" value=""/>
<?php $xf=0; while ($rows = mysqli_fetch_assoc($result)) { $xf+=1; $stats = ''; 
//sum recipients
	$recip = $rows['recipients'];
	$pages = countPage($rows['message'],$rows['type'],$rows['duration']);
	if($rows['status'] == 'completed') $stats='<a class="tooltipped" data-position="left" data-delay="50" data-tooltip="'.sentMessageProgress($rows['id']).' '.$LANG['messages sent'].'"><span class="pie">'.sentMessageProgress($rows['id']).'</span></a>';
	if($rows['status'] == 'canceled') $stats='<a class="tooltipped" data-position="left" data-delay="50" data-tooltip="'.sentMessageProgress($rows['id']).' '.$LANG['messages sent'].'"><span class="pie">'.sentMessageProgress($rows['id']).'</span></a>';
	if($rows['status'] == 'processing') $stats='<a class="tooltipped" data-position="left" data-delay="50" data-tooltip="'.messageProgress($rows['id']).' '.$LANG['messages processed'].'"><span class="pie">'.messageProgress($rows['id']).'</span></a>';
	$cosuL = round(messageCost($rows['id'])/userExchangeRate($rows['customer_id']),userCurrencyZero($userID));
	$cosrU = $cosuL*userExchangeRate($userID);
?>
						<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><?=$rows['id']?></td>
                             <td><?=userData($rows['customer_id'],'first_name').' '.userData($rows['customer_id'],'last_name')?></td>
                             <td><?=timeElapsed($rows['date'])?></td>
                             <td><?=shorten($rows['message'],50)?></td>
                             <td><?=number_format($rows['to_count'])?></td>
                             <td><?=$billingModel=='unit'?'':userCurrencySymbol($userID)?><?=number_format($cosrU,userCurrencyZero($userID))?></td>
                             <td><?=ucfirst($rows['status'])?> <?=@$stats?></td>
                             <td><a class="hoverable" href="rsent?view=<?=$rows['id']?>"><i class="fa fa-info-circle"></i> <?=$LANG['Details']?></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 } ?> 
<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>Export SMS Log<span class="right"><a href="#" class="red-text" onclick="$('#add_phonebook')[0].reset();$('#add_new').hide('slow');"><i class="fa fa-times"></i></a></span></h5>
               <div class="card ">
                 <div class="card-content">
                    <form action="rsent" method="get" id="add_phonebook">
                        <div class="row no-m-t no-m-b">
                    	 <div class="input-field col s12">
                           <input name="from_date" type="date" class="validate" required value="<?=date("Y-m-d",time()-86400)?>" >
                           <label for="from_date" class="active">From Date</label>
                    	 </div>
                        </div>
                        <div class="row no-m-t no-m-b">
                    	 <div class="input-field col s12">
                           <input name="to_date" type="date" class="validate" required value="<?=date("Y-m-d",time())?>" >
                           <label for="to_date" class="active">To Date</label>
                    	 </div>
                        </div>
                       <div class="card-action">
                            <button id="cont-button" class="btn ight-blue darken-4" name="export" type="submit"><i class="fa fa-save"></i> Export</button>
                            <a class="btn waves-effect waves-light red" href="#" onclick="$('#add_phonebook')[0].reset();$('#add_new').hide('slow');"><i class="fa fa-times"></i> <?=$LANG['Cancel']?></a>
                       </div>
             		</form>
                 </div>
             </div>
           </div>
	 </div>
 </div>                      
<?php } ?>  