<?php

namespace App\Http\Controllers\Admin;

/** Ajax Request */

use App\City;
use App\Hotel;
use App\Region;
use App\Room;
use App\User;
use Exception;
use Illuminate\View\View;
use App\HotelDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\HotelRequest; // for Validation

class HotelController extends Controller
{

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

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

    /**
     * return data of the hotels.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = Hotel::latest()
            ->join('hotel_descriptions AS hd', 'hotels.id', 'hd.hotel_id')
            ->where('hd.language_id', $language_id)
            ->join('cities', 'cities.id', 'hotels.city_id')
            ->join('city_descriptions as cityDesc', 'cityDesc.city_id', 'cities.id')
            ->where('cityDesc.language_id', $language_id)
            ->select(['hd.name', 'cityDesc.name as city_name',  'hotels.*']);

        if ($request->date_from) {
            $query->whereDate('hotels.created_at', '>=', $request->date_from);
        }

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

        if ($request->name) {
            $query->where('hd.name', 'LIKE', '%'.$request->name.'%');
        }
        if ($request->email) {
            $query->where('hotels.email', 'LIKE', '%'.$request->email.'%');
        }

        if ($request->show_in_hotel_home == 'yes') {
            $query->where('hotels.show_in_hotel_home', 1);
        }
        if($request->show_in_hotel_home == 'no') {
            $query->where('hotels.show_in_hotel_home', 0);
        }
        if ($request->city_id) {
            $query->where('cities.id', 'LIKE', $request->city_id);
        }

        if ($request->city_id) {
            $query->where('cities.id', 'LIKE', $request->city_id);
        }


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

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

    /**
     * Show the form for creating a new service.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('hotels.store');
        $head = metaFields('hotels', 'add_new', getCurrentLocale()) ?? __('hotels.new');
        $cities = City::withDescription();
        $local = getCurrentLocale();
//        $added_service = $this->addedServiceAndRoomType()['added_service'];
//        $room_type = $this->addedServiceAndRoomType()['room_type'];
        $rooms = Room::withDescription();
        return view( $this->viewDirectory.'form', get_defined_vars() );
    }

    /**
     * Store a newly created service in storage.
     * @param HotelRequest $request
     * @return JsonResponse
     */
    public function store(HotelRequest $request) :JsonResponse
    {
        $data = $request->all();
//        $data['added_service_price'] = array_values($data['added_service_price']);
        $roomTypePrices = array_filter($data['room_type_price']);
        $thursdayPrices = array_filter($data['room_type_thursday_price']);
        $fridayPrices = array_filter($data['room_type_friday_price']);
        $data['first_room_type_price'] = array_first(array_filter($data['room_type_price']));
        $data['include_breakfast'] = $request->include_breakfast ?? 0;
        $data['room_type'] = Room::whereIn('id', $request->room_type)->pluck('type')->toArray();
        $data['room_id'] = Room::whereIn('id', $request->room_type)->pluck('id')->toArray();
        $data['room_type_price'] = [];

        foreach ($roomTypePrices as $roomId => $price) {
            $data['room_type_price'][$roomId] = [$price, $thursdayPrices[$roomId], $fridayPrices[$roomId]];
        }
        $hotel = Hotel::create($data);
        $this->saveData( $request, $hotel->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('hotels.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

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

        $query = HotelDescription::where('hotel_id', $hotel->id)
            ->join('languages', 'languages.id', 'hotel_descriptions.language_id')
            ->select(['hotel_descriptions.*', 'languages.local']);

        $hotelDescription= $query->get();
        foreach ($hotelDescription as $row) {
            $hotel[$row->local]= $row;
        }
        $cities = City::withDescription();
        $local = getCurrentLocale();

//        $added_service = $this->addedServiceAndRoomType()['added_service'];
//        $room_type = $this->addedServiceAndRoomType()['room_type'];
        $rooms = Room::withDescription();

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


    public function activeHall(Hotel $hotel)
    {
        if ($hotel->status){
            $hotel->update(['status' => 0]);
            return response()->json(['message' => __('hotels.de_active_success')]);
        } else {
            $hotel->update(['status' => 1]);
            return response()->json(['message' => __('hotels.active_success')]);
        }

    }

    /**
     * Update the specified service in storage.
     * @param HotelRequest $request
     * @param Hotel $hotel
     * @return JsonResponse
     */
    public function update(HotelRequest $request, Hotel $hotel) :JsonResponse
    {
        $data = $request->all();
//        $data['added_service_price'] = array_values($data['added_service_price']);
        $roomTypePrices = array_filter($data['room_type_price']);
        $thursdayPrices = array_filter($data['room_type_thursday_price']);
        $fridayPrices = array_filter($data['room_type_friday_price']);
        $data['first_room_type_price'] = array_first(array_filter($data['room_type_price']));
        $data['include_breakfast'] = $request->include_breakfast ?? 0;
        $data['room_type'] = Room::whereIn('id', $request->room_type)->pluck('type')->toArray(); // room_type = room_id
        $data['room_id'] = Room::whereIn('id', $request->room_type)->pluck('id')->toArray(); // room_type = room_id
        $data['room_type_price'] = [];

        foreach ($roomTypePrices as $roomId => $price) {
            $data['room_type_price'][$roomId] = [$price, $thursdayPrices[$roomId], $fridayPrices[$roomId]];
        }
        $hotel->update($data);
        HotelDescription::where('hotel_id', $hotel->id)->delete();
        $this->saveData( $request, $hotel->id );
        session()->flash('message', __('dashboard.saveDone'));
        return response()->json(['url' => route('hotels.index')]);
//        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param HotelRequest $request
     * @param int $hotel_id
     * @return void
     */

    private function saveData(HotelRequest $request, int $hotel_id ) :void
    {

        $requestData= $request->all();

        foreach (languages() as $lang) {
            $data=[
                'hotel_id'=> $hotel_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
            ];

            HotelDescription::create($data);
        }

    }

    private function addedServiceAndRoomType()
    {
        $added_service = [
            'breakfast' => __('hotels.breakfast'),
            'half_residence' => __('hotels.half_residence'),
            'full_residence' => __('hotels.full_residence'),
        ];
        $room_type = [
            1 => __('hotels.individually'),
            2 => __('hotels.couple'),
            3 => __('hotels.tripartite'),
            4 => __('hotels.quadrilateral'),
        ];

        return ['added_service' => $added_service, 'room_type' => $room_type];
    }

    public function getCities(Request $request)
    {
        if ($request->ajax()){
            $cities = City::withDescription($request->region_id);
            return ['cities' => $cities];
        }
    }

    public function getCityAndSector(Request $request)
    {
        if ($request->ajax()){
            $data = [];
            $status = false; // to specify which request returned city or sectors
            if ($request->region_id){
                $status = 'city';
                $data = City::withDescription($request->region_id);
            }
            if ($request->city_id){
                $status = 'sector';
                $data = Sector::withDescription($request->city_id);
            }

            return ['data' => $data, 'status' => $status];
        }
    }

    /**
     * Remove the specified service from storage.
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $hotel= Hotel::withTrashed()->find($id);
        if ($hotel) {
//            $hotelHasReservations = Reservation::where('hotel_id', $id)
//                ->whereIn('re_status', ['confirmed', 'unconfirmed', 'waiting_for_pay'])->count();
//            if ($hotelHasReservations){
//                return response()->json(['message'=> __('hotels.cant_delete_hotel_has_reservation')]);
//            }

            if ($hotel->deleted_at) {
                $hotel->forceDelete();
            } else {
                $hotel->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several hotels by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;

        if ($request->force) {
            Hotel::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Hotel::whereIn('id', $ids)->delete();
        }

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

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

    }

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