<?php
namespace App\Models\Hims;

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 RawData extends Model
{
    use HasFactory;
    use HasDbLink;

    protected $primaryKey = '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.RAW_DATA@G2RAW';

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

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

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

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

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

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