<?php

namespace App\Models;

class ClientBDTDevice extends Model
{
    protected $table = 'client_bdt_device';

    public function device() {
        return $this->hasOne(BDTDevice::class, 'id', 'device_id');
    }

    public function client() {
        return $this->hasOne(Client::class, 'id', 'client_id');
    }

    public function supplyOrders(){
        return $this->hasMany(SupplyOrder::class, 'client_bdt_device_id', 'id');
    }

    public function mostRecentMeasurement() {
        return $this->hasOne(ClientBDTMeasurement::class, 'id', 'most_recent_client_bdt_measurement_id');
    }


    public function lastDeviceMeasurement() {
        return BDTMeasurement::select('bdt_measurement.created_at', 'measurement.label', 'measurement.sbp_mm_hg', 'measurement.dbp_mm_hg', 'measurement.numeric_value')
            ->join('client_bdt_measurement', 'client_bdt_measurement.bdt_measurement_id', '=', 'bdt_measurement.id')
            ->join('measurement', 'measurement.client_bdt_measurement_id', '=', 'client_bdt_measurement.id')
            ->where('bdt_measurement.is_cellular_zero', '<>', true)
            ->whereNotNull('bdt_measurement.ts')
            ->where('client_bdt_measurement.client_id', $this->client_id)
            ->where('bdt_measurement.imei', $this->device->imei)
            ->orderBy('bdt_measurement.created_at', 'DESC')
            ->first();
    }

}
