<?php

namespace App\Services\Repositories;

use App\Models\Room;
use App\Models\RoomDescription;
use App\Services\Interfaces\RoomRepositoryInterface;
use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class RoomRepository implements RoomRepositoryInterface
{
    public function get(Request $request)
    {
        $query = Room::query()
            ->join('room_descriptions AS pd', 'rooms.id', 'pd.room_id')
            ->join('languages', 'languages.id', 'pd.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['pd.name', 'rooms.*']);

        if ($request->name) {
            $query->where('pd.name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->count) {
            $query->where('min_count','<=',$request->count)->where('max_count','>=',$request->count);
        }
        if ($request->date_from) {
            $query->whereDate('rooms.created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('rooms.created_at', '<=', $request->date_to);
        }


        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }


        if ($request->orderBy) 
        {
            $query->orderBy('rooms.id', $request->orderBy);
        }
        else
        {
            $query->orderBy('rooms.id','DESC');
        }


        if ($request->paginate ?? null) {
            $pagination = $request->pagination ? $request->pagination : 50;
            $clients= $query->paginate($pagination);
        }else{
            $clients=$query->cursor();
        }

        return $clients;
    }

    public function getItem(Room $room)
    {
        $query = RoomDescription::where('room_id', $room->id)
            ->join('languages', 'languages.id', 'room_descriptions.language_id')
            ->select(['room_descriptions.*', 'languages.local']);

        $roomDescription= $query->get();
        // dd($roomDescription->toArray());
        foreach ($roomDescription as $row) {
            $room[$row->local]= $row;
        }
        $room['name'] = $room[getCurrentLocale()]['name'];
        $room['description'] = $room[getCurrentLocale()]['description'];
        return $room ;
    }

    //
    public function save(Request $request, ?Room $room): Room
    {
        $data= $request->all();
        unset($data['id']);// for security reasons
        if (!$room) {
            $room = Room::create($data);
        } else {
            $room->update($data);
            RoomDescription::where('room_id', $room->id)->delete();
        }
        $this->saveData( $request, $room->id );
        return $room;
    }

    private function saveData(Request $request, int $room_id ) :void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'room_id'=> $room_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local] ?? null,
            ];

            RoomDescription::create($data);
        }
    }
    /**
     * Remove the specified client from storage.
     * @param Request $request
     * @param int $id
     * @return array
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :array
    {
        $client= Room::withTrashed()->find($id);
        if ($client) {
            if ($client->deleted_at) {
                $client->forceDelete();
            } else {
                $client->delete();
            }
            return [ ['message'=> __('dashboard.deletedDone')]];
        } else{
            return [ ['message'=> __('dashboard.noResult')], 400];
        }
    }

    /**
     * Remove several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function destroyAll(Request $request) :array
    {
        $ids= $request->ids;
        $query= Room::whereIn('id', $ids);
        if ($request->force) {
            $deleted= $query->onlyTrashed()->forceDelete();
        } else {
            $deleted= $query->delete();
        }
        if($deleted){
            return [['message'=> __('dashboard.deletedDone')]];
        }
        return [ ['message'=> __('dashboard.noResult')], 400];
    }

    /**
     * Restore the specified client from storage.
     *
     * @param Request $request
     * @param int $id
     * @return array
     */
    public function restore(Request $request, int $id) :array
    {
        $client= Room::withTrashed()->find($id);
        if ($client) {
            $client->restore();
            return [['message'=> __('dashboard.saveDone')]];
        }
        return [['message'=> __('dashboard.noResult')], 400];

    }

    /**
     * Restore several clients by IDs.
     *
     * @param Request $request
     * @return array
     */
    public function restoreAll(Request $request) :array
    {
        $ids= $request->ids;
        Room::whereIn('id', $ids)->onlyTrashed()->restore();
        return [['message'=> __('dashboard.saveDone')]];
    }
}
