<?php

namespace App\Http\Controllers\Api\ProductServices;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Hotel;
use Auth;
use App\Models\Room;
use App\Models\RoomPrice;

class HotelController extends Controller
{
    public function hotelCreateUpdate(Request $request){

        $validator=validator($request->all(),[
            'hotel_type'=>'required',
            'hotel_name'=>'required'
        ]);

        //Inout 1 = payment rec , 2= payment made

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            $obj['hotel_type']=$request['hotel_type'];
            $obj['hotel_logo']=$request['hotel_logo']??null;
            $obj['hotel_name']=$request['hotel_name'];
            $obj['email']=$request['email'];
            $obj['mobile_no']=$request['mobile_no'];
            $obj['address_line_1']=$request['address_line_1'];
            $obj['address_line_2']=$request['address_line_2'];
            $obj['city_id']=$request['city_id']??0;
            $obj['state_id']=$request['state_id']??0;
            $obj['country_id']=$request['country_id']??0;
            $obj['pincode']=$request['pincode']??0;
            $obj['status']=$request['status']??0;
            $obj['ratings']=$request['ratings']??0;
            $obj['description']=$request['description'];
            $obj['upload_documents']=$request['upload_documents'];
            $obj['meta_description']=$request['meta_description'];
            $obj['no_of_nights']=$request['no_of_nights']??1;
            $obj['inclusion']=$request['inclusion'];
            $obj['exclusion']=$request['exclusion'];
            $obj['terms_and_conditions']=$request['terms_and_conditions'];
            $obj['website_url']=$request['website_url'];
                
            if($request['id']>0){
                
                try {
                    
                    $hotel=Hotel::findOrFail($request['id']);

                    $hotel->update($obj);
                
                } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                    // Return error message in JSON if ID not found
                    return response()->json(['message' => 'Invalid Id to update '], 404);
                }

            }else{
                $hotel=Hotel::create($obj);
            }

            $response=[
                'success'=>true,
                'data'=>$hotel,
                'message'=>$request['id']>0?'Hotel Updated Successfully':"Hotel Added Successfully",
            ];
    
            return response()->json($response);

        }   
    }

    //List of Hotels
    public function getHotels(Request $request){

        $user=Auth::user();

        $hotels = Hotel::where('is_disabled', 0)
            ->with('city:id,name','state:id,name','country:id,name');

        if($request['hotel_type']!=null && $request['hotel_type']!=0 && isset($request['hotel_type'])){
            $hotels=$hotels->where('hotel_type',$request['hotel_type']);
        }

        if($request['ratings']!=null && $request['ratings']!=0 && isset($request['ratings'])){
            $hotels=$hotels->where('ratings',$request['ratings']);
        }

        if($request['status']!=null && $request['status']!=0 && isset($request['status'])){
            $hotels=$hotels->where('status',$request['status']);
        }
        
        if ($request['search'] != null && $request['search'] != '') {

            $searchTerm = $request['search'];
            $hotels = $hotels->where(function ($query) use ($searchTerm) {
                $query->where('hotel_type', 'LIKE', '%' . $searchTerm . '%')
                    ->orWhere('hotel_name', 'LIKE', '%' . $searchTerm . '%')
                    ->orWhere('address_line_1', 'LIKE', '%' . $searchTerm . '%')
                    ->orWhere('pincode', 'LIKE', '%' . $searchTerm . '%')
                    ->orWhere('description', 'LIKE', '%' . $searchTerm . '%');
            });
        }
    
        $count=$hotels->count();

        if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
            $sort_order=$request['sort_order']==1?'asc':'desc';

            $hotels = $hotels->orderby($request['sort_by'],$sort_order);

        }else{
            $hotels = $hotels->orderby('id','desc');
        }
        
        $hotels=$hotels->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??50)
                // ->orderBy('id','desc')
                ->get();

        $response=[
            'success'=>true,
            'total_hotels'=>$count,
            'hotels'=>$hotels,
            'message'=>'All Hotels Listed Successfully'
        ];
        
        return response()->json($response);

    }             

    // Details Hotels
    public function hotelDetails(Request $request){

        $validator=validator($request->all(),[
            'hotel_id'=>'required'
        ]);

        //Inout 1 = payment rec , 2= payment made

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            $hotel=Hotel::with('city:id,name','state:id,name','country:id,name')
                ->findOrFail($request['hotel_id']);

            $response=[
                'success'=>true,
                'hotels'=>$hotel,
                'message'=>'Hotels Details Fetched Successfully'
            ];
            
            return response()->json($response);

        }
    }

    // change hotel status active or inactiv
    public function changeHotelStatus(Request $request){
        
        $validator=validator($request->all(),[
            'hotel_id'=>'required',
            'status'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            try {
                    
                $hotel=Hotel::findOrFail($request['hotel_id']);
                $hotel['status']=$request['status'];

                $hotel->update();
            
            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['success'=>false,'message' => 'Invalid Id to update '], 404);
            }

            $response=[
                'success'=>true,
                'data'=>$hotel,
                'message'=>'Hotel Status Updated Successfully',
            ];
    
            return response()->json($response);
        }
    }
    

    // Add rooms in a hotels
    public function roomCreateUpdate(Request $request){

        $validator=validator($request->all(),[
            'hotel_id'=>'required',
            // 'room_type'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            $obj['hotel_id']=$request['hotel_id'];
            $obj['room_type']=$request['room_type'];   //Single , Double
            $obj['room_number']=$request['room_number']??null;
            $obj['currency']=$request['currency'];
            $obj['price']=$request['price']??0;
            $obj['bed_id']=$request['bed_id']??0;
            $obj['bed_name']=$request['bed_name'];
            $obj['meal_id']=$request['meal_id']??0;
            $obj['meal_name']=$request['meal_name'];
            $obj['occupancy_id']=$request['occupancy_id']??0;   
            $obj['occupancy_name']=$request['occupancy_name'];   
            $obj['max_occupancy']=$request['max_occupancy']??2;   //Maximum number of guests the room can accommodate
            $obj['amenities']=$request['amenities'];
            $obj['availability_status']=$request['availability_status']??0;
            $obj['description']=$request['description'];
            $obj['upload_documents']=$request['upload_documents'];

            if($request['id']>0){
                
                try {
                    
                    $room=Room::findOrFail($request['id']);

                    $room->update($obj);
                
                } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                    // Return error message in JSON if ID not found
                    return response()->json(['message' => 'Invalid Id to update '], 404);
                }

            }else{
                $room=Room::create($obj);
            }

            $response=[
                'success'=>true,
                'data'=>$room,
                'message'=>$request['id']>0?'Hotel Room Updated Successfully':"Hotel Room Added Successfully",
            ];
    
            return response()->json($response);
        
        }
    }
    
    // create room prices according to dates
    public function roomPriceCreateUpdate(Request $request){

        $validator=validator($request->all(),[
            'hotel_id'=>'required',
            'room_id'=>'required',
            'start_date'=>'required',
            'end_date'=>'required',
            'price'=>'required',
            // 'currency'=>'required',
        ]);
        
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];
        } else {

            $obj['hotel_id']=$request['hotel_id'];
            $obj['room_id']=$request['room_id'];
            $obj['start_date']=$request['start_date'];
            $obj['end_date']=$request['end_date'];
            $obj['price']=$request['price'];
            $obj['currency']=$request['currency'];
            $obj['status']=$request['status']??0;  
            $obj['description']=$request['description'];

            if($request['id']>0){

                try {

                    $roomPrice=RoomPrice::findOrFail($request['id']);
                    $roomPrice->update($obj);

                }
                catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                    // Return error message in JSON if ID not found
                    return response()->json(['message' => 'Invalid Id to update '], 404);
                }
            }
            else{
                $roomPrice=RoomPrice::create($obj);
            }
            $response=[
                'success'=>true,
                'data'=>$roomPrice,
                'message'=>$request['id']>0?'Hotel Room Price Updated Successfully':"Hotel Room Price Added Successfully",
            ];

            return response()->json($response);
        }
    }

    //get price list room_id  wise
    public function getRoomPriceList(Request $request){
        $user=Auth::user();
        $validator=validator($request->all(),[
            'room_id'=>'required',
        ]);
        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];
        } else {
            $roomPriceList = RoomPrice::where('room_id', $request['room_id'])
                ->where('status',0)->get();
            $response=[
                'success'=>true,
                'data'=>$roomPriceList,
                'message'=>"Room Price List",
            ];
            return response()->json($response);
        }
    }

    //Hotels Room List
    public function getRoomList(Request $request){
        $user=Auth::user();

        $validator=validator($request->all(),[
            'hotel_id'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            $rooms = Room::where('hotel_id', $request['hotel_id']);

            if(isset($request['availability_status'])){
                $rooms=$rooms->where('availability_status',$request['availability_status']);
            }

            if ($request['search'] != null && $request['search'] != '') {

                $searchTerm = $request['search'];
                $rooms = $rooms->where(function ($query) use ($searchTerm) {
                    $query->where('room_number', 'LIKE', '%' . $searchTerm . '%')
                        ->orWhere('price', 'LIKE', '%' . $searchTerm . '%')
                        ->orWhere('bed_name', 'LIKE', '%' . $searchTerm . '%')
                        ->orWhere('occupancy_name', 'LIKE', '%' . $searchTerm . '%')
                        ->orWhere('meal_name', 'LIKE', '%' . $searchTerm . '%');
                });
            }

            $count=$rooms->count();

            $rooms=$rooms->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??50)
                ->orderBy('id','desc')
                ->get();

            $response=[
                'success'=>true,
                'count'=>$count,
                'message'=>'All Hotel Rooms Listed Successfully',
                'hotels'=>$rooms
            ];
        
            return response()->json($response);
        }
    }

    // Room Details
    public function getRoomDetails(Request $request){
        $user=Auth::user();

        $validator=validator($request->all(),[
            'room_id'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {

            $rooms = Room::where('id', $request['room_id']);

            $rooms=$rooms->first();

            $response=[
                'success'=>true,
                'room'=>$rooms,
                'message'=>'Room details Fetched Successfully'
            ];
        
            return response()->json($response);
        }
    }

    // change availability status
    public function changeRoomStatus(Request $request){

        $validator=validator($request->all(),[
            'room_id'=>'required',
            'availability_status'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            try {
                    
                $room=Room::findOrFail($request['room_id']);
                $room['availability_status']=$request['availability_status'];

                $room->update();
            
            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['success'=>false,'message' => 'Invalid Id to update '], 404);
            }

            $response=[
                'success'=>true,
                'data'=>$room,
                'message'=>'Room Status Updated Successfully',
            ];
    
            return response()->json($response);
        }
    }

    // Delete
    public function deleteHotel(Request $request){
        
        $validator=validator($request->all(),[
            'hotel_id'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            try {
                    
                $hotel=Hotel::findOrFail($request['hotel_id']);
                $hotel['is_disabled']=1;

                $hotel->update();
            
            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['success'=>false,'message' => 'Invalid Id to Delete '], 404);
            }

            $response=[
                'success'=>true,
                'message'=>'Hotel Deleted Successfully',
            ];
    
            return response()->json($response);
        }
    }
}