<?php namespace NetSTI\System\Models;

use DB;
use Model;

class Taxdocument extends Model{
	// VALIDATIONS RULES
	use \October\Rain\Database\Traits\Validation;
	public $rules = [
		
	];

	// PROPERTIES
	protected $table = 'netsti_system_tax_documents';
	protected $guarded = [];
	protected $dates = [];
	public $timestamps = false;

	// RELATIONS
	public $hasOne = [];
	public $hasMany = [];
	public $belongsTo = [];
	public $belongsToMany = [];
	public $morphTo = [];
	public $morphOne = [];
	public $morphMany = [];
	public $attachOne = [];
	public $attachMany = [];

	public static function getTaxStatus(){
		$q = 'id, IF(end_date < NOW(),TRUE,FALSE) as isExpired, IF(actual_number > end_number,TRUE, FALSE) as isLimit';
		return DB::table('netsti_system_tax_documents')->select(DB::raw($q))->where('status',0)->get();
	}

	public static function getTaxDocuments(){
		foreach (Taxdocument::getTaxStatus() as $taxd) {
			if($taxd->isExpired || $taxd->isLimit){
				$td = Taxdocument::find($taxd->id);
				$td->status = 1;
				
				$td->save();
			}
		}
		return Taxdocument::where('status',0)->get();
	}

	public function getLabel($n){
		return $this->doc_prefix.str_pad($n, $this->digits, 0, STR_PAD_LEFT);
	}

	public function upRedord(){
		$this->actual_number++;
		$this->save();
	}

	public static function getTaxDocumentsOptions(){
		$docs = Taxdocument::getTaxDocuments();
		$r = [];
		$r[''] = '- - -';
		foreach ($docs as $value) {
			$r[$value->id] = $value->doc_type.' ['.$value->doc_name.']';
		}
		return $r;
	}
}
