<?php

namespace App\Http\Controllers\Admin;

use App\Category;
use Exception;
use App\Hotel;
use App\HotelPhoto;
use Illuminate\View\View;
use App\HotelDescription;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\HotelRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

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 resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('hotels.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the pages.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = Hotel::latest()
            ->join('hotel_descriptions AS ad', 'hotels.id', 'ad.hotel_id')
            ->join('languages', 'languages.id', 'ad.language_id')
            ->where('local', LaravelLocalization::getCurrentLocale())
            ->select(['ad.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('ad.name', 'LIKE', '%'.$request->name.'%');
        }

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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('hotels.store');
        $head= metaFields('hotels', 'new', getCurrentLocale()) ?? __('hotels.new');
        $hotels = Hotel::withDescription(false, true);
        $categories = Category::withDescription();

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

    /**
     * Store a newly created resource in storage.
     *
     * @param HotelRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(HotelRequest $request) :RedirectResponse
    {
        $data = $request->all();
        if (!$data['category_id']){
            $data['category_id'] = Hotel::find($data['hotel_id'])->category_id;
        }
        $hotel = Hotel::create($data);

        // Insert Description
        $this->saveData($request, $hotel->id);

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @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;
        }

        $hotels = Hotel::withDescription(false, true);
        $categories = Category::withDescription();

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

    /**
     * Update the specified resource in storage.
     *
     * @param HotelRequest $request
     * @param Hotel $hotel
     * @return RedirectResponse|Redirector
     */
    public function update(HotelRequest $request, Hotel $hotel) :RedirectResponse
    {

        $data = $request->all();
        if (!$data['category_id']){
            $data['category_id'] = $hotel->hotel->category_id;
        }

        $hotel->update($data);

        // Delete old description
        HotelDescription::where('hotel_id', $hotel->id)->delete();

        // delete old photos
        HotelPhoto::where('hotel_id', $hotel->id)->delete();

        // Insert new description
        $this->saveData( $request, $hotel->id );

        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],
                'slug'=> $requestData['slug_'.$lang->local],
                'meta_description'=> $requestData['meta_description_'.$lang->local],
                'description'=> $requestData['description_'.$lang->local],
                'keywords'=> $requestData['keywords_'.$lang->local],
                'more_info'=> $requestData['more_info_'.$lang->local],
                'facilities'=> $requestData['facilities_'.$lang->local],
            ];
            HotelDescription::create($data);
        }

        if ($request->has('images')){

            foreach ($request->images as $image) {
                $data=[
                    'image'=> $image,
                    'hotel_id'=> $hotel_id,
                ];

                HotelPhoto::create($data);

            }
        }

    }


    /**
     * 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 = Hotel::withTrashed()->find($id);
        if ($hotel) {
            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 pages 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 category 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 pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $hotel = Hotel::whereIn('id', $request->ids)->onlyTrashed();
        if ($hotel){
            $hotel->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
