<?php

namespace Modules\Linksehat\Http\Controllers\Api;

use App\Helpers\Helper;
use App\Models\Organization;
use App\Models\Speciality;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\Linksehat\Transformers\Hospital\HospitalResource;

class HospitalController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $hospitals = Organization::query()
            ->with(['currentAddress'])
            ->where('organizations.type', 'hospital')
            ->when($request->search ?? null, function ($query, $search) {
                $query->where('name', 'LIKE', '%' . $search . '%');
            });
        if ($request->has('lat') && !empty($request->lat) && $request->has('lng') && !empty($request->lng)) {
            $hospitals->leftJoin('addresses', function ($q) {
                $q->on('organizations.main_address_id', '=', 'addresses.id');
                $q->where('addresses.addressable_type', '=', Organization::class);
            });
            $hospitals->select([
                "organizations.*",
                DB::raw("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_km")
            ]);

            $hospitals->orderBy('distance_km', 'asc');
        } else {
            $hospitals->orderBy('organizations.name', 'asc');
        }

        if ($request->has('order_by')) {
            switch ($request->order_by) {
                case 'distance_asc':
                    if ($request->order_by == 'distance_asc' && $request->has('lat') && !empty($request->lat) && $request->has('lng') && !empty($request->lng)) {
                        $hospitals->orderBy('distance_km', 'asc');
                        break;
                    }
                case 'distance_desc':
                    if ($request->order_by == 'distance_desc' && $request->has('lat') && !empty($request->lat) && $request->has('lng') && !empty($request->lng)) {
                        $hospitals->orderBy('distance_km', 'desc');
                        break;
                    }
                default:
                    $hospitals->orderBy('organizations.name', 'asc');
                    break;
            }
        }

        $limit = $request->limit ?? 6;
        if ($limit > 20) {
            $limit = 20;
        }

        $hospitals = $hospitals->paginate($limit);

        return Helper::responseJson([
            'hospitals' => Helper::paginateResources(HospitalResource::collection($hospitals))
        ], 200, 'Sukses mengambil data Rumah Sakit');
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('linksehat::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show(Request $request, $id)
    {
        $queryHospitals = Organization::query()
            ->with(['practitionerRoles' => function ($query) {
                $query->select(['organization_id', 'speciality_id'])
                    ->whereNot('speciality_id')
                    ->groupBy(['organization_id', 'speciality_id'])
                    ->orderBy('speciality_id');
            }])
            ->when($request->lat && $request->lng, function (Builder $query) use ($request) {
                $query->getQuery()
                    ->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");
            }, function (Builder $query) {
                $query->getQuery()
                    ->select(['organizations.*', 'addresses.text AS address', 'addresses.lat', 'addresses.lng', 'cities.name AS city_name']);
            })
            ->leftJoin('addresses', function ($query) {
                $query->on('organizations.main_address_id', '=', 'addresses.id');
            })
            ->leftJoin('cities', function ($query) {
                $query->on('addresses.city_id', '=', 'cities.id');
            })
            ->where('organizations.id', $id)
            ->where('addresses.addressable_type', '=', Organization::class)
            ->findOrFail($id);

        foreach ($queryHospitals->practitionerRoles as  $practitionerRole) {
            $specialitiesId[] = $practitionerRole->speciality_id;
        }

        $queryHospitals['specialities'] = Speciality::query()
            ->whereIn('id', $specialitiesId)
            ->get();

        return Helper::responseJson(new HospitalResource($queryHospitals));
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        return view('linksehat::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        //
    }
}
