<?php
namespace App\Models\Hims;

use App\Models\ClientCollectionStation;
use App\Models\Hims\GtStation;
use App\Models\Hims\Station;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Rishadblack\OracleTableLinker\Traits\HasDbLink;

class AutoObservationData extends Model
{
    use HasFactory;
    use HasDbLink;

    protected $connection = 'oracle';
    public $incrementing  = false;
    protected $primaryKey = 'series_id';
    public $timestamps    = true;
    protected $guarded    = [];
    public $sequence      = null;
    protected $dateFormat = 'Y-M-d H:i:s';
    protected $casts      = [
        'time' => 'datetime',
    ];
    // protected $keyType = 'string';
    protected $table = 'ORACLE_USER.OBSERVATION@G2RAW';

    public function DataOrigin()
    {
        return $this->belongsTo(DataOrigin::class, 'origin_code', 'code');
    }

    public function Station()
    {
        return $this->belongsTo(Station::class, 'series_id', 'series_id');
    }

    public function GtStation()
    {
        return $this->belongsTo(GtStation::class, 'origin_code', 'new_id');
    }

    public function StationOrigin()
    {
        return $this->belongsTo(Station::class, 'series_id', 'series_id');
    }

    public function latestTime()
    {
        return $this->hasMany(self::class, 'oracle_user.observation.series_id', 'oracle_user.observation.series_id')
            ->select('oracle_user.observation.series_id', DB::raw('MAX(oracle_user.observation.time) as max_time'))
            ->groupBy('oracle_user.observation.series_id');
    }

    public function ClientCollectionStation()
    {
        return $this->hasMany(ClientCollectionStation::class, 'series_id', 'station_id');
    }
}