<?php namespace NetSTI\System\Models;

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

class Estimate extends Model{

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

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

	// RELATIONS
	public $hasOne = [];
	public $hasMany = [];
	public $belongsTo = [
		'contact' => ['NetSTI\System\Models\Contact'],
		'owner' => ['Backend\Models\User']
	];
	public $belongsToMany = [
		'products' => [
			'NetSTI\System\Models\Product',
			'table' => 'netsti_system_estimates_products',
			'pivot' => ['price', 'description','tax','discount','quantity','total'],
			'pivotModel' => 'NetSTI\System\Models\EstimateProductPivot'
		],
	];
	public $morphTo = [];
	public $morphOne = [];
	public $morphMany = [];
	public $attachOne = [];
	public $attachMany = [];

	public function afterCreate(){
		PaymentsSettings::set('estimate_number', PaymentsSettings::get('estimate_number')+1);
	}

	public function beforeCreate(){
		$prefix = PaymentsSettings::get('estimate_prefix');
		$next   = PaymentsSettings::get('estimate_number');
		$digits = PaymentsSettings::get('estimate_digits');

		$this->nid = $next;
		$this->label_nid = $prefix.str_pad($next, $digits, 0, STR_PAD_LEFT);
		$this->owner_id = BackendAuth::getUser()->id;
	}

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

}