<?php 

function qf_get_payouts($options) {
	$post = new post;
	$sorting = new sorting;
	$session = Session::getInstance();
	$args = [
		'type' => 'payout'
	];
	if(current_user_can("approve_payout")) {
		$response['admin'] = 1;
	} else {
		$response['admin'] = 0;
		$args['user_id'] = $session->id;
	}
	
	if($options['args']['status'] !== '' && $options['args']['status'] !== null) {
		$args['status'] = $options['args']['status'];
	}
	$response['options'] = $options;
	$response['payouts'] = $post->get_post_by_meta_data($args);
	$response['payouts'] = $sorting->sort_by_meta_value($response['payouts'], "posted_on", "DESC");
	if(isset($options['args']['from'])) {
		$to = (isset($options['args']['to']) && $options['args']['to'] != '') ? strtotime($options['args']['to']) : time();
		$from = strtotime($options['args']['from']);
		$response['payouts'] = filter_post_result_by_date_range($response['payouts'], $from, $to, 'posted_on');
	}
	if(_count($response['payouts'])) {
		foreach ($response['payouts'] as $key => &$value) {
			$value['date'] = date(_DATE_FORMAT_, $value['posted_on']);
			$value['requester'] = get_fullname($value['user_id']);
			// $value['receiving_account'] = apply_filters("pm_payouts_receiving_account", $value['user_id']);
			$value['amount'] = toMoney($value['amount']);
		}
	}
	return $response;
}

function qf_get_expenses($options) {
	$post = new post;
	$sorting = new sorting;
	$session = Session::getInstance();
	$args = [
		'type' => 'expense'
	];
	if(current_user_can("approve_expense")) {
		$response['admin'] = 1;
	} else {
		$response['admin'] = 0;
	}
	
	if($options['args']['status'] !== '' && $options['args']['status'] !== null) {
		$args['status'] = $options['args']['status'];
	}
	$currency = str_replace("0", '', toMoney(0));
	$response['currency'] = str_replace(".", '', $currency);
	$response['options'] = $options;
	$response['expenses'] = $post->get_post_by_meta_data($args);
	$response['expenses'] = $sorting->sort_by_meta_value($response['expenses'], "posted_on", "ASC");
	if(isset($options['args']['from'])) {
		$to = (isset($options['args']['to']) && $options['args']['to'] != '') ? strtotime($options['args']['to']) : time();
		$from = strtotime($options['args']['from']);
		$response['expenses'] = filter_post_result_by_date_range($response['expenses'], $from, $to, 'posted_on');
	}
	if(_count($response['expenses'])) {
		foreach ($response['expenses'] as $key => &$value) {
			$value['date'] = date(_DATE_FORMAT_, $value['posted_on']);
			$value['_amount'] = toMoney($value['amount']);
			$value['_posted_by'] = get_fullname($value['posted_by']);
		}
	}
	return $response;
}

function qf_get_direct_credits($options) {
	$post = new post;
	$sorting = new sorting;
	$session = Session::getInstance();
	$args = [
		'type' => 'credit_user'
	];
	if(current_user_can("approve_direct_credit")) {
		$response['admin'] = 1;
	} else {
		$response['admin'] = 0;
	}
	
	if($options['args']['status'] !== '' && $options['args']['status'] !== null) {
		$args['status'] = $options['args']['status'];
	}
	$currency = str_replace("0", '', toMoney(0));
	$response['currency'] = str_replace(".", '', $currency);
	$response['options'] = $options;
	$response['direct_credits'] = $post->get_post_by_meta_data($args);
	$response['direct_credits'] = $sorting->sort_by_meta_value($response['direct_credits'], "posted_on", "ASC");
	if(isset($options['args']['from'])) {
		$to = (isset($options['args']['to']) && $options['args']['to'] != '') ? strtotime($options['args']['to']) : time();
		$from = strtotime($options['args']['from']);
		$response['credit'] = filter_post_result_by_date_range($response['direct_credits'], $from, $to, 'posted_on');
	}
	if(_count($response['direct_credits'])) {
		foreach ($response['direct_credits'] as $key => &$value) {
			$value['date'] = date(_DATE_FORMAT_, $value['posted_on']);
			$value['_amount'] = toMoney($value['amount']);
			$value['_posted_by'] = get_fullname($value['posted_by']);
		}
	}
	return $response;
}

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

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

		default:
			$query = ['type' => ['bank_deposit', 'bank_withdrawal'], 'apply_db_session' => 1, 'status' => 'approved', 'bank_id' => $args['args']['ledger_type']];
			$query_type = "bankLedger";
			break;
	}

	if(isset($args['args']['from']) && $args['args']['from'] !== "") {
		$query["_range_from"] = strtotime($args['args']['from']);
	}
	if(isset($args['args']['to']) && $args['args']['to'] !== "") {
		$query["_range_to"] = strtotime("11.59 PM ". $args['args']['to']);
	}
	if(isset($args['args']['db_section_id']) && $args['args']['db_section_id'] !== "" && $args['args']['db_section_id'] !== "all") {
		$query['db_section_id'] = $args['args']['db_section_id'];
	}

	$txn = $post->get_post_by_meta_data($query, "LIKE", false, $args['limit'], $args['offset']);

	if(_count($txn) && is_array($txn)) {
		$table = new table("ledger-table", $txn);
		$table->query_type = $query_type;
		$table->table_class = "table table-bordered";
		$table->set_display_columns([
			"sn" => "SN",
			"posted_on" => "Date",
			"user_id" => "Beneficiary/Payer",
			"description" => "Description",
			"ref" => "Reference",
			"inflow" => "Inflow",
			"outflow" => "Outflow",
			"balance" => "Balance</em>"
		]);
		$table->set_dynamic_columns([
			"posted_on" => "_tf_get_date",
			"user_id" => "_tf_get_ledger_beneficiary_payer",
			"description" => "_tf_get_fee_description",
			"inflow" => "_tf_get_ledger_inflow",
			"outflow" => "_tf_get_ledger_outflow",
			"balance" => "_tf_get_ledger_balance",
			"ref" => "_tf_get_ledger_ref"
		]);
		
		if(isset($args['temp'])) {
			$table->temp = $args['temp'];
		}
		if($args['count'] > 0) {
			$response['html'] = $table->table_rows();
		} else $response['html'] = $table->table_html();

		$response['temp'] = $table->temp;
		$response['continue'] = true;
	}
	else {
		if($args['count'] > 0) {
			$from = isset($query['_range_from']) ? $query['_range_from'] : 0;
			$balance_bf = pm_get_balance_bf($from, $args['args']['ledger_type']);
			$grand_total = $balance_bf['balance'] + $args['temp']['balance'];
			$html = "<tr><td colspan=5 style=\"text-align:center;background: #e8e8e8;padding: 0;font-size: 15px;\"><em>----- SUMMARY -----</em></td><td style=\"text-align:center;background: #e8e8e8;padding: 0;font-size: 15px;\"><em>INFLOW</em></td><td style=\"text-align:center;background: #e8e8e8;padding: 0;font-size: 15px;\"><em>OUTFLOW</em></td><td style=\"text-align:center;background: #e8e8e8;padding: 0;font-size: 15px;\"><em>BALANCE</em></td></tr>";
			$html .= "<tr><th colspan=5 style=\"text-align:right;\">TOTAL</th>";
			$html .= "<th>".toMoney($args['temp']['total_inflow'])."</th>";
			$html .= "<th>".toMoney($args['temp']['total_outflow'])."</th>";
			$html .= "<th style=\"text-align:right;\">".toMoney($args['temp']['balance'])."</th>";
			$html .= "</tr>";
			$html .= "<tr><th colspan=5 style=\"text-align:right;\">Balance Brought Forward Till ".$args['args']['from']."</th>";
			$html .= "<th colspan=3 style=\"text-align:right;\">".toMoney($balance_bf['balance'])."</th>";
			$html .= "</tr>";
			$html .= "<tr><th colspan=5 style=\"text-align:right;\">GRAND TOTAL</th>";
			$html .= "<th colspan=3 style=\"text-align:right;\">".toMoney($grand_total)."</th>";
			$html .= "</tr>";
			$response['html'] = $html;
			$response['in_container'] = true;
		} else $response['html'] = "no transaction found";
		$response['continue'] = false;
	}
	$response['container'] = "ledger-table tbody";
	return $response;
}

function pm_get_qf_my_invoices($args) {
	$query = new query;

	$sql = "SELECT * FROM invoice
			WHERE `user_id` = ".$args['args']['user_idx'];

	if($args['args']['status'] === "paid") {
		$sql .= " AND `status` LIKE '".$args['args']['status']."'";
	} else {
		$sql .= " AND `status` NOT LIKE 'paid'";
	}
	

	$sql .=	" LIMIT ".$args['limit']." OFFSET ".$args['offset'];
	$res = $query->get_results($sql, ARRAY_A);

	if(_count($res) && is_array($res)) {
		$table = new table("invoices-table", $res);
		$table->action_pos = 1;
		$table->set_display_columns([
			"sn" => "SN",
			// "user_id" => "User",
			"invoice_number" => "Invoice Number",
			"total" => "Invoice Total",
			"date_created" => "Date",
			"status" => "Status"
		]);
		$table->set_dynamic_columns([
			"total" => "_tf_get_invoice_total",
			"status" => "_tf_get_invoice_status"
		]);
		if($args['args']['status'] === 'paid') {
			$table->set_action_links([
				"View Invoice & Pay" => "invoice"
			]);
			$table->set_action_access([
				"View Invoice & Pay" => "invoice"
			]);
			$table->set_action_args([
				"View Invoice & Pay" => ["id" => "id"]
			]);
		} else {
			$table->set_action_links([
				"View Invoice & Pay" => "invoice",
				"Add Payment" => "pm-add-payment",
				"Edit" => "edit-invoice",
				"Cancel" => false
			]);
			$table->set_action_access([
				"View Invoice & Pay" => "invoice",
				"Add Payment" => "pm_add_payment",
				"Edit" => "pm_edit_invoice",
				"Cancel" => "pm_cancel_invoice"
			]);
			$table->set_action_args([
				"View Invoice & Pay" => ["id" => "id"],
				"Add Payment" => ["ref" => "invoice_number", 'onreturncb' => 'removeTableRow'],
				"Edit" => ["id" => "id"],
				"Cancel" => ["id" => "id", 'callback' => 'removeTableRow']
			]);
			$table->set_action_callback([
				"Cancel" => "pm_cancel_invoice"
			]);
		}
		if(isset($args['temp'])) {
			$table->temp = $args['temp'];
		}
		if($args['count'] > 0) {
			$response['html'] = $table->table_rows();
		} else $response['html'] = $table->table_html();

		$response['temp'] = $table->temp;
		$response['continue'] = true;
	}
	else {
		if($args['count'] > 0) {
			$response['html'] = "";
		} else $response['html'] = "no result found".$sql;
		$response['continue'] = false;
	}
	$response['container'] = "invoices-table tbody";
	return $response;
}

function pm_qf_get_invoices($args) {
	$query = new query;
	$user = new user;
	$session = Session::getInstance();
	$user_meta = $user->get_user_meta($session->id);
	// $exempt_users = trim_array(get_option("exempt_users"));
	$settings = ["where" => $args["args"], "limit" => $args['limit'], "offset" => $args['offset']];
	if($args['args']['status'] !== "paid") {
		$settings["where"]["status"] = "paid";
		$settings["compare"] = ["status" => "NOT LIKE"];
	} else {
		$settings["compare"] = ["status" => "LIKE"];
	}
	unset($settings["where"]["from"]);
	unset($settings["where"]["to"]);
	$res = $query->quick_select("invoice", $settings, ARRAY_A);;

	if(_count($res) && is_array($res)) {
		$table = new table("invoices-table", $res);
		$table->set_display_columns([
			"sn" => "SN",
			"date_created" => "Date",
			"user_id" => "User",
			"invoice_number" => "Invoice Number",
			"total" => "Invoice Total",
			"status" => "Status"
		]);
		$table->set_dynamic_columns([
			"total" => "_tf_get_invoice_total",
			"status" => "_tf_get_invoice_status"
		]);
		if($args['args']['status'] === 'paid') {
			$table->set_action_links([
				"View Invoice" => "invoice",
				"Download" => ""
			]);
			$table->set_action_access([
				"View Invoice" => "invoice",
				"Download" => "invoice"
			]);
			$table->set_action_callback([
				"Download" => false
			]);
			$table->set_action_args([
				"View Invoice" => ["id" => "id"],
				"Download" => ["id" => "id", "action" => base64_encode("pm_download_invoice"), "output_type" => "D"]
			]);
		} else {
			$table->set_action_links([
				"View Invoice" => "invoice",
				"Add Payment" => "pm-add-payment",
				"Edit" => "edit-invoice",
				"Cancel" => false,
				"Download" => ""
			]);
			$table->set_action_access([
				"View Invoice" => "invoice",
				"Add Payment" => "pm_add_payment",
				"Edit" => "pm_edit_invoice",
				"Cancel" => "pm_cancel_invoice",
				"Download" => "invoice"
			]);
			$table->set_action_args([
				"View Invoice" => ["id" => "id"],
				"Add Payment" => ["ref" => "invoice_number"],
				"Edit" => ["id" => "id"],
				"Cancel" => ["id" => "id", 'callback' => 'click', 'callbackid' => '#btn-pm_qf_invoices'],
				"Download" => ["id" => "id", "action" => base64_encode("pm_download_invoice"), "output_type" => "D"]
			]);
			$table->set_action_popup([
				"Add Payment" => true
			]);
			$table->set_action_callback([
				"Cancel" => "pm_cancel_invoice"
			]);
		}
		if(isset($args['temp'])) {
			$table->temp = $args['temp'];
		}
		if($args['count'] > 0) {
			$response['html'] = $table->table_rows();
		} else $response['html'] = $table->table_html();

		$response['temp'] = $table->temp;
		$response['continue'] = true;
	}
	else {
		if($args['count'] > 0) {
			$response['html'] = "";
		} else $response['html'] = "no result found";
		$response['continue'] = false;
	}
	$response['container'] = "invoices-table tbody";
	return $response;
}

function pm_get_payments($args) {
	$post = new post;
	$query = ['type' => 'credit', 'apply_db_session' => 1, 'status' => $args['status']];
	if(isset($args['from']) && $args['from'] !== "") {
		$query["_range_from"] = strtotime($args['from']);
	}
	if(isset($args['to']) && $args['to'] !== "") {
		$query["_range_to"] = strtotime("11.59 PM ". $args['to']);
	}
	$query = apply_filters("pm_get_payments_filter", $query, $args);

	$credits = $post->get_post_by_meta_data($query);
	$table = new table("credit_table", $credits);
	$columns = [
		"sn" => "SN",
		"posted_on" => "Date",
		"user_id" => "Paid By",
		"description" => "Description",
		"amount" => "Amount",
		"mode" => "Payment Method",
		"in_ref" => "Reference",
		"attachment" => "Attachment"
	];
	if($args['status'] === "confirmed") {
		$columns['confirmed_by'] = "Confirmed By";
		$columns['confirmed_on'] = "Confirmed On";
	}
	if($args['status'] === "rejected") {
		$columns['rejected_by'] = "Rejected By";
		$columns['rejected_on'] = "Rejected On";
		$columns['reason'] = "Reason";
	}
	$table->set_display_columns($columns);
	$table->set_dynamic_columns([
		'description' => "_tf_pm_get_invoice_description",
		// 'amount' => "_tf_pm_get_invoice_amount",
		'attachment' => "_tf_pm_get_invoice_attachment",
		'confirmed_by' => "_tf_pm_confirmed_by",
		'rejected_by' => "_tf_get_fullname_id",
		'confirmed_on' => "_tf_get_date",
		'rejected_on' => "_tf_get_date"
	]);
	if($args['status'] === "submitted") {
		$table->set_action_callback([
			"Confirm" => "pm_confirm_payment"
		]);
		$table->set_action_links([
			"Confirm" => false,
			"Reject" => "reject-payment"
		]);
		$table->set_action_access([
			"Confirm" => "confirm_payments",
			"Reject" => "reject_payments"
		]);
		$table->set_action_popup([
			"Reject" => true
		]);
		$table->set_action_args([
			"Confirm" => ["id" => "id", "in_ref" => "in_ref", "user_id" => "user_id", "callback" => "click", "callbackid" => "#search-query-btn"],
			"Reject" => ["id" => "id"]
		]);
	}
	
	return $table->table_html();
}

function pm_get_payment_history($args) {
	$post = new post;
	$session = Session::getInstance();
	$query = ['type' => 'credit', 'user_id' => $session->id, 'status' => $args['status']];
	if(isset($args['from']) && $args['from'] !== "") {
		$query["_range_from"] = strtotime($args['from']);
	}
	if(isset($args['to']) && $args['to'] !== "") {
		$query["_range_to"] = strtotime("11.59 PM ". $args['to']);
	}
	$query = apply_filters("pm_get_payments_filter", $query, $args);

	$credits = $post->get_post_by_meta_data($query);
	$table = new table("credit_table", $credits);
	$columns = [
		"sn" => "SN",
		"posted_on" => "Date",
		"user_id" => "Paid By",
		"description" => "Description",
		"amount" => "Amount",
		"mode" => "Payment Method",
		"in_ref" => "Reference",
		"attachment" => "Attachment"
	];
	if($args['status'] === "confirmed") {
		$columns['confirmed_by'] = "Confirmed By";
	}
	if($args['status'] === "rejected") {
		$columns['rejected_by'] = "Rejected By";
	}
	$table->set_display_columns($columns);
	$table->set_dynamic_columns([
		'description' => "_tf_pm_get_invoice_description",
		'amount' => "_tf_pm_get_invoice_amount",
		'attachment' => "_tf_pm_get_invoice_attachment",
		'confirmed_by' => "_tf_pm_confirmed_by",
		'rejected_by' => "_tf_get_fullname_id"
	]);
	
	return $table->table_html();
}

function pm_get_wallet_statement($args) {
	$post = new post;
	$session = Session::getInstance();
	$query = ['type' => ['credit_user', 'debit_user'], 'user_id' => $args['user_id'], 'status' => 'confirmed'];
	if(isset($args['from']) && $args['from'] !== "") {
		$query["_range_from"] = strtotime($args['from']);
	}
	if(isset($args['to']) && $args['to'] !== "") {
		$query["_range_to"] = strtotime("11.59 PM ". $args['to']);
	}
	$query = apply_filters("pm_get_payments_filter", $query, $args);

	$credits = $post->get_post_by_meta_data($query);
	$table = new table("credit_table", $credits);
	$columns = [
		"sn" => "SN",
		"posted_on" => "Date",
		"narration" => "Narration",
		"ref" => "Reference",
		"credit" => "Credit",
		"debit" => "Debit",
		"balance" => "Balance"
	];
	$table->set_display_columns($columns);
	$table->set_dynamic_columns([
		'credit' => "_tf_get_wallet_credit",
		'debit' => "_tf_get_wallet_debit",
		'balance' => "_tf_get_wallet_balance"
	]);
	
	return $table->table_html();
}

function pm_qf_get_wallet_statement($args) {
	$post = new post;
	$query = ['type' => ['credit_user', 'debit_user'], 'user_id' => $args['args']['user_id'], 'status' => 'confirmed'];
	$res = $post->get_post_by_meta_data($query, 'LIKE', false, $args['limit'], $args['offset']);
	if(_count($res) && is_array($res)) {
		$table = new table("invoices-table", $res);
		// $table->balance = 0;
		$table->set_display_columns([
			"sn" => "SN",
			"posted_on" => "Date",
			"narration" => "Narration",
			"ref" => "Reference",
			"credit" => "Credit",
			"debit" => "Debit",
			"balance" => "Balance"
		]);
		$table->set_dynamic_columns([
			'credit' => "_tf_get_wallet_credit",
			'debit' => "_tf_get_wallet_debit",
			'balance' => "_tf_get_wallet_balance"
		]);
		if(isset($args['temp'])) {
			$table->temp = $args['temp'];
		}
		if($args['count'] > 0) {
			$response['html'] = $table->table_rows();
		} else $response['html'] = $table->table_html();

		$response['temp'] = $table->temp;
		$response['continue'] = true;
	}
	else {
		if($args['count'] > 0) {
			$response['html'] = "";
		} else $response['html'] = "no result found";
		$response['continue'] = false;
	}
	$response['container'] = "invoices-table tbody";
	return $response;
}