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

use App\Http\Controllers\V1\ApiController;
use App\Http\Controllers\V1\QueryTraits\SwApiQuery;
use App\Http\Resources\RainfallDataResource;
use App\Http\Resources\WaterlevelDataResource;
use App\Models\ClientCollection;
use App\Models\ClientCollectionParameter;
use App\Models\Hims\FfwcData;
use App\Models\Hims\FfwcStation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FfwcDataController extends ApiController
{
    use SwApiQuery;

    public function wlObservationJson(Request $request)
    {
        $ClientCollection = ClientCollection::whereHas('ClientToken', function ($query) {
            return $query->where('api_client_tokens.token', request()->bearerToken());
        })->active()->where('collection_id', 7)->first();

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

        $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;
        } elseif ($request->has('sms_id')) {
            $RequestData['identifier'] = $request->sms_id;
        }

        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();

        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 ($value->value && 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 ($value->value && 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);
                }
            }

        }

        $Data = FfwcData::query()
        // $Data = DB::table(DB::raw('bwdbffwc.data_tbl@ffwcsms as dtbl'))
            ->where('d_type', 'W');
        // ->join(DB::raw('bwdbffwc.stations_tbl@ffwcsms as stbl'), 'stbl.keyword', '=','dtbl.station_code');

        if (isset($RequestData['date']) && $RequestData['date']) {
            $Data->whereDate('m_date', $RequestData['date']);
        } else {
            if (isset($RequestData['from_date']) && $RequestData['from_date']) {
                $Data->whereDate('m_date', '>=', $RequestData['from_date']);
            }

            if (isset($RequestData['to_date']) && $RequestData['to_date']) {
                $Data->whereDate('m_date', '<=', $RequestData['to_date']);
            }
        }

        $perPage = 10;

        if (isset($RequestData['per_page']) && $RequestData['per_page'] > 0) {
            $perPage = $RequestData['per_page'];
        }

        if (isset($RequestData['identifier'])) {
            $FFWCStation = FfwcStation::where(DB::raw("LOWER(station_id)"), strtolower($RequestData['identifier']))->first();

            $Data->where(DB::raw("LOWER(station_code)"), strtolower($FFWCStation->ffwc_keyword));

            // $Data = $Data->first();

            // if(!$Data) {
            //     return response()->json([
            //         'message' => 'No data found',
            //         'status' => 'errors'
            //     ], 404);
            // }

            // return new WaterlevelDataResource($Data);
        }

        // dd($Data->first());

        return WaterlevelDataResource::collection($Data->paginate($perPage))->additional($this->commonJsonReturn('You surface water data json format is successfully'));
    }

    public function rfObservationJson(Request $request)
    {
        $ClientCollection = ClientCollection::whereHas('ClientToken', function ($query) {
            return $query->where('api_client_tokens.token', request()->bearerToken());
        })->active()->where('collection_id', 8)->first();

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

        $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;
        } elseif ($request->has('sms_id')) {
            $RequestData['identifier'] = $request->sms_id;
        }

        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();

        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);
                }
            }

        }

        $Data = FfwcData::query()->where('d_type', 'R');

        if (isset($RequestData['date']) && $RequestData['date']) {
            $Data->whereDate('m_date', $RequestData['date']);
        } else {
            if (isset($RequestData['from_date']) && $RequestData['from_date']) {
                $Data->whereDate('m_date', '>=', $RequestData['from_date']);
            }

            if (isset($RequestData['to_date']) && $RequestData['to_date']) {
                $Data->whereDate('m_date', '<=', $RequestData['to_date']);
            }
        }

        $perPage = 10;

        if (isset($RequestData['per_page']) && $RequestData['per_page'] > 0) {
            $perPage = $RequestData['per_page'];
        }

        if (isset($RequestData['identifier'])) {
            $FFWCStation = FfwcStation::where(DB::raw("LOWER(station_id)"), strtolower($RequestData['identifier']))->first();

            $Data->where(DB::raw("LOWER(station_code)"), strtolower($FFWCStation->ffwc_keyword));
            // $Data->where(DB::raw("LOWER(station_code)"), strtolower($RequestData['identifier']));
            // $Data = $Data->first();

            // if(!$Data) {
            //     return response()->json([
            //         'message' => 'No data found',
            //         'status' => 'errors'
            //     ], 404);
            // }
            // return new RainfallDataResource($Data);
        }

        return RainfallDataResource::collection($Data->paginate($perPage))->additional($this->commonJsonReturn('You surface water data json format is successfully'));
    }

}
