<?php
include "config/init.php";
include "system/hubtel/hubtel_func.php";
include "template/header.php";
//Main Header
include "template/main-header.php";
//Left side column. contains the logo and sidebar -->
include "template/main-sidebar.php";

if(isset($_POST['creditCustomer'])){
    $transaction_uid = trim(html_filter($dbc,$_POST['transaction_uid']));
    $hubtel_tnx = trim(html_filter($dbc,$_POST['hubtel_tnx']));
	$selaction = trim(html_filter($dbc,$_POST['selaction']));

    $transactionType = "PUSH";

    if(!empty($transaction_uid) || !empty($hubtel_tnx)){
		
		if($selaction=="CANCELLED"){
		
        if(check_transaction_by_transaction_uid_momo_tnx($dbc,$transaction_uid,$hubtel_tnx)) {
            $all_transaction = get_main_transaction_by_transaction_uid_momo_tnx($dbc,$transaction_uid,$hubtel_tnx);
			//var_dump($all_transaction);
			//exit();
            $fee = $all_transaction['fee'] * 1; // Fee for cash out
            $mm_amount = $all_transaction['sendersAmount'] * 1;
            $totalAmount = $fee + $mm_amount;
            $customerData = get_customer_by_id($dbc,$all_transaction['senderID']);
			//print_r($customerData);
			//exit();
            $global_hubtel_Acc = get_customer_by_phoneNum($dbc, "+233770000000");
            if (redraw_funds($dbc,$global_hubtel_Acc['id'],$totalAmount,$global_hubtel_Acc['countryCode'])) {
                if (add_funds($dbc, $customerData['id'], $totalAmount,$customerData['countryCode'])) {
                    $cusAcc = get_cus_account_info_by_customerID($dbc,$all_transaction['senderID'],$customerData['countryCode']);
					
					if($customerData['accountType']=="2" or $customerData['accountType']=="4"){
						//reverse_agent_commission($dbc,$all_transaction,$fee,$customerData['countryCode']);
						
						redraw_agent_commission_by_uid($dbc,$transaction_uid,$all_transaction['senderID']);
               			redraw_payGlobal_commission_by_uid($dbc,$transaction_uid);
					}
					
					
					
                    if (update_hubtel_transaction_after_success_refund($dbc, $transaction_uid,$cusAcc['balance'],'CANCELLED')) {
                        $q = mysqli_query($dbc,"INSERT INTO hubtel_resolver_tbl (id, transaction_uid, transactionType, hubtel_txn, customerID, phoneNumber, amount,user)
                        VALUES (UUID(),'$transaction_uid','PUSH','$all_transaction[foreignId]','$customerData[id]','$customerData[phoneNum]','$totalAmount','$_SESSION[uid]')
                        ");
						$q1 = mysqli_query($dbc,"UPDATE maintransaction_tbl SET transactionStatus='CANCELLED' WHERE transaction_uid = '$transaction_uid'");
						
						if($q1){
						
                        if($q){
                            $result = "<p class='alert alert-success'>You have refunded {$totalAmount} to a customer by the name {$customerData['fullName']}({$customerData['companyName']}) with phone number {$customerData['phoneNum']}</p>";
                            //$message = "Your wallet has been refund with an amount of {$totalAmount} from GN Money/PayGlobal. transaction ID: {$transaction_uid} ";
                            //sendSMS($customerData['phoneNum'],$message);
                        } else{
                            $result = "<p class='alert alert-danger'>System Error..</p>";

                        }
						
						}else{
                            $result = "<p class='alert alert-danger'>System Error..</p>";

                        }

                    } else{
                        $result = "<p class='alert alert-danger'>System Error occur..</p>";

                    }
                }else{
                    $result = "<p class='alert alert-danger'>Can't Add funds to customer</p>";
                }
            }else{
                $result = "<p class='alert alert-danger'>No funds in Transit Account</p>";

            }
        } else{
            $result = "<p class='alert alert-danger'>Transaction ID does not exist or transaction already cancelled</p>";
        }
		
		
		
		} else{
		
		//////$result = "<p class='alert alert-danger'>Complete Action</p>";//////////////////////////////
			
			
		if(check_transaction_by_transaction_uid_momo_tnx1($dbc,$transaction_uid,$hubtel_tnx)) {
            $all_transaction = get_main_transaction_by_transaction_uid_momo_tnx($dbc,$transaction_uid,$hubtel_tnx);
			
			
			
			$q1 = mysqli_query($dbc,"UPDATE maintransaction_tbl SET transactionStatus='COMPLETED' WHERE transaction_uid = '$transaction_uid'");
						
						if($q1){
							$result = "<p class='alert alert-success'> Transaction successfully completed</p>";
                          
                        } else{
                            $result = "<p class='alert alert-danger'>System Error..</p>";

                        }
			
			
			/**
			//var_dump($all_transaction);
			//exit();
            $fee = $all_transaction['fee'] * 1;
			$comm = $fee * 0.5;// Fee for cash out
            $mm_amount = $all_transaction['sendersAmount'] * 1;
            $totalAmount = $fee + $mm_amount;
            $customerData = get_customer_by_id($dbc,$all_transaction['senderID']);
			//print_r($customerData);
			//exit();
            $global_hubtel_Acc = get_customer_by_phoneNum($dbc, "+233770000000");
            if (add_funds($dbc,$global_hubtel_Acc['id'],$totalAmount,$global_hubtel_Acc['countryCode'])) {
                if (redraw_funds($dbc, $customerData['id'], $totalAmount,$customerData['countryCode'])) {
                    $cusAcc = get_cus_account_info_by_customerID($dbc,$all_transaction['senderID'],$customerData['countryCode']);
					
					if($customerData['accountType']=="2" or $customerData['accountType']=="4"){
						//reverse_agent_commission($dbc,$all_transaction,$fee,$customerData['countryCode']);
						
						add_agent_commission($dbc,$all_transaction,$comm,$customerData['countryCode']);
						add_payGlobal_commission($dbc,$all_transaction,$comm);
               			//redraw_payGlobal_commission_by_uid($dbc,$transaction_uid);
					}
					
					
					
                    if (update_hubtel_transaction_after_success_refund($dbc, $transaction_uid,$cusAcc['balance'],'COMPLETED')) {
                        $q = mysqli_query($dbc,"INSERT INTO hubtel_resolver_tbl (id, transaction_uid, transactionType, hubtel_txn, customerID, phoneNumber, amount,user)
                        VALUES (UUID(),'$transaction_uid','PUSH','$all_transaction[foreignId]','$customerData[id]','$customerData[phoneNum]','$totalAmount','$_SESSION[uid]')
                        ");
						$q1 = mysqli_query($dbc,"UPDATE maintransaction_tbl SET transactionStatus='COMPLETED' WHERE transaction_uid = '$transaction_uid'");
						
						if($q1){
						
                        if($q){
                            $result = "<p class='alert alert-success'>You have debited customer by the name {$customerData['fullName']}({$customerData['companyName']}) with phone number {$customerData['phoneNum']} an amount of {$totalAmount}</p>";
                            //$message = "Your wallet has been refund with an amount of {$totalAmount} from GN Money/PayGlobal. transaction ID: {$transaction_uid} ";
                            //sendSMS($customerData['phoneNum'],$message);
                        } else{
                            $result = "<p class='alert alert-danger'>System Error..</p>";

                        }
						
						}else{
                            $result = "<p class='alert alert-danger'>System Error..</p>";

                        }

                    } else{
                        $result = "<p class='alert alert-danger'>System Error occur..</p>";

                    }
                }else{
                    $result = "<p class='alert alert-danger'>Can't Add funds to customer</p>";
                }
            }else{
                $result = "<p class='alert alert-danger'>No funds in Transit Account</p>";

            }
			
			*****/
			
        } else{
            $result = "<p class='alert alert-danger'>Transaction ID does not exist</p>";
        }
			
			
        }
		
		
    } else{
        $result = "<p class='alert alert-danger'>All fields required</p>";
    }

}

?>

<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>
            MoMo Push Cancellation
        </h1>
    </section>

    <!-- Main content -->
    <section class="content">
        <?php
            if(isset($result)){echo $result;}
        ?>
        <div class="row">
            <div class="col-md-4">
                <div class="box box-default">
                    <div class="box-header with-border">Cancel MoMo Push</div>
                    <div class="box-body">
                        <form method="post" role="form" onsubmit="return confirm('Are you sure you want to do this transaction');">

                            <div class="form-group">
                                <label for="transaction_uid">Transaction ID</label>
                                <input type="text" name="transaction_uid" id="transaction_uid" required class="form-control">
                            </div>
                            <div class="form-group">
                                <label for="hubtel_tnx">Hubtel TXN</label>
                                <input type="text" name="hubtel_tnx" id="hubtel_tnx" value='XXXXXXXXXX' required class="form-control">
                            </div>
							
							<div class="form-group">
							<select class="form-control" name="selaction" required id="selaction">
                                    <option value="">Select Action</option>                                  
                                    <option value='CANCELLED'>CANCEL</option>
									<option value='COMPLETED'>COMPLETE</option>
                                    
                                </select>
							</div>
                            <button class="btn btn-primary" name="creditCustomer" type="submit" id="creditCustomer">Process Transaction</button>

                        </form>
                    </div>
                </div>
            </div>
            <div class="col-md-8">
                <div class="box box-success">
                    <div class="box-header with-border">List of Cancelled MoMo Push transactions</div>
                    <div class="box-body">
                        <table class="table table-striped" id="">
                            <thead>
                            <tr>
                                <th>Date</th>
                                <th>customer</th>
                                <th>Amount</th>
                                <th>Transaction Type</th>
                                <th>Phone Number</th>
                                <th>Transaction ID</th>
                                <th>Hubtel TXN</th>
                                <th>User</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
                            $ListResolves = get_all_hubtel_resolved($dbc);
                            foreach($ListResolves as $value){
                                $customerData2 = get_customer_by_id($dbc,$value['customerID']);
                                $userData = get_user_by_id($dbc,$value['user']);
                                ?>
                                <tr>
                                    <td><?=$value['dateTime'] ?></td>
                                    <td><?=$customerData2['fullName']." ".$customerData2['companyName'] ?></td>
                                    <td><?=$value['amount'] ?></td>
                                    <td><?=$value['transactionType'] ?></td>
                                    <td><?=$value['phoneNumber'] ?></td>
                                    <td><?=$value['transaction_uid'] ?></td>
                                    <td><?=$value['hubtel_txn'] ?></td>
                                    <td><?=$userData['fullName'] ?></td>
                                </tr>
                                <?php
                            }
                            ?>
                            </tbody>
                        </table>
                    </div>
                </div>



            </div>
        </div>
    </section>
    <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<?php include "template/footer.php"?>


