<?php

/**
 *
 * @copyright  2017 izend.org
 * @version    1
 * @link       http://www.izend.org
 */

require_once 'userhasrole.php';
require_once 'userprofile.php';
require_once 'models/payment.inc';

function invoice($lang, $arglist=false) {
	if (!(user_has_role('client') or user_has_role('administrator'))) {
		return run('error/unauthorized', $lang);
	}

	$payment_id=false;

	if (is_array($arglist)) {
		if (isset($arglist[0])) {
			$payment_id=$arglist[0];
		}
	}

	if (!$payment_id or !is_numeric($payment_id)) {
		return run('error/badrequest', $lang);
	}

	$r = payment_detail($payment_id);

	if (!$r) {
		return run('error/notfound', $lang);
	}
	extract($r);	/* payment_user_id payment_payed payment_amount payment_fee payment_vat payment_currency payment_billing_name payment_billing_address */

	$user_id=user_profile('id');

	if ($user_id != $payment_user_id and !user_has_role('administrator')) {
		return run('error/notfound', $lang);
	}

	$billing_name=$payment_billing_name;
	$billing_address=$payment_billing_address;

	$total=$payment_amount;
	$vat=$payment_vat;
	$ht=$payment_amount-$payment_vat;
	$vat_rate=($vat/$ht) * 100;
	$currency=$payment_currency;
	$date=$payment_payed;

	$payment_desc=translate('payment:desc', $lang);

	$number=date('Y', $date) . '-' . $payment_id;

	$now=time();

	$title=translate('invoice:title', $lang);

	$content = view('invoice', $lang, compact('now', 'billing_name', 'billing_address', 'number', 'date', 'ht', 'vat', 'total', 'currency', 'vat_rate', 'payment_desc'));

	$output = layout('invoice', compact('lang', 'title', 'content'));

	return $output;
}

