<?php
namespace Modules\Hotel\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\AdminController;
use Modules\Core\Models\Attributes;
use Modules\Hotel\Models\HotelRoom;
use Modules\Hotel\Models\HotelRoomTerm;
use Modules\Hotel\Models\HotelRoomTranslation;
use Modules\Location\Models\Location;
use Modules\Hotel\Models\Hotel;
use Modules\Hotel\Models\HotelTerm;
use Modules\Hotel\Models\HotelTranslation;

class RoomController extends AdminController
{
    protected $hotelClass;
    protected $roomTermClass;
    protected $attributesClass;
    protected $locationClass;
    /**
     * @var HotelRoom
     */
    protected $roomClass;
    protected $currentHotel;
    protected $roomTranslationClass;

    public function __construct()
    {
        $this->setActiveMenu(route('hotel.admin.index'));
        $this->hotelClass = Hotel::class;
        $this->roomTermClass = HotelRoomTerm::class;
        $this->attributesClass = Attributes::class;
        $this->locationClass = Location::class;
        $this->roomClass = HotelRoom::class;
        $this->roomTranslationClass = HotelRoomTranslation::class;
    }
    public function callAction($method, $parameters)
    {
        if(!Hotel::isEnable())
        {
            return redirect('/');
        }
        return parent::callAction($method, $parameters); // TODO: Change the autogenerated stub
    }

    protected function hasHotelPermission($hotel_id = false){
        if(empty($hotel_id)) return false;

        $hotel = $this->hotelClass::find($hotel_id);
        if(empty($hotel)) return false;

        if(!$this->hasPermission('hotel_manage_others') and $hotel->author_id != Auth::id()){
            return false;
        }

        $this->currentHotel = $hotel;
        return true;
    }
    public function index(Request $request,$hotel_id)
    {
        $this->checkPermission('hotel_view');

        if(!$this->hasHotelPermission($hotel_id))
        {
            abort(403);
        }

        $query = $this->roomClass::query() ;

        $query->orderBy('id', 'desc');
        if (!empty($hotel_name = $request->input('s'))) {
            $query->where('title', 'LIKE', '%' . $hotel_name . '%');
            $query->orderBy('title', 'asc');
        }

        $query->where('parent_id',$hotel_id);
        $data = [
            'rows'               => $query->with(['author'])->paginate(20),
            'hotel_manage_others' => $this->hasPermission('hotel_manage_others'),
            'breadcrumbs'        => [
                [
                    'name' => __('Hotels'),
                    'url'  => route('hotel.admin.index')
                ],
                [
                    'name' => __('Hotel: :name',['name'=>$this->currentHotel->title]),
                    'url'  => route('hotel.admin.edit',['id'=>$this->currentHotel->id])
                ],
                [
                    'name'  => __('Room Management'),
                    'class' => 'active'
                ],
            ],
            'page_title'=>__("Room Management"),
            'hotel'=>$this->currentHotel,
            'row'=> new $this->roomClass(),
            'translation'=>new $this->roomTranslationClass(),
            'attributes'     => $this->attributesClass::where('service', 'hotel_room')->get(),
        ];
        return view('Hotel::admin.room.index', $data);
    }

    public function edit(Request $request, $hotel_id,$id)
    {
        $this->checkPermission('hotel_update');

        if(!$this->hasHotelPermission($hotel_id))
        {
            abort(403);
        }

        $row = $this->roomClass::find($id);
        if (empty($row) or $row->parent_id != $hotel_id) {
            return redirect(route('hotel.admin.room.index',['hotel_id'=>$hotel_id]));
        }

        $translation = $row->translate($request->query('lang',get_main_lang()));
        if (!$this->hasPermission('hotel_manage_others')) {
            if ($row->author_id != Auth::id()) {
                return redirect(route('hotel.admin.room.index'));
            }
        }
        $data = [
            'row'            => $row,
            'translation'    => $translation,
            "selected_terms" => $row->terms->pluck('term_id'),
            'attributes'     => $this->attributesClass::where('service', 'hotel_room')->get(),
            'enable_multi_lang'=>true,
            'breadcrumbs'    => [
                [
                    'name' => __('Hotels'),
                    'url'  => route('hotel.admin.index')
                ],
                [
                    'name' => __('Hotel: :name',['name'=>$this->currentHotel->title]),
                    'url'  => route('hotel.admin.edit',['id'=>$this->currentHotel->id])
                ],
                [
                    'name' => __('All Rooms'),
                    'url'  => route('hotel.admin.room.index',['hotel_id'=>$this->currentHotel->id])
                ],
                [
                    'name' => __('Edit room: :name',['name'=>$row->title]),
                ],
            ],
            'page_title'=>__("Edit: :name",['name'=>$row->title]),
            'hotel'=>$this->currentHotel
        ];
        return view('Hotel::admin.room.detail', $data);
    }

    public function store( Request $request, $hotel_id,$id ){

        if(is_demo_mode()){
            return redirect()->back()->with('danger',__("DEMO MODE: can not add data"));
        }
        if(!$this->hasHotelPermission($hotel_id))
        {
            abort(403);
        }
        if($id>0){
            $this->checkPermission('hotel_update');
            $row = $this->roomClass::find($id);
            if (empty($row)) {
                return redirect(route('hotel.admin.index'));
            }

            if($row->author_id != Auth::id() and !$this->hasPermission('hotel_manage_others'))
            {
                return redirect(route('hotel.admin.room.index'));
            }

            if($row->parent_id != $hotel_id)
            {
                return redirect(route('hotel.admin.room.index'));
            }
        }else{
            $this->checkPermission('hotel_create');
            $row = new $this->roomClass();
            $row->status = "publish";
        }
        $dataKeys = [
            'title',
            'content',
            'image_id',
            'gallery',
            'price',
            'number',
            'beds',
            'size',
            'adults',
            'children',
            'status',
            'min_day_stays',
        ];

        $row->fillByAttr($dataKeys,$request->input());
	    $row->ical_import_url  = $request->ical_import_url;

        if($id<0){
            $row->parent_id = $hotel_id;
        }

        $res = $row->saveOriginOrTranslation($request->input('lang'),true);

        if ($res) {
            if(!$request->input('lang') or is_default_lang($request->input('lang'))) {
                $this->saveTerms($row, $request);
            }

            if($id > 0 ){
                return redirect()->back()->with('success',  __('Room updated') );
            }else{
                return redirect()->back()->with('success',  __('Room created') );
            }
        }
    }

    public function saveTerms($row, $request)
    {
        $this->checkPermission('hotel_manage_attributes');
        if (empty($request->input('terms'))) {
            $this->roomTermClass::where('target_id', $row->id)->delete();
        } else {
            $term_ids = $request->input('terms');
            foreach ($term_ids as $term_id) {
                $this->roomTermClass::firstOrCreate([
                    'term_id' => $term_id,
                    'target_id' => $row->id
                ]);
            }
            $this->roomTermClass::where('target_id', $row->id)->whereNotIn('term_id', $term_ids)->delete();
        }
    }

    public function bulkEdit(Request $request)
    {
        $ids = $request->input('ids');
        $action = $request->input('action');
        if (empty($ids) or !is_array($ids)) {
            return redirect()->back()->with('error', __('No items selected!'));
        }
        if (empty($action)) {
            return redirect()->back()->with('error', __('Please select an action!'));
        }
        switch ($action){
            case "delete":
                foreach ($ids as $id) {
                    $query = $this->roomClass::where("id", $id);
                    if (!$this->hasPermission('hotel_manage_others')) {
                        $query->where("create_user", Auth::id());
                        $this->checkPermission('hotel_delete');
                    }
                    $query->first();
                    if(!empty($query)){
                        $query->delete();
                    }
                }
                return redirect()->back()->with('success', __('Deleted success!'));
                break;
            case "clone":
                $this->checkPermission('hotel_create');
                foreach ($ids as $id) {
                    (new $this->roomClass())->saveCloneByID($id);
                }
                return redirect()->back()->with('success', __('Clone success!'));
                break;
            default:
                // Change status
                foreach ($ids as $id) {
                    $query = $this->roomClass::where("id", $id);
                    if (!$this->hasPermission('hotel_manage_others')) {
                        $query->where("create_user", Auth::id());
                        $this->checkPermission('hotel_update');
                    }
                    $query->update(['status' => $action]);
                }
                return redirect()->back()->with('success', __('Update success!'));
                break;
        }
    }
}
