<?php

namespace App\Http\Controllers\Api\ProductServices;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TourPackage;
use App\Models\Itinerary;
use App\Models\ItineraryRow;
use Auth;

class TourPackageController extends Controller
{
    public function tourCreateupdate(Request $request){

        $validator=validator($request->all(),[
            'package_name'=>'required',
            'days' => 'nullable|integer|min:0',
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            $obj['package_name']=$request['package_name'];
            $obj['destination']=$request['destination'];
            $obj['days']=$request['days']??0;
            $obj['hotel_type']=$request['hotel_type'];
            $obj['meal_id']=$request['meal_id']??0;
            $obj['meal_name']=$request['meal_name'];
            $obj['currency']=$request['currency'];
            $obj['price_per_person']=$request['price_per_person']??0;
            $obj['other']=$request['other'];
            $obj['description']=$request['description']??null;
            $obj['terms_and_conditions']=$request['terms_and_conditions']??null;
            $obj['package_inclusion']=$request['package_inclusion']??null;
            $obj['package_exclusion']=$request['package_exclusion']??null;
            $obj['upload_documents']=$request['upload_documents'];
            $obj['discount']=$request['discount']??0.0;
            $obj['is_transport']=$request['is_transport']??0;    //0 for no and 1 for yes

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

                try {
                        
                    $hotel=TourPackage::findOrFail($request['id']);

                    $hotel->update($obj);
                //
                } 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);
                }
            }else{
                $hotel=TourPackage::create($obj);
            }

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

    // List Of Tour Packages
     public function getTourPackages(Request $request){

        $user=Auth::user();

        $hotels = TourPackage::where('is_disabled', 0);

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

        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('package_name', 'LIKE', '%' . $searchTerm . '%')
                    ->orWhere('destination', 'LIKE', '%' . $searchTerm . '%')
                    ->orWhere('price_per_person', '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,
            'count'=>$count,
            'data'=>$hotels,
            'message'=>'All Tour Packages Listed Successfully'
        ];
        
        return response()->json($response);

    } 

    // Details Of Tour Packages
    public function tourPackageDetails(Request $request){

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

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

            $hotel=TourPackage::with('itinerary','itinerary.itinary_rows','itinerary.itinary_rows.destination',
                'itinerary.itinary_rows.accomodation','itinerary.itinary_rows.transport',
                'itinerary.itinary_rows.destination.accommodation','itinerary.itinary_rows.others')
                ->where('id', $request['tour_id'])->first();

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

        }
    }

    // Status
    public function changeTourStatus(Request $request){
        
        $validator=validator($request->all(),[
            'tour_id'=>'required',
            'status'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            try {
                    
                $hotel=TourPackage::findOrFail($request['tour_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'=>'Tour Package Status Updated Successfully',
            ];
    
            return response()->json($response);
        }
    }

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

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

                $tour->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'=>'Tour Package Deleted Successfully',
            ];
    
            return response()->json($response);
        }
    }

    // Add Itinerary
    public function addItinerary(Request $request){

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

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

            $obj['tour_package_id']=$request['tour_package_id'];
            $obj['day']=$request['day'];
            $obj['day_plan']=$request['day_plan'];
            $obj['destination_id']=$request['destination_id']??0;
            $obj['accommodation_id']=$request['accommodation_id']??0;
            $obj['transport_id']=$request['transport_id']??0;
            $obj['description']=$request['description'];
            $obj['upload_documents']=$request['upload_documents'];
            $obj['start_date']=$request['start_date'];
            $obj['end_date']=$request['end_date'];
            $obj['itinerary_list']=$request['itinerary_list']??null;

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

                try {
                        
                    $itinarary=Itinerary::findOrFail($request['id']);

                    ItineraryRow::where('itinerary_id', $request['id'])->delete();

                    $itinarary->update($obj);

                    if(isset($request['itinary_rows']) && count($request['itinary_rows'])>0){

                        foreach ($request['itinary_rows'] as $key => $value) {

                            $obj2['itinerary_id']=$itinarary['id'];
                            $obj2['destination_id']=$value['destination_id']??0;
                            $obj2['accommodation_id']=$value['accommodation_id']??0;
                            $obj2['transport_id']=$value['transport_id']??0;
                            $obj2['other_id']=$value['other_id']??0;
                            $obj2['description']=$value['description']??null;
                            $obj2['upload_documents']=$value['upload_documents']??null;
                            ItineraryRow::create($obj2);
                        }
                    }
                
                } 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 '], 200);
                }
            }else{
                $itinarary=Itinerary::create($obj);

                if(isset($request['itinary_rows']) && count($request['itinary_rows'])>0){

                    foreach ($request['itinary_rows'] as $key => $value) {

                        $obj2['itinerary_id']=$itinarary['id'];
                        $obj2['destination_id']=$value['destination_id']??0;
                        $obj2['accommodation_id']=$value['accommodation_id']??0;
                        $obj2['other_id']=$value['other_id']??0;
                        $obj2['transport_id']=$value['transport_id']??0;
                        $obj2['description']=$value['description']??null;
                        $obj2['upload_documents']=$value['upload_documents']??null;
                        ItineraryRow::create($obj2);
                    }
                }
            }

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

    // Itinerary list
    public function itineraryList(Request $request){

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

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            $itinarary = Itinerary::where('is_deleted',0)
                ->with('destination','accomodation','transport','itinary_rows','itinary_rows.destination','itinary_rows.accomodation','itinary_rows.transport')
                ->where('tour_package_id', $request['tour_package_id']);

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

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

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

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

            $response=[
                'success'=>true,
                'count'=>$count,
                'data'=>$itinarary,
                'message'=>'All Itinerary Listed Successfully'
            ];
            
            return response()->json($response);
        }
    }

    // Status
    public function changeItinerary(Request $request){
        
        $validator=validator($request->all(),[
            'itinerary_id'=>'required',
            'status'=>'required'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            try {
                    
                $hotel=Itinerary::findOrFail($request['itinerary_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'=>'Itinerary Status Updated Successfully',
            ];
    
            return response()->json($response);
        }
    }

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

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            try {
                    
                $tour=Itinerary::findOrFail($request['itinerary_id']);
                $tour['is_deleted']=1;

                $itinarary_row=ItineraryRow::where('itinerary_id',$request['itinerary_id'])->get();

                foreach ($itinarary_row as $key => $value) {
                    $value->delete();
                }

                $tour->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'=>'Itinerary Deleted Successfully',
            ];
    
            return response()->json($response);
        }
    }
}
