<?php

namespace App\Http\Controllers\Admin;

use App\Room;
use App\City;
use App\Country;
use App\Http\Requests\RoomRequest;
use Exception;
use App\RoomDescription;
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;

class RoomController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/rooms';
    /** View folder */
    private $viewDirectory = 'admin.rooms.';

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('rooms.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',get_defined_vars());
    }

    /**
     * return data of the courses.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Room::join('room_descriptions AS roomDesc', 'rooms.id', 'roomDesc.room_id')
            ->where('roomDesc.language_id', currentLanguage()->id)
            ->select(['rooms.*', 'roomDesc.name']);;

        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 ($request->name) {
            $query->where('roomDesc.name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->type) {
            $query->where('rooms.type', $request->type);
        }



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

        $rooms= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('rooms'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('rooms.store');
        $head = metaFields('rooms', 'add_new', getCurrentLocale()) ?? __('rooms.new');
        $local = getCurrentLocale();
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Store a newly created resource in storage.
     * @param RoomRequest $request
     * @return JsonResponse
     */
    public function store(RoomRequest $request)
    {
        $room = Room::create($request->all());
        $this->saveData( $request, $room->id );
        session()->flash('message', __('dashboard.saveDone'));
        return  response()->json(['url' => route('rooms.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param Room $room
     * @return View
     */
    public function edit(Room $room) :View
    {
        $action= route('rooms.update', $room->id);
        $head = metaFields('rooms', 'edit', getCurrentLocale()) ?? __('rooms.edit');

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

        $roomDescription= $query->get();

        foreach ($roomDescription as $row) {
            $room[$row->local]= $row;
        }

        $local = getCurrentLocale();
        return view( $this->viewDirectory.'form', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     * @param RoomRequest $request
     * @param Room $room
     * @return JsonResponse
     */
    public function update(RoomRequest $request, Room $room)
    {
        $room->update($request->all());
        // Delete old description
        RoomDescription::where('room_id', $room->id)->delete();
        $this->saveData( $request, $room->id );
        session()->flash('message', __('dashboard.saveDone'));
        return  response()->json(['url' => route('rooms.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Handle Save form data
     *
     * @param RoomRequest $request
     * @param int $room_id
     * @return void
     */

    private function saveData(RoomRequest $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],
            ];
            RoomDescription::create($data);
        }

    }


    public function getCity(Request $request)
    {
        if ($request->ajax()){
            $cities = City::withDescription($request->country_id);
            if (count($cities)){
                return response()->json(['cities' => $cities]);
            } else {
                return response()->json(['cities' => false]);
            }
        }
    }

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

    /**
     * Remove several courses by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Room::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Room::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $room = Room::withTrashed()->find($id);

        if ($room){
            $room->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

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