<?php 

/**
 * Confirm payment is a function that runs when a payment is confirmed
 * On success, it checks if the success_method function set is existing
 * If not, it will reverse the confirmation on the grounds that value could not be given
 * Every invoice has success and error method
 * the success or error method has one parameter which is an array of args
 * args has the following handles which includes 
 * in_ref :: the invoice number
 * user_id :: the id of the payer
 * id :: reference to the credit post by id
 * trx :: [optional] which is serialized returned parameters from payment gateways
 * The invoice success_method by defualt runs success_methods for each items of the invoice
 * the items success or error methods have two parameters which is args and items
 * the args is an array of the parent success method args
 * items is the array of individual item being processed
 * the item param have the following handles
 * feeid, ref, amount, narration, ref, quantity, remark
 * @param  array $args [description]
 * @return array       [description]
 */
function pm_confirm_payment($args) {
	$post = new post;
	$session = Session::getInstance();
	$invoice = new pm_invoice($args['user_id']);
	$invoice->set_invoice_by_number($args['in_ref']);
	$payment_meta = $post->get_post_meta($args['id']);
	$sum_paid = $invoice->total(true);
	if($payment_meta['status'] === "rejected") {
		return ['status' => false, 'msg' => 'Sorry, this payment has already been rejected by '.get_fullname($payment_meta['rejected_by'])];
	}
	if($args['user_id'] == $session->id) {
		return ['status' => false, 'msg' => 'Sorry, you cannot confirm your own payment. Please ask another admin to perform the action.'];
	}
	$update = true;
	$update = $post->update_post_meta($args['id'], ["status" => "confirmed", "confirmed_by" => $session->id, 'confirmed_on' => time()]);
	$deposit = db_post_unique(['type' => 'bank_deposit', 'ref' => $args['id'] . ' : ' . $args['in_ref']]);
	if($update) {
		if(function_exists($invoice->invoice->success_method)) {
			$success_method = $invoice->invoice->success_method;
			$res = $success_method($args);
			if($res) {
				if($deposit) {
					$post->update_post_meta($deposit['id'], ['status' => 'approved', 'approved_by' => $session->id]);
				}
				if(isset($invoice->balance)) {
                    $invoice->balance -= $sum_paid;
                }
				$invoice->mail_receipt();
				$home_url = get_option("home_url");
				$user_meta = get_user_meta($args['user_id']);
				$info = "Your payment ref #".$args['in_ref']." of ".toMoney($sum_paid)." has been confirmed by the admin.";
				$support = new support;
    			$support->action = $home_url."invoice?id=".$invoice->invoice->id;
    			$support->template_name = "payment_confirmation";
    			$support->add_placeholders([
    				"amount" => toMoney($sum_paid),
    				"payment_date" => date("d m, Y", $payment_meta['posted_on']),
    				"mode_of_payment" => $payment_meta['mode'],
    				"bank" => $payment_meta['mode'],
    				"invoice_reference" => $invoice->invoice->invoice_number,
    				"name_on_invoice" => $invoice->name
    			]);
    			$support->inform_user($user_meta, $info, "Payment Received", EMAIL, NOTIFICATION);
				$info = "The admin in this mention, confirmed that he/she saw and verified the payment ref #".$args['in_ref']." of ".toMoney($sum_paid)." by ".get_fullname($user_meta)." on ".date(_DATE_FORMAT_,$invoice->invoice->date_created);
				admin_log($info);
				$info = get_fullname($session->id)." just confirmed a payment ref #".$args['in_ref']." of ".toMoney($sum_paid)." 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 ['status' => true, 'msg' => 'You have successfully confirmed this payment ref #'.$args['in_ref'].' and the payer has received value. Thank you.'];
			} else {
				$post->update_post_meta($args['id'], ["status" => "submitted"]);
				return ['status' => false, 'msg' => 'Sorry, the system failed to give value to the payer, Please contact the software developer.'];
			}
		} else {
			$post->update_post_meta($args['id'], ["status" => "submitted"]);
			return ['status' => false, '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.'];
		}
	} else {
		return ['status' => false, 'msg' => 'Sorry, unable to perform this action at the moment. Please try again later.'];
	}
}

function pm_reject_payment($args) {
	$post = new post;
	$session = Session::getInstance();
	$invoice = new pm_invoice($args['user_id']);
	$invoice->set_invoice_by_number($args['in_ref']);
	$payment_meta = $post->get_post_meta($args['id']);
	if($payment_meta['status'] === "confirmed") {
		return ['status' => false, 'msg' => 'Sorry, this payment has already been confirmed by '.get_fullname($payment_meta['confirmed_by'])];
	}
	if($args['user_id'] == $session->id) {
		return ['status' => false, 'msg' => 'Sorry, you cannot reject your own payment. Please ask another admin to perform the action.'];
	}
	$update = $post->update_post_meta($args['id'], ["status" => "rejected", "rejected_by" => $session->id, 'rejected_on' => time()]);
	if($update) {
		if(function_exists($invoice->invoice->error_method)) {
			$error_method = $invoice->invoice->error_method;
			$res = $error_method($args);
			if($res) {
				
				$home_url = get_option("home_url");
				$user_meta = get_user_meta($args['user_id']);
				$info = "Your payment ref #".$args['in_ref']." of ".toMoney($invoice->total(true))." was rejected by the admin. You are to re-upload your proof of payment or open a support ticket to dispute the decision";
				inform_user($user_meta, $info, "PAYMENT REJECTED", $home_url."support-ticket", EMAIL, SMS, NOTIFICATION);
				$info = "The admin in this mention, rejected the payment of ".toMoney($invoice->total(true))." by ".get_fullname($args['user_id'])." on ".date(_DATE_FORMAT_, $invoice->invoice->date_created);
				admin_log($info);
				$info = get_fullname($session->id)." rejected a payment ref #".$args['in_ref']." of ".toMoney($invoice->total(true))." by ".get_fullname($user_meta);
				inform_admins($info, "PAYMENT REJECTED", $home_url."invoice?id=".$invoice->invoice->id, "super_admin", "admin", "admin_tech", "super_admin_tech");
				return ['status' => true, 'msg' => 'You have successfully rejected this payment. Thank you.'];
			} else {
				$post->update_post_meta($args['id'], ["status" => "submitted"]);
				return ['status' => false, 'msg' => 'Sorry, the system failed to give value to the payer, Please contact the software developer.'];
			}
		} else {
			if($error_method == NULL || $error_method == "") {
				$info = "The admin in this mention, rejected the payment of ".toMoney($invoice->total(true))." by ".get_fullname($args['user_id'])." on ".date(_DATE_FORMAT_, $invoice->invoice->date_created);
				admin_log($info);
				$info = get_fullname($session->id)." rejected a payment ref #".$args['in_ref']." of ".toMoney($invoice->total(true))." by ".get_fullname($user_meta);
				inform_admins($info, "PAYMENT REJECTED", $home_url."invoice?id=".$invoice->invoice->id, "super_admin", "admin", "admin_tech", "super_admin_tech");
				return ['status' => true, 'msg' => 'You have successfully rejected this payment. Thank you.'];
			} else {
				$post->update_post_meta($args['id'], ["status" => "submitted"]);
				return ['status' => false, 'msg' => 'Sorry, there is no function <strong>'.$invoice->invoice->error_method.'</strong> in place to regularlize the system, Please contact the software developer.'];
			}
			
		}
	}
}

function pm_approve_payout($args) {
	$post = new post;
	$session = Session::getInstance();
	$payout_meta = $post->get_post_meta($args['id']);
	
	if($payout_meta['posted_by'] == $session->id) {
		return ['status' => false, 'msg' => 'Sorry, you cannot approve your own payout request'];
	} else {
		$commission_on_payout = ($option = get_option('commission_on_payout')) ? $option : 0;
		if($commission_on_payout > 0) {
			$commission = 0.01 * $commission_on_payout * $payout_meta['amount'];
		} else $commission = 0;
		$to_pay = $payout_meta['amount'] - $commission;
		$beneficiary = get_fullname($payout_meta['posted_by']);
		$narration = "Payout request reference number: ".$payout_meta['ref']." ifo ".$beneficiary;
		$outflow = pm_post_outflow($payout_meta['amount'], $narration, $beneficiary, $payout_meta['ref']);
		if($outflow) {
			if($commission > 0) {
				$narration = $commission_on_payout."% Commission on Payout request reference number: ".$payout_meta['ref']." by ".$beneficiary;
				$inc = pm_post_income($commission, $narration, $beneficiary, $payout_meta['ref']);
			}
			$res = $post->update_post_meta($args['id'], ['status' => 'approved']);
			$info = "Your payout request has been approved by the admin. You will receive value in few minutes. Thank you";
			inform_user($args['userid'], $info, "PAYOUT REQUEST APPROVED", get_option("home_url"), EMAIL, SMS, NOTIFICATION);
			return ['status' => true, 'msg' => 'You have approved the payout request of '.$beneficiary];
		} else {
			return ['status' => false, 'msg' => 'This action is not allowed'];
		}
		
	}
	
}

function pm_disapprove_payout($args) {
	$post = new post;
	$session = Session::getInstance();
	
	if($args['userid'] == $session->id) {
		return ['status' => false, 'msg' => 'Sorry, you cannot disapprove your own payout request'];
	} else {
		$payout_meta = $post->get_post_meta($args['id']);
		$narration = "Refund: payout request reference number: ".$payout_meta['ref'];
		$cre = pm_credit_wallet($args['userid'], $payout_meta['amount'], $narration, $payout_meta['ref']);
		if($cre) {
			$res = $post->update_post_meta($args['id'], ['status' => 'disapproved']);
			$info = "Your payout request was disapproved by the admin due to the following reasons: \"".$args['reason']."\". Your ewallet has been credited back with the sum of ".toMoney($payout_meta['amount']).". Thank you";
			inform_user($args['userid'], $info, "PAYOUT REQUEST DENIED", get_option("home_url"), EMAIL, SMS, NOTIFICATION);
			return ['status' => true, 'msg' => 'You have disapproved the payout request of '.get_fullname($args['userid'])];
		} else {
			return ['status' => false, 'msg' => 'This action is not allowed'];
		}
		
	}
	
}

function pm_approve_expense($args) {
	$post = new post;
	$session = Session::getInstance();
	
	if($args['posted_by'] == $session->id) {
		return ['status' => false, 'msg' => 'Sorry, you cannot approve your own expense request'];
	} else {
		$res = $post->update_post_meta($args['id'], ['status' => 'approved']);
		$info = "Your expense request reference number: ".$args['ref']." has been approved.";	
		inform_user($args['posted_by'], $info, "EXPENSE REQUEST APPROVED", get_option("home_url"), EMAIL, SMS, NOTIFICATION);
		return ['status' => true, 'msg' => 'You have approved this expense. please refresh to see the changes'];
	}
}

function pm_disapprove_expense($args) {
	$post = new post;
	$session = Session::getInstance();
	
	if($args['posted_by'] == $session->id) {
		return ['status' => false, 'msg' => 'Sorry, you cannot disapprove your own expense request'];
	} else {
		$res = $post->update_post_meta($args['id'], ['status' => 'disapproved']);
		$info = "Your expense request reference number: ".$args['ref']." was disapproved.";	
		inform_user($args['posted_by'], $info, "EXPENSE REQUEST DENIED", get_option("home_url"), EMAIL, SMS, NOTIFICATION);
		return ['status' => true, 'msg' => 'You have disapproved this expense. please refresh to see the changes'];
	}
}

function pm_cancel_invoice($args) {
	$invoice = new pm_invoice();
	$invoice->get_invoice_by_id($args['id']);
	if($invoice->invoice && $invoice->status() === "unpaid") {
		$invoice->delete();
		$info = "Your invoice #".$invoice->invoice->invoice_number." was cancelled by admin";
		inform_user($invoice->user_id, $info, "INVOICE CANCELLED", get_option("home_url"), EMAIL, SMS, NOTIFICATION);
		admin_log("Cancelled invoice #".$invoice->invoice->invoice_number." Billed to ".get_fullname($invoice->user_id)." of amount ".toMoney($invoice->total(true)).". Description: ".$invoice->description());
		return ['status' => true, 'msg' => 'You have successfully cancelled and deleted this invoice.'];
	}
	return ['status' => false, 'msg' => 'Invoice has either been paid for or already cancelled.'];
}

function pm_remove_account($args) {
	$user = new user;
	$session = Session::getInstance();
	if($user->user_login($session->id, $args['password']) == 0) {
		return ['status' => false, 'msg' => 'Sorry, you entered a wrong password.'];
	}
	if($user->user_login($session->id, $args['password']) == -1) {
		return ['status' => false, 'msg' => 'Sorry, you cannot perform this action.'];
	}
	if($user->user_login($session->id, $args['password']) == 1) {
		$subject = "REQUEST TO REMOVE ACCOUNT";
		$action = get_option("home_url")."pm-account?action=".base64_encode("pm_remove_account_confirm")."&id=".base64_encode($args['id']);
		$info = "<p>There is a request to remove an account details added in your profile. Click the link below to confirm or highlight and copy the link (if not clickable)</p>";
		$info .= "<a href=\"".$action."\">".$action."</a><br/>";
		$info .= "<p>If you did not initiate this request, please <strong>DO NOT CLICK</strong> on the link above. You may consider changing your password.</p>";
		inform_user($session->id, $info, $subject, $action, EMAIL);
		return ['status' => true, 'msg' => 'We sent you a mail to this effect. Please check your mail to complete this process.'];
	}
	
	return ['status' => false, 'msg' => serialize($args)];
}

function pm_remove_account_confirm($args) {
	$post = new post;
	$id = base64_decode($args['id']);
	$post->drop_post($id);
	$session = Session::getInstance();
	$session->message = "Account removed successfully";
}

function pm_add_account_confirm($args) {
	$post = new post;
	$id = base64_decode($args['id']);
	$post->update_post_meta($id, ['status' => 'active']);
	$session = Session::getInstance();
	$session->message = "Account added successfully";
}

function pm_download_invoice($args) {
	$invoice = new pm_invoice();
	$invoice->get_invoice_by_id($args['id']);
	$settings = [
		'html' => $invoice->invoice_template(),
		'pdf_header_title' => $invoice->invoice->invoice_number,
        'pdf_subject' => $invoice->invoice->invoice_number,
		'output_file_name' => $invoice->invoice->invoice_number.'-invoice.pdf',
	];
	$settings = array_merge($settings, $args);
	make_pdf($settings);
}

function pm_download_invoice_receipt($args) {
	$invoice = new pm_invoice();
	$invoice->get_invoice_by_id($args['id']);
	$settings = [
		'html' => $invoice->full_receipt_template(),
		'pdf_header_title' => $invoice->invoice->invoice_number,
        'pdf_subject' => $invoice->invoice->invoice_number,
		'output_file_name' => $invoice->invoice->invoice_number.'-receipt.pdf',
	];
	$settings = array_merge($settings, $args);
	make_pdf($settings);
}