<?php

namespace Modules\Linksehat\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\Organization;
use App\Models\PractitionerRole;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Modules\Linksehat\Transformers\Article\ArticleResource;
use Modules\Linksehat\Transformers\Doctor\DoctorResource;
use Modules\Linksehat\Transformers\Hospital\HospitalResource;

class DashboardController extends Controller
{
    public function index(Request $request, $query, $limit = 20)
    {
        if ($query === 'doctors') {
            $queryDoctors = PractitionerRole::query()
                ->with([
                    'person' => function ($query) {
                        $query->select(['name']);
                    },
                    'speciality' => function ($query) {
                        $query->select(['id', 'name']);
                    },
                ])
                ->where('active', 1)
                ->whereNot('speciality_id')
                ->get(['id', 'practitioner_id', 'speciality_id'])
                ->random($limit);

            $data = ['doctors' => DoctorResource::collection($queryDoctors)];
        } elseif ($query === 'hospitals') {
            $queryHospitals = Organization::query()
                ->leftJoin('addresses', function ($query) {
                    $query->on('organizations.main_address_id', '=', 'addresses.id');
                })
                ->leftJoin('cities', function ($query) {
                    $query->on('addresses.city_id', '=', 'cities.id');
                })
                ->where('addresses.addressable_type', '=', Organization::class)
                ->active()
                ->hospital()
                ->when($request->lat && $request->lng, function ($query) use ($request) {
                    $query->selectRaw("organizations.*, addresses.text AS address, addresses.lat, addresses.lng, cities.name AS city_name, 6371 * acos (cos ( radians($request->lat) ) * cos( radians( addresses.lat ) ) * cos( radians( addresses.lng ) - radians($request->lng) ) + sin ( radians($request->lat) ) * sin( radians( addresses.lat ) )) as distance");
                    $query->orderBy('distance', 'ASC');
                }, function ($query) {
                    $query->select(['organizations.*', 'addresses.text AS address', 'addresses.lat', 'addresses.lng', 'cities.name AS city_name']);
                    $query->orderBy('organizations.name', 'asc');
                })
                ->limit($limit)
                ->get();

            $data = ['hospitals' => HospitalResource::collection($queryHospitals)];
        } elseif ($query === 'articles') {
            $data = ['articles' => ArticleResource::collection(json_decode(Http::get('https://linksehat.com/api/medical-assistance-articles')))];
        }

        return Helper::responseJson($data);
    }
}
