<?php namespace NetSTI\System\Models;

use Model;
use Backend;
use ValidationException;

class Expense extends Model{

	// VALIDATIONS RULES
	use \October\Rain\Database\Traits\Validation;
	public $rules = [
		'subject' => ['required','min:5'],
		'type' => 'required',
		'account' => 'required',
		'amount' => 'required',
		'expense_at' => 'required'
	];

	// PROPERTIES
	protected $table = 'netsti_system_expenses';
	protected $dates = ['expense_at'];
	protected $guarded = [];
	protected $jsonable = [];

	// RELATIONS
	public $hasOne = [];
	public $hasMany = [];
	public $belongsTo = [
		'account' => ['NetSTI\System\Models\Account']
	];
	public $belongsToMany = [];
	public $morphTo = [];
	public $morphOne = [];
	public $morphMany = [];
	public $attachOne = [
		'invoice' => ['System\Models\File']
	];
	public $attachMany = [];

	public static function getMonthAmount($month){
		$monthExpenses = Expense::whereMonth('expense_at', '=', $month)->get();

		$resp = array(
			'incomings' => 0,
			'countIncomings' => 0,
			'expenses' => 0,
			'countExpenses' => 0,
			'total' => 0
		);

		foreach ($monthExpenses as $expense) {
			if($expense->type == "expense"){
				$resp['expenses'] += $expense->amount;
				$resp['total'] -= $expense->amount;
				$resp['countExpenses']++;
			}else{
				$resp['incomings'] += $expense->amount;
				$resp['total'] += $expense->amount;
				$resp['countIncomings']++;
			}
		}

		return $resp;
	}

	public function getGroupedAttribute(){
		$expense = $this->find($this->id);
		echo '<span style="margin-right:6px;color:#FFF;padding: 2px 4px;display:inline-block; background-color: #EEE; background-color: '.$expense->account->color.'; border-radius: 3px;">'.$expense->account->name.'</span>';
		if($expense->invoice)
			echo "<a href='".$expense->invoice->getPath()."' target='_blank'><i class='icon icon-file-o'></i></a>";
	}

	public function getAmountedAttribute()
	{
		$expense = $this->find($this->id);
		$amount = number_format($expense->amount, 2, '.', ',');
		if($expense->type == "expense")
			echo "<span class='text-danger'><b>L. -".$amount."</b></span>";
		else
			echo "<span class='text-success'><b>L. ".$amount."</b></span>";
	}
}