<?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','Transactions');
if(userRole()>2 && (getRole() != 10 || getRole() != 11)) {
	header('location: index.php');	
}
hasModulePermission('view transaction');
$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['view'])) {
	if(userRole()<3) {
		$reference = mysqli_real_escape_string($server,$_GET['view']);
		$_SESSION['reference']= $reference;
		header('location: atransaction?inv=1');	
		exit;
	}
}
if(isset($_GET['appr'])) {
	hasModulePermission('approve transaction');
	$reference = mysqli_real_escape_string($server,$_GET['appr']);
	$owner = transactionData($reference,'customer_id');
	$reseller = userData($owner,'reseller');
	if($reseller == 0) {
		processTransaction($reference);
		$_SESSION['message'] = $LANG['The selected transaction has been successfully processed'];
		header('location: atransaction?err=0');
	}
}
if(isset($_GET['canc'])) {
	hasModulePermission('approve transaction');
	$reference = mysqli_real_escape_string($server,$_GET['canc']);
	$owner = transactionData($reference,'customer_id');
	$reseller = userData($owner,'reseller');
	if($reseller == 0) {
		mysqli_query($server,"UPDATE `transactions` SET `status` =  'canceled' WHERE `transaction_reference` = '$reference'");
		$_SESSION['message'] = $LANG['The selected transaction has been canceled'];
		header('location: atransaction?err=0');
	}
}

if(!isset($_GET['inv'])) {
?>
<?php
	if(isset($_REQUEST['exportc'])) { 
		exportToCSV('TransactionLog_','transactions','t.customer_id,t.date,t.description,t.credits,t.cost,t.status,t.transaction_reference'," t JOIN users u ON t.customer_id = u.id WHERE u.reseller = '0'");
		exit;
	}		
?>
<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['atranact_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">
                </div>
                <div class="col s12 m8 l8">
                  <div class="col s12 m12 l12">
                    <div class="row no-m-t no-m-b">
                     <form action="atransaction" 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['customer_id']) && $_GET['customer_id']>0) {
		$req_customer_id = mysqli_real_escape_string($server,$_GET['customer_id']);
		$added .= " AND t.customer_id = '$req_customer_id' ";
	}
	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.description LIKE '%$term%' OR t.id = '%$term%' OR t.credits LIKE '%$term%' OR t.transaction_reference LIKE '%$term%' OR t.status LIKE '%$term%'";
			} else {
				 $clauses[] = " t.id LIKE '%%' ";
			}
		}
		$added .= ' AND ('.implode(' OR ', $clauses).') ';		
	}
	if(isset($_GET['s'])) {

	} else {
		$added .= " order by t.id DESC ";	
	}
    $query="SELECT t.* FROM transactions t JOIN users u ON t.customer_id = u.id WHERE u.reseller = '0' $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-title">
                      <a class='waves-effect waves-light btn green white-text' href='atransaction?exportc=1'>Export</a>
                </div>
                
                <table class="highlight responsive-table">
                
                <?php if($x>0) { ?>
                <thead>
                	<tr>
                        <th data-field="date"><?=$LANG['Date']?></th>
                        <th data-field="to"><?=$LANG['Customer']?></th>
                        <th data-field="credit"><?=$LANG['Credits']?></th>
                        <th data-field="cost"><?=$LANG['Cost']?></th>
                        <th data-field="ref"><?=$LANG['Reference']?></th>
                        <th data-field="status"><?=$LANG['Status']?></th>
                        <th></th>
                    </tr>
                 </thead>
                 <?php } ?>
                 <tbody>
<?php $xf=0; while ($rows = mysqli_fetch_assoc($result)) { $xf+=1;
$link = '';
if( ($rows['is_earned'] < 1) && ($rows['is_shared'] < 1) && ($rows['credits'] > 0) ) {
$link = '<a class="hoverable" href="atransaction?view='.$rows['transaction_reference'].'"><i class="fa fa-search"></i> '.$LANG['Invoice'].'</a>';	
if(strtolower($rows['status']) != 'completed')
$link .= ' <a onclick="return confirm(\''.$LANG['order_confirm_lan'].'\');" class="green-text hoverable" href="atransaction?appr='.$rows['transaction_reference'].'"><i class="fa fa-check"></i> '.$LANG['Approve'].'</a>';	

if(strtolower($rows['status']) != 'completed' && strtolower($rows['status']) != 'canceled' && strtolower($rows['status']) != 'failed')
$link .= ' <a class="red-text hoverable" href="atransaction?canc='.$rows['transaction_reference'].'"><i class="fa fa-times"></i> '.$LANG['Cancel'].'</a>';	
}
$vars = array( "reference"=>$rows['transaction_reference']	 );
$_SESSION['EventVals'] = $vars;
?>
						<tr class="">
                             <td><?=date('M j, Y',strtotime($rows['date']))?></td>
                             <td class=""><a href="acustomer?v=<?=$rows['customer_id']?>"><?=userData($rows['customer_id'],'first_name').' '.userData($rows['customer_id'],'last_name')?></a></td>
                             <td><?=number_format($rows['credits'],userCurrencyZero($userID))?></td>
                             <td><?=userCurrencySymbol($rows['customer_id']).number_format($rows['cost'],userCurrencyZero($userID))?></td>
                             <td><?=$rows['transaction_reference']?></td>
                             <td><?=ucfirst($rows['status'])?></td>
                             <td><?php if(userRole()<3) {?><?=$link?><?php } ?>
                             <?php global $hooks; $hooks->do_action('TransactionTableAction'); ?>
                             </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($_SESSION['reference'])) { header('location: transaction');	} 
//get trans data
if(transactionData($_SESSION['reference'],'customer_id')<1) { header('location: transaction');	} 
$total = transactionData($_SESSION['reference'],'cost');
$customerID = transactionData($_SESSION['reference'],'customer_id');
?>
<div id="printable">
	<?php if(strtolower(transactionData($_SESSION['reference'],'status'))=='completed') { $status = $LANG['Paid']?>
		<div class="green darken-4">
    <?php } elseif(strtolower(transactionData($_SESSION['reference'],'status'))=='canceled') { $status = $LANG['Canceled'] ?>
    	<div class="grey darken-1">
     <?php } else { $status = $LANG['Unpaid'] ?>
    	<div class="red darken-4">
    <?php } ?>    
                    <div class="container">
                        <div class="row no-m-b">
                            <div class="col s12 m12 l12">
                                <div class="card card-transparent no-m">
                                    <div class="card-content  white-text">
                                        <div class="row">
                                            <div class="col s12 m6 l6">
                                                <h4><?=getSetting('businessName')?></h4>
                                                <address>
                                                    <?=getSetting('companyAddress')?><br>
                                                    <i class="fa fa-phone"></i>: <?=getSetting('companyPhone')?>
                                                </address>
                                            </div>
                                            <div class="col s12 m6 l6 right-align">
                                                <h4><?=$status?></h4>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="container">
                    <div class="row">
                        <div class="col s12 m12 l12">
                            <div class="card card-white no-m">
                                <div class="card-content invoice-relative-content">
                                    <div class="row">
                                        <div class="col s12 12 l12 center-align">
                                            <h4>
                                                <?=$LANG['Invoice']?> #<?=$_SESSION['reference']?></b><br>
                                            </h4>
                                        </div>
                                    </div>
                                    <div class="row">
                                    	<div class="col s12 m6 l4">
                                            <p>
                                                <span class="light-blue-text"><?=$LANG['Customer']?></span><br>
                                                <b><?=userData(transactionData($_SESSION['reference'],'customer_id'),'first_name').' '.userData(transactionData($_SESSION['reference'],'customer_id'),'last_name')?></b><br>
                                                <b><?=userData(transactionData($_SESSION['reference'],'customer_id'),'phone')?></b><br>
                                            </p>
                                        </div> 
                                        <div class="col s12 m6 l3">
                                            <p>
                                                <span class="light-blue-text"><?=$LANG['Invoice Date']?></span><br>
                                                <b><?=date('M j, Y',strtotime(transactionData($_SESSION['reference'],'date')))?></b><br>
                                            </p>
                                        </div> 
                                        <div class="col s12 m6 l3">
                                            <p>
                                            <?php if($status=='Paid') {?>
                                               <span class="light-blue-text"><?=$LANG['Paid On']?></span><br>
                                                <b><?=date('M j, Y',strtotime(transactionData($_SESSION['reference'],'paid_on')))?></b><br>
                                            <?php } else {?>
                                            	<span class="light-blue-text"><?=$LANG['Due Date']?></span><br>
                                                <b><?=date('M j, Y',strtotime(transactionData($_SESSION['reference'],'date')))?></b><br>
                                            <?php }?>    

                                            </p>
                                        </div>
                                        <div class="col s12 m6 l6 right-align">
    	                                        <a onclick="Print('printable');" class="btn-floating btn-large waves-effect waves-light indigo darken-4 invoice-edit-btn"><i class="material-icons">print</i></a>
	                                    </div>
                                    </div>
                                    <div class="row">
                                        <div class="col s12 m12 l12">
                                            <table class="table responsive-table">
                                                <thead>
                                                    <tr>
                                                        <th>S/N</th>
                                                        <th><?=$LANG['Description']?></th>
                                                        <th class="right-align"><?=$LANG['Quantity']?></th>
                                                        <th class="right-align"><?=$LANG['Cost']?></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                    	<th>1</th>
                                                        <td><?=transactionData($_SESSION['reference'],'description')?></td>
                                                        <td class="right-align"><?=number_format(transactionData($_SESSION['reference'],'credits'),userCurrencyZero($customerID))?></td>
                                 						<td class="right-align"><?=userCurrencySymbol($customerID)?><?=number_format(transactionData($_SESSION['reference'],'cost'),userCurrencyZero($customerID))?></td>                       
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col s12 m6 l7">
                                            <span class="heading-title"><?=$LANG['Thank you']?> !</span>
                                         <?php if($status == 'Unpaid') { ?>   
                                            <?=paymentGatewayData(transactionData($_SESSION['reference'],'method'),'text')?>
                                          <?php } ?>  
                                       <?php if(!empty(getSetting('invoiceSignature'))) { ?>     
                                            <img src="files/<?=getSetting('invoiceSignature')?>" class="invoice-signature m-t-md" alt="">
                                       <?php } ?>
                                       		<br>
                                       		<a id="cancel_inv" href="atransaction" class="waves-effect waves-light btn dark-blue darken-2"><?=$LANG['Back to Transactions']?></a>     

                                        </div>
                                        <div class="col s12 m6 l5 right-align">
                                            <div class="text-right">
                                                <h6 class="m-t-sm light-blue-text"><b><?=$LANG['Subtotal']?></b></h6>
                                                <h5 class=""><?=userCurrencySymbol($customerID)?><?=number_format(transactionData($_SESSION['reference'],'cost'),userCurrencyZero($customerID))?></h5>
                                                <div class="divider"></div>
                                        <?php if(gatewayCharge(getUser(),transactionData($_SESSION['reference'],'method'),transactionData($_SESSION['reference'],'cost')) > 0) { 
											$total += gatewayCharge(getUser(),transactionData($_SESSION['reference'],'method'),transactionData($_SESSION['reference'],'cost'))
										?>
                                                <h6 class="m-t-sm light-blue-text"><b><?=$LANG['Gateway Charges']?></b></h6>
                                                <h5 class=""><?=userCurrencySymbol($customerID)?><?=number_format(gatewayCharge(getUser(),transactionData($_SESSION['reference'],'method'),transactionData($_SESSION['reference'],'cost')),userCurrencyZero($customerID))?></h5>
                                                <div class="divider"></div>
                                        <?php } ?>
                                                
                                        <?php if(getUserVat(getUser(),transactionData($_SESSION['reference'],'cost')) >0) { 
											$total += getUserVat(getUser(),transactionData($_SESSION['reference'],'cost'));
										?>
                                                <h6 class="m-t-sm light-blue-text"><b><?=$LANG['VAT']?> (<?=getSetting('vatAmount')?>%)</b></h6>
                                                <h5 class=""><?=userCurrencySymbol($customerID)?><?=number_format(getUserVat(getUser(),transactionData($_SESSION['reference'],'cost')),userCurrencyZero($customerID))?></h5>
                                                <div class="divider"></div>
                                        <?php } ?>
                                                
                                        <?php if(getUserTax(getUser(),transactionData($_SESSION['reference'],'cost')) >0) { 
											$total += getUserTax(getUser(),transactionData($_SESSION['reference'],'cost'));
										?>
                                                <h6 class="m-t-sm light-blue-text"><b><?=$LANG['TAX']?> (<?=getSetting('taxAmount')?>%)</b></h6>
                                                <h5 class=""><?=userCurrencySymbol($customerID)?><?=number_format(getUserTax(getUser(),transactionData($_SESSION['reference'],'cost')),userCurrencyZero($customerID))?></h5>
                                                <div class="divider"></div>
                                        <?php } ?>
                                                <h6 class="m-t-md text-success light-blue-text"><b><?=$LANG['Total']?></b></h6>
                                                <h4 class="text-success"><?=userCurrencySymbol($customerID)?><?=number_format($total,userCurrencyZero($customerID))?></h4>
                                                <div class="divider"></div>
                                                <h6 class="m-t-md text-success light-blue-text"><b><?=$LANG['Payment Method']?></b></h6>
                                                <h5 class="text-success"><?=paymentMethod(transactionData($_SESSION['reference'],'method'))?></h5>
                                                <br>
                                              
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
</div>                
<?php } ?>	