<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class AirWatch extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function setLastSeenAttribute($date)
    {
        return $this->attributes['last_seen'] =  format_workspace_one_datetime_to_db_datetime($date);
    }

    public function getLastSeenAttribute($date)
    {
        return parse_datetime_from_db_datetime($date);
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function asset()
    {
        return $this->belongsTo('App\Models\Asset');
    }

    public function getOwnershipAttribute()
    {
        if (!isset($this->attributes['ownership'])) {
            return '';
        }
        if ($this->attributes['ownership'] === 'C') {
            return 'Corporate';
        }

        if ($this->attributes['ownership'] == 'S') {
            return 'Shared';
        }

        if ($this->attributes['ownership'] == 'E') {
            return 'Employee Owned';
        }
        return '';
    }

    public function scopeRelationData($query, $value, $field)
    {
        if ($value) {
            if (is_array($value)) {
                return $query->whereIn($field, $value);
            }
            return $query->where($field, $value);
        }
        return $query;
    }

    public function mobileCarrier()
    {
        return $this->belongsTo('App\Models\Carrier', 'carrier_id', 'id');
    }


    public function scopeGetByAssetStatusIds($query, $statusIds)
    {
        return $query->whereHas('asset', function ($query) use ($statusIds) {
            $query->whereIn('asset_status_id', $statusIds);
        });
    }

    /**
     * @param mixed $query
     * @param mixed $assetTypeId
     * @param mixed $manufacturerId
     * 
     * @return [type]
     */
    public function scopeFilterByAssetTypeIdOrManufacturerId($query, $assetTypeId, $manufacturerId)
    {
        return $query->whereHas('asset.makeAndModel', function ($query) use ($assetTypeId, $manufacturerId) {
            $query = $query->where(function ($query) use ($assetTypeId, $manufacturerId) {
                $query = $query->where('assets.asset_type_id', '=', $assetTypeId)
                    ->orWhere('manufacturer_id', $manufacturerId);
            });
        });
    }
}
