<?php
namespace App\Http\Controllers\V1\QueryTraits;

use App\Models\ClientCollection;
use App\Models\Hims\AutoObservationData;

trait SwApiQuery
{
    public function getSwAllDataQuery($data, $clientCollectionId, $paginate = false)
    {
        $Datas = AutoObservationData::query()
            ->with('Station')
            ->withWhereHas('Station', function ($query) use ($data, $clientCollectionId) {
                if (ClientCollection::whereNull('is_all_station')->find($clientCollectionId)) {
                    $query->whereHas('ClientCollectionStation', function ($query) use ($clientCollectionId) {
                        $query->where('api_client_collection_stations.client_collection_id', $clientCollectionId); // 21 is for surface water
                    });
                }

                if (isset($data['identifier'])) {
                    $query->where('station_id', $data['identifier']);
                } else {
                    $query->where('station_id', 'like', 'SW%');
                }
            });

        if (isset($data['date']) && $data['date']) {
            $Datas->whereDate('observation.time', $data['date']);
        } else {
            if (isset($data['from_date']) && $data['from_date']) {
                $Datas->whereDate('observation.time', '>=', $data['from_date']);
            }

            if (isset($data['to_date']) && $data['to_date']) {
                $Datas->whereDate('observation.time', '<=', $data['to_date']);
            }
        }

        if (isset($data['per_page']) && ! $paginate) {
            $Datas->limit($data['per_page']);
        }

        if (! isset($data['per_page'])) {
            $data['per_page'] = 10;
        }

        if ($paginate) {
            return $Datas->paginate($data['per_page']);
        }

        $Datas->limit(10);

        return $Datas->get();
    }
}