<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\V1\ApiController;
use App\Http\Resources\CsManualDataResource;
use App\Models\ClientCollection;
use App\Models\ClientCollectionParameter;
use App\Models\ClientCollectionStation;
use App\Models\Hims\HydrologyCsData;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CsApiController extends ApiController
{
    public function getCsDataManualJson(Request $request)
    {
        $ClientCollection = ClientCollection::whereHas('ClientToken', function ($query) {
            return $query->where('api_client_tokens.token', request()->bearerToken());
        })->active()->where('collection_id', 18)->first();

        if (!$ClientCollection) {
            return response()->json([
                'message' => 'You are not authorized to access this API',
                'status' => 'Unauthorized',
            ], 403);
        }

        $this->apiLogRequest($ClientCollection);

        $RequestData = [];

        if ($request->has('from_date')) {
            $RequestData['from_date'] = $request->from_date;
        } else {
            $RequestData['from_date'] = now()->format('Y-m-d');
        }

        if ($request->has('to_date')) {
            $RequestData['to_date'] = $request->to_date;
        } else {
            $RequestData['to_date'] = now()->format('Y-m-d');
        }

        if ($request->has('station_id')) {
            $RequestData['identifier'] = $request->station_id;
        } elseif ($request->has('station')) {
            $RequestData['identifier'] = $request->station;
        } elseif ($request->has('identifier')) {
            $RequestData['identifier'] = $request->identifier;
        } else {
            return response()->json([
                'message' => 'Please provide station id',
                'status' => 'errors',
            ], 422);
        }

        if ($request->has('per_page')) {
            $RequestData['per_page'] = $request->per_page;
        }

        $ClientCollectionParameter = ClientCollectionParameter::with('CollectionParameter')->where('collection_id', $ClientCollection->collection_id)->where('client_id', $ClientCollection->client_id)->get();

        if (!$ClientCollection->is_all_station && isset($RequestData['identifier'])) {
            if (!ClientCollectionStation::where('client_collection_id', $ClientCollection->id)->where('station_id', $RequestData['identifier'])->exists()) {
                return response()->json([
                    'message' => 'Your station is not authorized to access this API',
                    'status' => 'errors',
                ], 422);
            }
        }

        foreach ($ClientCollectionParameter as $key => $value) {
            if (isset($RequestData['per_page']) && $value->CollectionParameter->name == 'max_per_page') {
                if ($RequestData['per_page'] > $value->value) {
                    return response()->json([
                        'message' => 'Your per page limit is ' . $value->value,
                        'status' => 'errors',
                    ], 422);
                }

            }

            if (isset($RequestData['from_date']) && $value->CollectionParameter->name == 'start_date' && $value->value) {
                if (now()->parse($RequestData['from_date'])->format('Y-m-d') < now()->parse($value->value)->format('Y-m-d')) {
                    return response()->json([
                        'message' => 'Your from date limit is ' . $value->value,
                        'status' => 'errors',
                    ], 422);
                }
            }

            if (isset($RequestData['to_date']) && $value->CollectionParameter->name == 'end_date' && $value->value) {
                if (now()->parse($RequestData['to_date'])->format('Y-m-d') > now()->parse($value->value)->format('Y-m-d')) {
                    return response()->json([
                        'message' => 'Your to date limit is ' . $value->value,
                        'status' => 'errors',
                    ], 422);
                }
            }

        }

        $Datas = HydrologyCsData::query();

        $Datas->select('cs_data.station_id', 'cs_data.start_dt', 'cs_data.sl_no', 'cs_data.distance as cs_data_distance', 'cs_data.rl_val');

        $Datas->join(DB::raw('HYDROLOGY.SW_STATION_TBL@HYDRO10 sw_station_tbl'), function (JoinClause $join) {
            $join->on('cs_data.station_id', '=', 'sw_station_tbl.station_id');
        })
            ->with('Station')
            ->whereHas('Station', function ($query) use ($RequestData, $ClientCollection) {
                if (ClientCollection::whereNull('is_all_station')->find($ClientCollection->id)) {
                    $query->whereHas('ClientCollectionStation', function ($query) use ($ClientCollection) {
                        $query->where('api_client_collection_stations.client_collection_id', $ClientCollection->id); // 21 is for surface water
                    });
                }

                if (isset($RequestData['identifier'])) {
                    $query->where('station_id', $RequestData['identifier']);
                }
            });

        if (isset($RequestData['identifier'])) {
            $Datas->where('cs_data.station_id', $RequestData['identifier']);
        }

        if (isset($RequestData['date']) && $RequestData['date']) {
            $Datas->whereDate('cs_data.start_dt', $RequestData['date']);
        } else {
            if (isset($RequestData['from_date']) && $RequestData['from_date']) {
                $Datas->whereDate('cs_data.start_dt', '>=', $RequestData['from_date']);
            }

            if (isset($RequestData['to_date']) && $RequestData['to_date']) {
                $Datas->whereDate('cs_data.start_dt', '<=', $RequestData['to_date']);
            }
        }

        return CsManualDataResource::collection($Datas->get()->sortBy('start_dt'))->additional($this->commonJsonReturn('You surface water level manual data json format is successfully'));
    }
}
