<?php namespace NetSTI\System\Models;

use Model;
use Backend;
use BackendAuth;
use ValidationException;
use NetSTI\System\Models\PaymentsSettings;

class Invoice extends Model{

	// VALIDATIONS RULES
	use \October\Rain\Database\Traits\Validation;
	public $rules = [
		'contact' => 'required',
		'taxdocument_id' => 'required',
		'date' => 'required'
	];

	// PROPERTIES
	protected $table = 'netsti_system_invoices';
	protected $dates = ['date'];
	protected $guarded = [];
	protected $jsonable = [];

	// RELATIONS
	public $hasOne = [];
	public $hasMany = [];
	public $belongsTo = [
		'contact' => ['NetSTI\System\Models\Contact'],
		'taxdocument' => ['NetSTI\System\Models\Taxdocument'],
		'estimate' => ['NetSTI\System\Models\Estimate'],
		'owner' => ['Backend\Models\User']
	];
	public $belongsToMany = [
		'products' => [
			'NetSTI\System\Models\Product',
			'table' => 'netsti_system_invoices_products',
			'pivot' => ['price', 'description','tax','discount','quantity','total'],
			'pivotModel' => 'NetSTI\System\Models\InvoiceProductPivot'
		],
		'productsread' => [
			'NetSTI\System\Models\Product',
			'table' => 'netsti_system_invoices_products',
			'pivot' => ['price', 'description','tax','discount','quantity','total'],
			'pivotModel' => 'NetSTI\System\Models\InvoiceProductPivot'
		],
		'expenses' => [
			'NetSTI\System\Models\ExpensePayment',
			'table' => 'netsti_system_invoices_expenses'
		],
		'expensesread' => [
			'NetSTI\System\Models\ExpensePayment',
			'table' => 'netsti_system_invoices_expenses'
		],
	];
	public $morphTo = [];
	public $morphOne = [];
	public $morphMany = [];
	public $attachOne = [];
	public $attachMany = [];

	public static function getMonthAmount($month){
		$monthInvoices = Invoice::whereMonth('date', '=', $month)->get();

		$resp = array(
			'pendingAmount' => 0,
			'paidAmount' => 0,
			'balance' => 0,
			'pending' => 0,
			'approved' => 0,
			'paid' => 0
		);

		foreach ($monthInvoices as $invoice) {
			switch ($invoice->status) {
				case 0:
					$resp['pendingAmount'] += $invoice->total;
					$resp['pending']++;
					break;
				case 1: 
					$resp['pendingAmount'] += $invoice->total - $invoice->total_paid;
					$resp['paidAmount'] += $invoice->total_paid;
					$resp['approved']++; 
					break;
				case 2: 
					$resp['paidAmount'] += $invoice->total;
					$resp['paid']++;
					break;
				case 3:
					break;
			}
		}

		$resp['balance'] = $resp['paidAmount'] - $resp['pendingAmount'];

		return $resp;
	}

	public function afterCreate(){
		$this->taxdocument->upRedord();
	}

	public function beforeCreate(){
		$this->nid = $this->taxdocument->actual_number;
		$this->label_nid = $this->taxdocument->getLabel($this->taxdocument->actual_number);
		$this->owner_id = BackendAuth::getUser()->id;

		if($this->estimate != null)
			$this->products = $this->estimate->products;
	}

	public function beforeUpdate(){
		$this->saveTotal();
	}
	
	public function saveTotal(){
		$total = 0;
		foreach ($this->products as $product) {
			$total += $product->pivot->total;
		}
		$this->total = $total;
	}

	public function savePaid(){
		$total = 0;
		foreach ($this->expenses as $expense) {
			$total += $expense->amount;
		}
		$this->total_paid = $total;
	}

	public function getTaxdocumentIdOptions(){
		return Taxdocument::getTaxDocumentsOptions();
	}

	public function checkOverdue(){
		$date = date("Y-m-d", strtotime($this->date.' + '.PaymentsSettings::get('invoice_overdue').' days'));

		if(date("Y-m-d") > $date)
			return true;
		else
			return false;
	}

	public function setPayments(){
		foreach ($this->expenses as $expense) {
			if($expense->subject != $this->taxdocument->doc_type){
				$expense->setData($this->taxdocument->doc_type, $this->label_nid);
			}
		}
	}

	public function filterFields($fields, $context = null){
		if($context == 'create'){
			if($this->ifestimate)
				$fields->estimate->hidden = false;
			else
				$fields->estimate->hidden = true;
		}else{
			if($this->status > 0)
				$fields->total->hidden = true;
			if($this->status <> 1)
				$fields->debits->hidden = true;
		}
	}

}