<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Property extends Model
{

	use SoftDeletes;
	
	public function company()
	{
		return $this->belongsTo('App\Company');
	}

	public function customer()
	{
		return $this->belongsTo('App\Customer')->select(['id', 'created_at', 'name', 'status', 'quickbooks_id', 'contacts']);
	}
	
	public function work_orders()
	{
		return $this->hasMany('App\WorkOrder');
	}
	
	public function attachments()
	{
		return $this->morphMany('App\Attachment', 'attachable');
	}
	
	public function notes()
	{
		return $this->morphMany('App\Note', 'notable');
	}
	
	public function property_equipments()
	{
		return $this->hasMany('App\PropertyEquipment');
	}
	
	protected $casts = [
		'location' => 'array',
		'general_informations' => 'array',
		'bodies_of_water' => 'array',
		'maintenance_records' => 'array'
	];
	
	protected $hidden = ['created_at', 'updated_at', 'deleted_at'];
	
	protected $appends = ['has_dog_formatted', 'address_type_formatted', 'number', 'quickbooks_formatted', 'is_valid_lat_lng'];
	
	public function getHasDogFormattedAttribute()
    {
		if (isset($this->general_informations['has_dog'])) {
			return ($this->general_informations['has_dog']) ? 'Yes' : 'No';
		}
        return null;
    }
	
	public function getAddressTypeFormattedAttribute()
    {
		if (isset($this->address_type)) {
			return ($this->address_type) ? 'Commercial' : 'Residential';
		}
        return 'Residential';
    }
	
	public function getLastTimeFilterCleaned()
    {
		
		$work_order_visits = array();
		
		foreach ($this->work_orders as $work_order) {
			$work_order_visit = WorkOrderVisit::where('work_order_id', $work_order->id)
													->where('status', 2)
														->where('was_filter_cleaned', 1)
															->orderBy('date', 'DESC')
																->first();
			if ($work_order_visit) {
				$work_order_visits[] = strtotime($work_order_visit->date);
			}
		}
		
		if (count($work_order_visits)) {
			rsort($work_order_visits);
			return date('m/d/Y', $work_order_visits[0]);
		}
		
		return '-';
		
    }
	
	public function getPinnedNotes()
	{
		return $this->notes()->where('pinned', 1)->get();
	}
	
	public function getNumberAttribute()
    {
		return '#P' . $this->attributes['id'];
    }
	
	public function getQuickbooksFormattedAttribute()
    {
		if (isset($this->quickbooks)) {
			return ($this->quickbooks) ? 'Yes' : 'No';
		}
        return 'No';
    }
	
	public function getIsValidLatLngAttribute()
    {
		if (!$this->location['lat'] || !$this->location['lng']) {
			return 'INVALID COORDINATES';
		}
        return '';
    }

}
