<?php

$_POST = help::sanitize($_POST);

$status = false;


## [ Get Loan ] ##

if( $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])) {
	$query = $link->query( sQuery::select( 'loan', "id='{$_POST['id']}'" ) );
	$loan = $query->fetch_assoc();
} else $loan = null;


## [ Delete Loan ] ##

if(isset($_POST['delete']) && $loan) {

	$sql = "DELETE FROM loan WHERE id='{$loan['id']}'";
	
	$status = mysqli_query($link, $sql);

	$msg = $status ? "deleted successfully!" : "Cannnot delete! ";
	
}

    


 if(isset($_POST['approve']) && $loan) {
    
	$__user = help::get_user( $loan['email'] );
	
	if( (int)$_POST['approve'] ) {
		
		// --------------------
		
		
		$FUND_SQL = sQuery::update( 'tbl_users', array(
			"balance" => (float)$__user['balance'] + (float)$loan['amount']
		), "email = '{$__user['email']}'" );
		
		
		// ---------------------
		
		
		$APPROVAL_SQL = sQuery::update( 'loan', array(
			"status" => 1
		), "id = '{$loan['id']}'" );
		
		
		// ----------------------
		
		
		$history = array(
			"tx_no" => help::keygen(8, false),
			"tx_type" => 'credit',
			"amount" => $loan['amount'],
			"date" => date("Y/m/d"),
			"description" => "loan payment",
			"to_accno" => '',
			"account" => $loan['account'],
			"status" => 'success',
			"comments" => 'loan payment'
		);
		
		$HISTORY_SQL = sQuery::insert( 'tbl_transaction', $history);
		

		## -----------------------
		

		$user_funded = $status = $link->query( $FUND_SQL );
		
		if( $user_funded ) {
			
			$mark_approved = $link->query( $APPROVAL_SQL );
			$append_history = $link->query( $HISTORY_SQL );
			
			$msg = "Loan Approval Successful! <br> User account funded";
			
			require __DIR__ . '/for-loan-email.php';
		
		} else $msg = "Loan Approval Failed!";
	
	
	}; // else ($_POST['approve'] == false)
 
 }

