<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Mail;

class Estimate extends Model
{

	use SoftDeletes;
	
	protected $hidden = ['created_at', 'updated_at', 'deleted_at'];
	
	protected $appends = ['date_formatted', 'expiration_date_formatted', 'status_formatted', 'status_date_formatted', 'number'];
	
	protected $casts = [
		'attachments' => 'array',
		'description' => 'array'
	];
	
	public function company()
	{
		return $this->belongsTo('App\Company');
	}
	
	public function customer()
	{
		return $this->belongsTo('App\Customer')->withTrashed();
	}
	
	public function property()
	{
		return $this->belongsTo('App\Property')->withTrashed();
	}
	
	public function getDateFormattedAttribute()
    {
		return date('m/d/Y', strtotime($this->attributes['date']));
    }
	
	public function getExpirationDateFormattedAttribute()
    {
		return date('m/d/Y', strtotime($this->attributes['expiration_date']));
    }
	
	public function getStatusFormattedAttribute()
    {
		switch ($this->attributes['status']) {
			case 0:
				return 'Open';
				break;
			case 1:
				return 'Accepted';
				break;
			case 2:
				return 'Rejected';
				break;
			case 3:
				return 'Closed';
				break;
		}
    }
	
	public function getStatusDateFormattedAttribute()
    {
		return date('m/d/Y', strtotime($this->attributes['status_date']));
    }
	
	public function getNumberAttribute()
    {
		return '#EST' . $this->attributes['id'];
    }
	
	protected static function boot() {
		
		parent::boot();
		
		static::created(function($estimate) {
			
			$estimate->token = base64_encode(date('YmdHis') . rand(100000, 999999));
			
			if ($estimate->save()) {
				Mail::to($estimate->send_to)->send(new \App\Mail\EstimateDetail($estimate));
			}
			
		});
		
	}

}
