<?php 

require_once("pages.php");

function _pm_default_success_method($args, $item){
	return true;
}

function _pm_default_error_method($args, $item){
	return true;
}

function _pm_discount_success_method($args, $item){
	$query = new query;
	$res =	$query->update(
					"discount", 
					["status" => "redeemed"],
					["id" => $item['feeid']]
				);
	return true;
}

function _pm_discount_error_method($args, $item){
	return true;
}

function _pm_default_invoice_success_method($args){
	$invoice = new pm_invoice($args['user_id']);
	$invoice->set_invoice_by_number($args['in_ref']);
	return $invoice->process_success($args);
}

function _pm_default_invoice_error_method($args){
	$invoice = new pm_invoice($args['user_id']);
	$invoice->set_invoice_by_number($args['in_ref']);
	return $invoice->process_error($args);
}

function success_method(){
	return true;
}

function error_method(){
	return true;
}

function _pm_wallet_topup_success($args, $item) {
	$invoice = new pm_invoice($args['user_id']);
	$invoice->set_invoice_by_number($args['in_ref']);
	pm_credit_wallet($invoice->user_id, $invoice->total(), $item['narration'], "top_up_".$args['in_ref'], 'confirmed');
	$post = new post;
	$feeid = str_replace("e-wallet-top-up-", "", $item['feeid']);
	$post->update_post_meta($feeid, ['status' => 'paid']);
	return true;
}

function _pm_wallet_topup_error($args, $item) {
	return true;
}

function payment_method_list_template($args) {
	?>
	<div class="each">
		<form id="gateway-<?php echo $args['gateway_id']; ?>" method="post" action="<?php echo $args['gateway_page'] ?>">
			<input type="hidden" name="<?php echo SALT; ?>" value="<?php echo $args[SALT] ?>">
			<input type="hidden" name="amount" value="<?php echo $args['amount']; ?>">
			<input type="hidden" name="in_ref" value="<?php echo $args['in_ref']; ?>">
			<input type="hidden" name="user_id" value="<?php echo $args['user_id']; ?>">
	    </form>
	    <a href="javascript:void(0);" class="submit-payment" data-gateway="<?php echo $args['gateway_id']; ?>" title="Pay through <?php echo $args['gateway_name'] ?>">
	    <img class="img-72" src="<?php echo $args['gateway_icon'] ?>" alt="<?php echo $args['gateway_name'] ?>">
	    <div class="pl-3">
	    	<div class="users-list-name"><?php echo ucwords($args['gateway_name']) ?></div>
	    	<span class="users-list-date"><?php echo $args['gateway_description'] ?></span>
	    </div>
	    </a>
    </div>
	<?php
}

function past_payment($user_id = '', $db_session_id = "all") {
	$post = new post;
	$res = [];
	$args = ['type' => 'credit', 'status' => 'confirmed', 'apply_db_session' => 1];
	if($user_id !== '') {
		$args['user_id'] = $user_id;
	}
	if($db_session_id !== "all") {
		$args['db_session_id'] = $db_session_id;
	}
	$res = $post->get_post_by_meta_data($args);
	return $res;
}

function create_balance_bf_snapshot($ledger_type, $inflow, $outflow, $balance, $_range_to, $lastId, $query = false) {
    if($balance === 0) {
        return;
    }
    $time_stop = $_range_to - 0.01;
    $sql = "INSERT INTO balance_bf
            (ledger, outflow, inflow, balance, time_stop, last_post_id)
            VALUES('$ledger_type', '$outflow', '$inflow', '$balance', '$time_stop', '$lastId')";
    $query = ($query) ? $query : new query;
    $query->query($sql);
    return $query;
}

function get_balance_bf_snapshot($ledger, $_range_to, $query = false) {
    $sql = "SELECT * FROM balance_bf
            WHERE `ledger` LIKE '$ledger'
            AND `time_stop` < '$_range_to'
            ORDER BY `time_stop` DESC
            LIMIT 1";
    $query = ($query) ? $query : new query;
    $res = $query->get_results($sql);
    return (!_count($res)) ? false : array_shift($res);
}

function pm_get_balance_bf($_range_to, $ledger_type) {
	$query_type = "normalLedger";
	switch($ledger_type) {
		case "General Ledger":
			$query = ['type' => ['expense', 'income', 'payout', 'outflow', 'inflow', 'credit'], 'apply_db_session' => 1, 'status' => ['approved', 'confirmed'], '_range_to' => $_range_to];
			break;

		case "Cash Ledger":
			$query = ['type' => ['expense', 'income', 'payout', 'outflow', 'inflow', 'credit', 'bank_deposit', 'bank_withdrawal'], 'apply_db_session' => 1, 'status' => ['approved', 'confirmed'], '_range_to' => $_range_to];
			break;

		default:
			$query = ['type' => ['bank_deposit', 'bank_withdrawal'], 'apply_db_session' => 1, 'status' => 'approved', 'bank_id' => $args['args']['ledger_type'], '_range_to' => $_range_to];
			$ledger_type = "bankLedger-".$ledger_type;
			$query_type = "bankLedger";
			break;
	}
	$snap_shot = get_balance_bf_snapshot($ledger_type, $_range_to);
	if($snap_shot) {
		$query['_range_from'] = $snap_shot->time_stop;
		$outflow = $snap_shot->outflow;
		$inflow = $snap_shot->inflow;
		$balance = $snap_shot->balance;
		$lastIdSnapshot = $snap_shot->last_post_id;
	} else {
		$query['_range_from'] = 1;
		$outflow = $inflow = $balance = $lastIdSnapshot = 0;
	}
	$post = new post;
	$txns = $post->get_post_by_meta_data($query);
	$lastId = 0;
	if(_count($txns)) {
		foreach ($txns as $txn) {
			set_time_limit(60);
			if($txn['id'] == $lastIdSnapshot) continue;
			if($query_type === "normalLedger") {
				if ($txn["type"] == "credit" || $txn["type"] == "income" || $txn["type"] == "inflow" || $txn["type"] == "bank_withdrawal") {
					$balance += $txn['amount'];
					$inflow += $txn['amount'];
				} else {
					$balance -= $txn['amount'];
					$outflow += $txn['amount'];
				}
			} else {
				if ($txn["type"] == "bank_deposit") {
					$balance += $txn['amount'];
					$inflow += $txn['amount'];
				} else {
					$balance -= $txn['amount'];
					$outflow += $txn['amount'];
				}
			}
			$lastId = $txn['id'];
		}
		create_balance_bf_snapshot($ledger_type, $inflow, $outflow, $balance, $_range_to, $lastId);
	}
	return ['balance' => $balance, 'outflow' => $outflow, 'inflow' => $inflow];
}

function pm_credit_wallet($user_id, $amount, $narration, $ref, $status = 'confirmed') {
	if(db_post_unique(['type' => 'credit_user', 'user_id' => $user_id, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$credit = [
		'type' => 'credit_user',
		'user_id' => $user_id,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	$res = $post->add_post($credit);
	if($res) {
		$info = "Your wallet was credited with the sum of ".toMoney($amount).": ".$narration.". If payment did not reflect, know that it is waiting for approval.";
		inform_user($user_id, $info, "e-Wallet Credit Alert", get_option("home_url")."wallet-statement", SMS, EMAIL, NOTIFICATION);
	}
	return $res;
}

function pm_debit_wallet($user_id, $amount, $narration, $ref, $status = 'confirmed') {
	if(db_post_unique(['type' => 'debit_user', 'user_id' => $user_id, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$debit = [
		'type' => 'debit_user',
		'user_id' => $user_id,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	$res = $post->add_post($debit);
	if($res) {
		$info = "Your wallet was debited with the sum of ".toMoney($amount).": ".$narration.". If payment did not reflect, know that it is waiting for approval.";
		inform_user($user_id, $info, "e-Wallet Debit Alert", get_option("home_url")."wallet-statement", SMS, EMAIL, NOTIFICATION);
	}
	return $res;
}

// deprecating
// function pm_post_credit($amount, $narration, $user_id, $in_ref, $status = 'approved') {
// 	if(db_post_unique(['type' => 'expense', 'beneficiary' => $beneficiary, 'ref' => $ref])) {
// 		return false;
// 	}

// 	$post = new post;
// 	$expense = [
// 		'type' => 'expense',
// 		'beneficiary' => $beneficiary,
// 		'amount' => $amount,
// 		'narration' => $narration,
// 		'status' => $status,
// 		'ref' => $ref
// 	];
// 	return $post->add_post($expense);
// }

function pm_post_expense($amount, $narration, $beneficiary, $ref, $status = 'approved') {
	if(db_post_unique(['type' => 'expense', 'beneficiary' => $beneficiary, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$expense = [
		'type' => 'expense',
		'beneficiary' => $beneficiary,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	return $post->add_post($expense);
}

function pm_post_outflow($amount, $narration, $beneficiary, $ref, $status = 'approved') {
	if(db_post_unique(['type' => 'outflow', 'beneficiary' => $beneficiary, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$outflow = [
		'type' => 'outflow',
		'beneficiary' => $beneficiary,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	return $post->add_post($outflow);
}

function pm_post_income($amount, $narration, $benefactor, $ref, $status = 'approved') {
	if(db_post_unique(['type' => 'income', 'benefactor' => $benefactor, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$income = [
		'type' => 'income',
		'benefactor' => $benefactor,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	return $post->add_post($income);
}

function pm_request_payout($user_id, $amount, $ref, $account, $status = "pending") {
	
	if(db_post_unique(['type' => 'payout', 'user_id' => $user_id, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$payout = [
		'type' => 'payout',
		'user_id' => $user_id,
		'beneficiary' => $user_id,
		'account' => $account,
		'amount' => $amount,
		'status' => $status,
		'ref' => $ref
	];
	return $post->add_post($payout);
}

function pm_register_direct_credit($amount, $narration, $beneficiary, $ref, $status = 'approved') {
	if(db_post_unique(['type' => 'direct_credit', 'beneficiary' => $beneficiary, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$direct_credit = [
		'type' => 'direct_credit',
		'beneficiary' => $beneficiary,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	return $post->add_post($direct_credit);
}

function pm_register_direct_debit($amount, $narration, $user_id, $ref, $status = 'approved') {
	if(db_post_unique(['type' => 'direct_debit', 'user_id' => $user_id, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$direct_debit = [
		'type' => 'direct_debit',
		'user_id' => $user_id,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	return $post->add_post($direct_debit);
}

function pm_bank_deposit($amount, $narration, $bank_id, $ref, $status = 'approved') {
	if(db_post_unique(['type' => 'bank_deposit', 'bank_id' => $bank_id, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$bank_deposit = [
		'type' => 'bank_deposit',
		'bank_id' => $bank_id,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	return $post->add_post($bank_deposit);
}

function pm_bank_withdrawal($amount, $narration, $bank_id, $ref, $status = 'approved') {
	if(db_post_unique(['type' => 'bank_withdrawal', 'bank_id' => $bank_id, 'ref' => $ref])) {
		return false;
	}

	$post = new post;
	$bank_withdrawal = [
		'type' => 'bank_withdrawal',
		'bank_id' => $bank_id,
		'amount' => $amount,
		'narration' => $narration,
		'status' => $status,
		'ref' => $ref
	];
	return $post->add_post($bank_withdrawal);
}

function pm_get_user_wallet_bal($user_id) {
	$post = new post;
	$bal = 0;
	$payments_query = ['type' => ['credit_user', 'debit_user'], 'user_id' => $user_id, 'status' => 'confirmed'];
	$compare = "LIKE";
	$last_shot = false;
	if($snapshot = get_wallet_snapshot($user_id)) {
		$bal = $last_shot = $snapshot->balance;
		$payments_query['posted_on'] = $snapshot->date_created;
		$compare = ['posted_on' => ">"];
	}
	$payments = $post->get_post_by_meta_data($payments_query, $compare);
	if(_count($payments) && is_array($payments)) {
		foreach ($payments as $key => $payment) {
			if($payment['type'] === 'credit_user') {
				$bal += $payment['amount'];
			}
			if($payment['type'] === 'debit_user') {
				$bal -= $payment['amount'];
			}
		}
	}
	create_wallet_snapshot($user_id, $bal, $last_shot);
	return $bal;

}

function pm_generate_random_reference() {
	$ref = rand(1000, 9999).rand(1000, 9999).rand(1000, 9999).rand(1000, 9999);
	if(db_post_unique(['ref' => $ref])) {
		pm_generate_random_reference();
		exit();
	}
	return $ref;
}

function pm_new_invoice($user_id, $items, $due_date = false, $success_method = "_pm_default_success_method", $error_method = "_pm_default_error_method", $remove_duplicate = false) {
	$due_date = !$due_date ? time() : $due_date;
	$invoice = new pm_invoice($user_id);
	$invoice->due_date = $due_date;
	if(_count($items) && is_array($items)) {
		foreach ($items as $k => $v) {
			$quantity = isset($v['quantity']) ? $v['quantity'] : 1;
			$invoice->add_item($v['amount'], $v['narration'], $v['feeid'], $quantity, $v['ref'], $success_method, $error_method, $remove_duplicate);
		}
		$invoice->save();
	}
}

function item_in_another_invoice($ref) {
	$invoice = new pm_invoice();
	return $invoice->item_in_another_invoice($ref);
}

function create_wallet_snapshot($user_id, $balance, $last_shot = false, $query = false) {
    if($last_shot == $balance) {
        return;
    }
    $time = time();
    $sql = "INSERT INTO ewallet_snapshot
            (`user_id`, `balance`, `date_created`)
            VALUES('$user_id', '$balance', '$time')";
    $query = ($query) ? $query : new query;
    $query->query($sql);
    return $query;
}

function get_wallet_snapshot($user_id, $query = false) {
    $sql = "SELECT * FROM ewallet_snapshot
            WHERE `user_id` LIKE '$user_id'
            ORDER BY `date_created` DESC
            LIMIT 1";
    $query = ($query) ? $query : new query;
    $res = $query->get_results($sql);
    return ($res === null) ? false : array_shift($res);
}

function pm_get_total_inflow_interval($from, $to, $cache) {
	if($record = get_record("pm_total_inflow_".$from."_".$to)) {
		return $record;
	}
	$post = new post;
	$query = ['type' => ['income', 'credit', 'inflow'], 'status' => ['approved', 'confirmed'], '_range_from' => $from, '_range_to' => $to];
	$txn = $post->get_post_by_meta_data($query);
	$total = 0;
	if(_count($txn)) {
		foreach ($txn as $meta) {
			$total += $meta['amount'];
		}
	}
	if($cache) {
		update_record("pm_total_inflow_".$from."_".$to, $total);
	}
	return $total;
}

function pm_get_total_outflow_interval($from, $to, $cache) {
	if($record = get_record("pm_total_outflow_".$from."_".$to)) {
		return $record;
	}
	$post = new post;
	$query = ['type' => ['expense', 'outflow', 'payout'], 'status' => ['approved', 'confirmed'], '_range_from' => $from, '_range_to' => $to];
	$txn = $post->get_post_by_meta_data($query);
	$total = 0;
	if(_count($txn)) {
		foreach ($txn as $meta) {
			$total += $meta['amount'];
		}
	}
	if($cache) {
		update_record("pm_total_outflow_".$from."_".$to, $total);
	}
	return $total;
}

function get_inflow_outflow_chartdata() {
	$response = [];
	for ($i=0; $i < 12; $i++) { 
		if($i === 0) {
			$upper_limit = time();
			$date = strtotime('12AM first day of this month');
			$cache = false;
		} else {
			$upper_limit = $date;
			$date = strtotime("-1 month", $date);
			$cache = true;
		}
		$inflow = pm_get_total_inflow_interval($date, $upper_limit, $cache);
		$outflow = pm_get_total_outflow_interval($date, $upper_limit, $cache);
		$arr = [
			"date" => $date,
			"outflow" => $outflow,
			"inflow" => $inflow
		];
		array_push($response, $arr);
	}
	return $response;
}

function pm_update_ledger_wallets_balance($cron_id = false) {
	$records = new records;
	$post = new post;
	if($records->get_record("pm_updating_ledger_wallets", false)) {
		return;
	}
	$records->update_record("pm_updating_ledger_wallets", 1);
	$last_update = $records->get_record("pm_last_ledger_balance_check", false);
	$query_ledger = ['type' => ['expense', 'income', 'outflow', 'inflow', 'credit'], 'apply_db_session' => 1, 'status' => ['approved', 'confirmed']];
	$query_wallet = ['type' => ['credit_user', 'debit_user'], 'status' => 'confirmed'];
	if($last_update) {
		$query_ledger['_range_from'] = $query_wallet['_range_from'] = $last_update;
		$ledger = $records->get_record("pm_last_ledger_balance", false);
		$wallet = $records->get_record("pm_last_wallet_balance", false);
	} else {
		$ledger = $wallet = 0;
	}
	$time = time();
	// get ledger balance
	$txn = $post->get_post_by_meta_data($query_ledger);
	if(_count($txn)) {
		foreach ($txn as $meta) {
			set_time_limit(300);
			if ($meta["type"] == "credit" || $meta["type"] == "income" || $meta["type"] == "inflow") {
				$ledger += $meta['amount'];
			}
			if ($meta["type"] == "payout" || $meta["type"] == "outflow" || $meta["type"] == "expense") {
				$ledger -= $meta['amount'];
			}
		}
	}

	//get wallet balance
	$txn = $post->get_post_by_meta_data($query_wallet);
	if(_count($txn)) {
		foreach ($txn as $meta) {
			set_time_limit(300);
			if ($meta["type"] == "credit_user") {
				$wallet += $meta['amount'];
			}
			if ($meta["type"] == "debit_user") {
				$wallet -= $meta['amount'];
			}
		}
	}
	$records->update_record("pm_last_ledger_balance", $ledger);
	$records->update_record("pm_last_wallet_balance", $wallet);
	$records->update_record("pm_last_ledger_balance_check", $time);
	$records->update_record("pm_updating_ledger_wallets", 0);
	return ['ledger' => $ledger, 'wallet' => $wallet];
}

function get_ledger_balance_chartdata() {
	$records = new records;
	if(!$record = get_record("pm_last_ledger_balance_check")) {
		$cron = new cronjobs;
		$cron->schedule("*/5 * * * *", "pm_update_ledger_wallets_balance");
		$balances = pm_update_ledger_wallets_balance();
		if($balances) {
			$balances['system'] = $balances['ledger'] - $balances['wallet'];
		}
		return $balances;
	}
	$ledger = $records->get_record("pm_last_ledger_balance", false);
	$wallet = $records->get_record("pm_last_wallet_balance", false);
	$system = $ledger - $wallet;
	$system = ($system <= 0) ? 0 : $system;
	$ledger = toMoney($ledger);
	return ['ledger' => $ledger, 'wallet' => $wallet, 'system' => $system];
}

// $args @array [in_ref, amount]
function pm_process_add_payment($args, $invoice) {
	$session = Session::getInstance();
	$post = new post;
	$user = new user;
	$response = array();
	set_time_limit(200);
	ignore_user_abort(true);
	$valid = false;
	$default = [
		'type' => 'credit',
		'status' => 'confirmed',
		'confirmed_by' => get_fullname($session->id),
		'confirmed_on' => time(),
		'in_ref' => $invoice->invoice->invoice_number,
		'ref' => pm_generate_random_reference(),
		'user_id' => $invoice->user_id
	];
	$args = array_merge($default, $args);
	$args = apply_filters("pm_post_credit_args", $args);
	do_action("pm_post_credit_validation", $args);
	$invoice->total(true);
	$credits = $invoice->total_invoice_credit($args['in_ref'], ["confirmed", "submitted"]);
	$abs_credits = $invoice->total_invoice_credit($args['in_ref'], ["confirmed"]); //absolute credit
	$virtual_bal = $invoice->total - $credits;
	$abs_bal = $invoice->total - $abs_credits; //absolute bal
	if($virtual_bal <= 0) {
		$response['error'] = 1;
		$response['msg'] = 'This invoice has already been settled. If not cleared, look for unconfirmed payments linked to the invoice';
		return $response;
	}
	if(db_post_unique(['type' => 'credit', 'ref' => $args['ref'], 'user_id' => $args['user_id'], 'status' => ["confirmed", "submitted"]])) {
		$response['error'] = 1;
		$response['msg'] = 'This payment reference '.$args['ref'].' already exists';
		return $response;
	}
	if($args['amount'] > $virtual_bal) {
		$response['error'] = 1;
		$response['msg'] = 'Amount cannot be greater than '.toMoney($virtual_bal);
	} else {
		$credit_id = $post->add_post($args);
		$response['credit_id'] = $credit_id;
		$response['error'] = 0;
		$response['msg'] = 'You have successfully added the payment of '.toMoney($args['amount']).' to invoice number #'.$args['in_ref'].'.';
		$valid = true;
	}
	if($args['amount'] == $abs_bal && $valid) {
		if(function_exists($invoice->invoice->success_method)) {
			$success_method = $invoice->invoice->success_method;
			$res = $success_method($args);
			if($res) {
				if(isset($invoice->balance)) {
                    $invoice->balance -= $args['amount'];
                }
				$invoice->mail_receipt();
			} else {
				$post->drop_post($credit_id);
				$response['error'] = 1;
				$response['msg'] = 'Sorry, the system failed to give value to the payer, Please contact the software developer.';
				$valid = false;
			}
		} else {
			$post->drop_post($credit_id);
			$response['error'] = 1;
			$response['msg'] = 'Sorry, there is no function <strong>'.$invoice->invoice->success_method.'</strong> in place to give value to the payer, Please contact the software developer.';
			$valid = false;
		}
	}
	if($valid) {
		do_action("pm_payment_registration_success", $args);
		$home_url = get_option("home_url");
		$user_meta = $user->get_user_meta($args['user_id']);
		$support = new support;
		$support->action = $home_url."invoice?id=".$invoice->invoice->id;
		$support->template_name = "payment_confirmation";
		$support->add_placeholders([
			"amount" => toMoney($args['amount']),
			"payment_date" => date("d m, Y", time()),
			"mode_of_payment" => $args['mode'],
			"bank" => $args['mode'],
			"invoice_reference" => $invoice->invoice->invoice_number,
			"name_on_invoice" => $invoice->name
		]);
		$info = "Your payment ref #".$args['in_ref']." of ".toMoney($args['amount'])." was registered to the invoice by the admin.";
		$support->inform_user($user_meta, $info, "Payment Received", EMAIL, NOTIFICATION);
		$info = "The admin in this mention, manually registered a payment ref #".$args['in_ref']." of ".toMoney($args['amount'])." by ".get_fullname($user_meta).".";
		admin_log($info);
		$info = get_fullname($session->id)." just registered a payment ref #".$args['in_ref']." of ".toMoney($invoice->total(true))." by ".get_fullname($user_meta);
		inform_admins($info, "PAYMENT RECEIVED", $home_url."invoice?id=".$invoice->invoice->id, "super_admin", "admin", "admin_tech", "super_admin_tech");
	}
	return $response;
}

function pm_bank_accounts_option() {
	if($record = get_record("pm_bank_accounts_option")) {
		return $record;
	}
	$post = new post;
	$res = $post->get_post_by_meta_data(['type' => 'pm_bank_account', 'status' => 'active']);
	$option = [];
	if(_count($res)) {
		foreach ($res as $meta) {
			$accountID = pm_get_account_id($meta);
			$option[$accountID] = $meta['id'];
		}
	}
	update_record("pm_bank_accounts_option", $option);
	return $option;
}

function pm_get_account_id($meta) {
	if(!is_array($meta)) {
		$post = new post;
		$meta = $post->get_post_meta($meta);
	}
	return (trim($meta['account_id']) === "") ? $meta['account_number']." - ".$meta['bank_name'] : $meta['account_id'];
}

function pm_check_due_debt() {

}

function pm_accure_interest_on_debt() {
	
}