<?php

namespace App\Http\Controllers\Admin;

use App\City;
use App\Hotel;
use App\HotelReservation;
use App\Http\Controllers\Controller;
use App\Http\Requests\MemberRequest;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class HotelReservationController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath = '/admin/hotel_reservations';
    /** View folder */
    private $viewDirectory = 'admin.hotel_reservations.';

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('hotel_reservations.head');
        $request= $request->toArray();
        $hotelAndCities = $this->hotelAnsCities();

        $hotels = $hotelAndCities['hotels'];
        $cities = $hotelAndCities['cities'];

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


    /**
     * return data of the hotel_reservations.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $language_id = currentLanguage()->id;
        $query = HotelReservation::orderBy('hotel_reservations.id', 'DESC')
            ->leftJoin('users', 'users.id', 'hotel_reservations.user_id')
            ->join('cities', 'cities.id', 'hotel_reservations.city_id')
            ->join('city_descriptions as cityDesc', 'cityDesc.city_id', 'cities.id')
            ->where('cityDesc.language_id', $language_id)
            ->join('hotels', 'hotels.id', 'hotel_reservations.hotel_id')
            ->join('hotel_descriptions as hotelDesc', 'hotelDesc.hotel_id', 'hotels.id')
            ->where('hotelDesc.language_id', $language_id)
        ->select(
            [
                'hotel_reservations.*',
                'users.name as user_name',
                'users.email as user_email',
                'users.phone as user_phone',
                'cityDesc.name as city_name',
                'hotelDesc.name as hotel_name',
            ]
        );

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

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

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

        if ($request->hotel_id) {
            $query->where('hotel_reservations.hotel_id',$request->hotel_id);
        }
        if ($request->user_name) {
            $query->where('hotel_reservations.name', 'LIKE', '%'.$request->user_name.'%')
                ->orWhere('users.name', 'LIKE', '%'.$request->user_name.'%');
        }
        if ($request->user_email) {
            $query->where('hotel_reservations.email', 'LIKE', '%'.$request->user_email.'%')
            ->orWhere('users.email', 'LIKE', '%'.$request->user_email.'%');
        }
        if ($request->room_type) {
            $query->where('hotel_reservations.room_type', $request->room_type);
        }
        if ($request->days_count) {
            $query->where('hotel_reservations.days_count', $request->days_count);
        }
        if ($request->person_count) {
            $query->where('hotel_reservations.person_count', $request->person_count);
        }

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

        $hotel_reservations= $query->paginate(1000);

        $roomTypes = [
            1 => __('hotels.individually'),
            2 => __('hotels.couple'),
            3 => __('hotels.tripartite'),
            4 => __('hotels.quadrilateral'),
        ];

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
//    public function create() :View
//    {
//        $action= route('hotel_reservations.store');
//        $head = metaFields('hotel_reservations', 'add_new', getCurrentLocale()) ?? __('hotel_reservations.new');
////        $regions = Region::withDescription();
//        $cities = City::withDescription();
////        $sectors = [];
//        $local = getCurrentLocale();
//
//
//        return view( $this->viewDirectory.'form', compact('action', 'head', 'cities', 'local'));
//    }

    /**
     * Store a newly created resource in storage.
     *
     * @param MemberRequest $request
     * @return JsonResponse
     */
//    public function store(MemberRequest $request) :JsonResponse
//    {
//        $data = $request->all();
//        $data['password'] = bcrypt($request->password);
//        $data['role'] = 'user';
//        HotelReservation::create($data);
//        session()->flash('message', __('dashboard.saveDone'));
//        return response()->json(['url' => route('hotel_reservations.index')]);
////        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
//    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param HotelReservation $hotel_reservation
     * @return View
     */
    public function edit(HotelReservation $hotel_reservation)
    {
        $head = metaFields('hotel_reservations', 'edit', getCurrentLocale()) ?? __('hotel_reservations.edit');
        $local = getCurrentLocale();
        $language_id = currentLanguage()->id;

        $hotelReservation = HotelReservation::where('hotel_reservations.id', $hotel_reservation->id);

        if ($hotel_reservation->user_id){
            $hotelReservation->join('users', 'users.id', 'hotel_reservations.user_id');
        }
            $hotelReservation->join('cities', 'cities.id', 'hotel_reservations.city_id')
            ->join('city_descriptions as cityDesc', 'cityDesc.city_id', 'cities.id')
            ->where('cityDesc.language_id', $language_id)
            ->join('hotels', 'hotels.id', 'hotel_reservations.hotel_id')
            ->join('hotel_descriptions as hotelDesc', 'hotelDesc.hotel_id', 'hotels.id')
            ->where('hotelDesc.language_id', $language_id);

        if ($hotel_reservation->user_id){
            $hotelReservation->select(
                [
                    'hotel_reservations.*',
                    'users.name as user_name',
                    'users.email as user_email',
                    'users.phone as user_phone',
                    'cityDesc.name as city_name',
                    'hotelDesc.name as hotel_name',
                ]
            );
        } else {
            $hotelReservation->select(
                [
                    'hotel_reservations.*',
                    'cityDesc.name as city_name',
                    'hotelDesc.name as hotel_name',
                ]
            );
        }

        $hotelReservation = $hotelReservation->first();

//        $hotelReservation->added_service = array_map(function ($value){
//            return __('hotels.'.$value);
//        }, $hotelReservation->added_service);

//        $hotelReservation->added_service_price = implode(' - ', $hotelReservation->added_service_price);
        $roomTypes = [
            1 => __('hotels.individually'),
            2 => __('hotels.couple'),
            3 => __('hotels.tripartite'),
            4 => __('hotels.quadrilateral'),
        ];

        $hotelReservation->room_type = $roomTypes[$hotelReservation->room_type];

//        dd($hotelReservation->added_service_price);
        return view( $this->viewDirectory.'form', compact('hotelReservation', 'head', 'local') );
    }


    /**
     * Return cities and hotel that have hotel reservations
     * @return array
     */
    private function hotelAnsCities()
    {
        $languageId = currentLanguage()->id;
        $cities = City::whereHas('hotelReservations')
                ->join('city_descriptions as cd', 'cd.city_id', 'cities.id')
                ->where('cd.language_id', $languageId)->select([
                    'cities.*',
                    'cd.name',
                ])->cursor() ?? [];

        $hotels = Hotel::whereHas('reservations')
                ->join('hotel_descriptions as hd', 'hd.hotel_id', 'hotels.id')
                ->where('hd.language_id', $languageId)->select(
                    [
                        'hotels.*',
                        'hd.name',
                        'hd.address',
                    ]
                )->cursor() ?? [];

        return ['cities' => $cities, 'hotels' => $hotels];
    }


    /**
     * Update the specified resource in storage.
     *
     * @param MemberRequest $request
     * @param HotelReservation $hotel_reservations
     * @return JsonResponse
     */
//    public function update(MemberRequest $request, HotelReservation $hotel_reservations) :JsonResponse
//    {
//        $data = $request->all();
//        $data['password'] = $request->password ? bcrypt($request->password) : $hotel_reservations->password;
//        $data['role'] = 'user';
//        $hotel_reservations->update($data);
//        session()->flash('message', __('dashboard.saveDone'));
//        return response()->json(['url' => route('hotel_reservations.index')]);
//
////        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
//    }


//    public function activeMember(HotelReservation $hotel_reservations)
//    {
//        if ($hotel_reservations->status){
//            $hotel_reservations->update(['status' => 0]);
//            return response()->json(['message' => __('hotel_reservations.de_active_success')]);
//        } else {
//            $hotel_reservations->update(['status' => 1]);
//            return response()->json(['message' => __('hotel_reservations.active_success')]);
//        }
//
//    }




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

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            HotelReservation::onlyTrashed()->whereIn('id', $ids)->where('role', '!=', 'admin')->forceDelete();
        } else {
            HotelReservation::whereIn('id', $ids)->where('role', '!=', 'admin')->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
    {
        $hotel_reservations = HotelReservation::withTrashed()->find($id);

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

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