<?php

namespace App\Http\Controllers\Api\DsrServices;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Dsr;
use App\Models\User;
use App\Models\DsrPassenger;
use App\Models\DsrServiceHotel;
use App\Models\DsrServiceFlight;
use App\Models\DsrServiceVisa;
use App\Models\DsrServiceCarHire;
use App\Models\DsrServiceAssist;
use App\Models\DsrServiceInsurance;
use App\Models\DsrServiceOther;
use App\Models\DsrSupplierSummary;
use App\Models\DsrServiceTour;
use App\Service\SequenceService;
use App\Service\ActivityService;
use App\Jobs\Naksha\DsrAccounts;
use Auth;
use Log;
use Carbon\Carbon;

class DsrController extends Controller
{
    // Create a new DSR entry
    public function dsrCreateUpdate(Request $request)
    {
        // Validate the input
        $validator=validator($request->all(),[
            'customer_id' => 'required|integer',
            'customer_name' => 'nullable|string|max:100',
            'currency' => 'nullable|string|max:20',
            'exchange_rate' => 'required',
            'dsr_no' => 'nullable|string|max:50'
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            // Activity Service
            $activity=new ActivityService;
            $sequence=new SequenceService;

            $obj['customer_id']=$request['customer_id'];
            $obj['customer_name']=$request['customer_name'];
            $obj['customer_type']=$request['customer_type'];
            $obj['currency']=$request['currency'];
            $obj['currency_symbol']=$request['currency_symbol']??null;
            $obj['exchange_rate']=$request['exchange_rate']??0.00;
            $obj['dsr_no']=$request['dsr_no'];
            $obj['transaction_date']=Carbon::now()->format('Y-m-d');
            $obj['address']=$request['address'];
            
            if($request['id']>0){

                try{

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

                    //Creating Activities 
                    $activity->activityCreateUpdate('DSR Service',$dsr['id'],'Updated');

                } 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{
                // Create the DSR
                $dsr = Dsr::create($obj);

                //Creating Activities 
                $activity->activityCreateUpdate('DSR Service',$dsr['id'],'Created');

                // Update Sequence Number
                $sequence->updateSequence('dsr');
            }
            
            $response=[
                'success' => true,
                'message' => $request['id']>0?'DSR Updated Successfully':'DSR created successfully',
                'data' => $dsr
            ];

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

        }
    }

    //  DSR Lists
    public function dsrList(Request $request){

        $dsr=Dsr::where('rolledback',0)->with('customer:id,display_name,customer_type');

        if($request['search']!=null && $request['search']!=""){
            $dsr=$dsr->where('customer_name','like','%'.$request['search'].'%')
                ->orWhere('dsr_no','like','%'.$request['search'].'%')
                ->orWhere('currency','like','%'.$request['search'].'%')
                ->orWhere('customer_type','like','%'.$request['search'].'%');
        }

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

        $count=$dsr->count();

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

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

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

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

            
    }

    //  DSR Details
    public function dsrDetails(Request $request){
          // Validate the input
          $validator=validator($request->all(),[
            'dsr_id' => 'required|integer'
        ]);

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

            $dsr=Dsr::where('id',$request['dsr_id'])
                ->where('rolledback',0)->with('customer','passengers',
                    'passengers.passenger:id,email,display_name,mobile_no'
                )
                ->first();
            
            if (isset($dsr['passengers']) && !empty($dsr['passengers'])) {

                foreach ($dsr['passengers'] as $key => $passenger) {

                    $dsr_passenger=DsrPassenger::where('id',$passenger['id'])
                        ->with('passenger:id,email,display_name','dsr:id,dsr_no')
                        ->first();

                    if ($dsr_passenger) {

                        $dsrServiceHotel = DsrServiceHotel::where('passenger_id', $passenger['id'])
                            ->with('room:id,room_number')
                            ->where('is_cancle',0)
                            ->get();

                        foreach ($dsrServiceHotel as $index => $hotel) {
                            $guestIds = explode(',', $hotel['guest_ids'] ?? '');
                            $hotel['guests']=User::whereIn('id',$guestIds)->get();
                        }
                        // Attach hotels to the passenger entry
                        $dsr['passengers'][$key]['hotels'] = $dsrServiceHotel;

                        $dsrServicFlight = DsrServiceFlight::where('passenger_id', $passenger['id'])
                            ->where('is_cancle',0)
                            // ->with()
                            ->get();

                        foreach ($dsrServicFlight as $index => $flight) {
                            $guestIds = explode(',', $flight['guest_ids'] ?? '');
                            $flight['guests']=User::whereIn('id',$guestIds)->get();
                        }
                        // Attach Flights to the passenger entry
                        $dsr['passengers'][$key]['flights'] = $dsrServicFlight;

                        $dsrServicVisa = DsrServiceVisa::where('passenger_id', $passenger['id'])
                            ->where('is_cancle',0)
                            ->with('visa_passenger:id,display_name')
                            ->get();

                        foreach ($dsrServicVisa as $index => $visa) {
                            $guestIds = explode(',', $visa['guest_ids'] ?? '');
                            $visa['guests']=User::whereIn('id',$guestIds)->get();
                        }
                        // Attach Visas to the passenger entry
                        $dsr['passengers'][$key]['visas'] = $dsrServicVisa;

                        $dsrServicAssist = DsrServiceAssist::where('passenger_id', $passenger['id'])
                            ->where('is_cancle',0)
                            // ->with('visa_passenger:id,display_name','country:id,name')
                            ->get();

                        foreach ($dsrServicAssist as $index => $assist) {
                            $guestIds = explode(',', $assist['guest_ids'] ?? '');
                            $assist['guests']=User::whereIn('id',$guestIds)->get();
                        }
                        // Attach Assists to the passenger entry
                        $dsr['passengers'][$key]['assists'] = $dsrServicAssist;

                        $dsrServicCarHire = DsrServiceCarHire::where('passenger_id',$passenger['id'])
                            ->where('is_cancle',0)
                            // ->with('visa_passenger:id,display_name','country:id,name')
                            ->get();

                        foreach ($dsrServicCarHire as $index => $car_hire) {
                            $guestIds = explode(',', $car_hire['guest_ids'] ?? '');
                            $car_hire['guests']=User::whereIn('id',$guestIds)->get();
                        }
                        // Attach Car hire to the passenger entry
                        $dsr['passengers'][$key]['car_hires'] = $dsrServicCarHire;

                        $dsrServicInsurance = DsrServiceInsurance::where('passenger_id', $passenger['id'])
                            ->where('is_cancle',0)
                            ->with('passenger')
                            ->get();
                        // Attach Insurance to the passenger entry
                        $dsr['passengers'][$key]['insurance'] = $dsrServicInsurance;

                        $dsrServicOthers = DsrServiceOther::where('passenger_id', $passenger['id'])
                            ->where('is_cancle',0)
                            // ->with('visa_passenger:id,display_name','country:id,name')
                            ->get();
                        // Attach Insurance to the passenger entry
                        $dsr['passengers'][$key]['others'] = $dsrServicOthers;

                        // Show tour Package Details
                        $dsrServicTour = DsrServiceTour::where('passenger_id',$passenger['id'])
                            ->where('is_cancle',0)
                            ->with('tour_package','tour_package.itinerary','tour_package.itinerary.itinary_rows',
                            'tour_package.itinerary.itinary_rows.accomodation','tour_package.itinerary.itinary_rows.transport',
                            'tour_package.itinerary.itinary_rows.destination')
                            // ->with('visa_passenger:id,display_name','country:id,name')
                            ->get();

                        foreach ($dsrServicTour as $index => $tour) {
                            $guestIds = explode(',', $tour['guest_ids'] ?? '');
                            $tour['guests']=User::whereIn('id',$guestIds)->get();
                        }
                        // Attach Car hire to the passenger entry
                        $dsr['passengers'][$key]['tour_packages'] = $dsrServicTour;
                    }
                }

            }
            $response=[
                'success'=>true,
                'data'=>$dsr,
                'message'=>'Dsr Details Successfully'
            ];
            
            return response()->json($response);
        }

            
    }
    //  DSR Delete
    public function dsrDelete(Request $request){
          // Validate the input
          $validator=validator($request->all(),[
            'dsr_id' => 'required|integer'
        ]);

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

            try{

                $dsr=Dsr::findOrFail($request['dsr_id']);
                $dsr->rolledback=1;
                $dsr->save();

                $response=[
                    'success'=>true,
                    'data'=>$dsr,
                    'message'=>'Dsr Deleted Successfully'
                ];
                
                return response()->json($response);

            } 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);
            }

        }
            
    }

    //  DSR Invoiced
    public function dsrInvoiced(Request $request){
          // Validate the input
          $validator=validator($request->all(),[
            'dsr_id' => 'required|integer'
        ]);

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

            try{

                $dsr=Dsr::findOrFail($request['dsr_id']);

                if($dsr['is_invoiced']==0){

                    // Dispatch the job to send data to accounts table
                    DsrAccounts::dispatch($dsr);

                    $dsr->is_invoiced=1;
                    $dsr->save();

                    $response=[
                        'success'=>true,
                        'data'=>$dsr,
                        'message'=>'Dsr Invoiced Successfully'
                    ];

                }else{

                    $response=[
                        'success'=>false,
                        'message'=>'Dsr Invoiced already made',
                        'data'=>$dsr
                    ];
                }
                
                return response()->json($response);

            } 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);
            }

        }
            
    }


    // DSR Passengers Create
    public function dsrPassengerCreate(Request $request){
          // Validate the input
          $validator=validator($request->all(),[
            'dsr_id' => 'required|integer',
            'customer_id' => 'required|integer',
            'passenger_name' => 'nullable|string|max:100'
        ]);

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

            $obj['dsr_id']=$request['dsr_id'];
            $obj['customer_id']=$request['customer_id'];
            $obj['passenger_name']=$request['passenger_name'];
            
            if($request['id']>0){

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

            }else{
                // Create the DSR
                $dsr = DsrPassenger::create($obj);
            }
            
            $response=[
                'success' => true,
                'message' => $request['id']>0?'Passenger Updated Successfully':'Passenger created successfully'
            ];

            return response()->json($response);
        }
    }
    //DSR Passenger Delete
    public function dsrPassengerDelete(Request $request){
         // Validate the input
         $validator=validator($request->all(),[
            'passenger_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            
            try {
                    
                $dsr=DsrPassenger::findOrFail($request['passenger_id']);

                //update all the services for this passenger
                // All Services Lists
                $services=['Hotel','Flight','Visa','Assist','CarHire','Insurance','Other','Tour'];

                // Calling all the services in a loop
                foreach ($services as $key => $service) {

                    $namespace = 'App\Models';                            // Replace with the actual namespace
                    $dsrService = $namespace . '\DsrService' . $service;  //'App/Models/DsrServiceAssist'

                    // Getting all the data of single service like Assists, all Assists in a passenger
                    $dsr_service=$dsrService::where('dsr_id',$dsr['dsr_id'])
                        ->where('passenger_id',$dsr['id'])
                        ->where('is_cancle',0)
                        ->update(['is_cancle'=>1]);
                }

                $dsr['rolledback']=1;
                $dsr->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 '], 200);
            }

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

    // Get all supplier entry dsr id wise
    public function getSupplierSummary(Request $request){

        $validator=validator($request->all(),[
            'dsr_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 
            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];
        } else {
            
            $summary=DsrSupplierSummary::where('dsr_id',$request['dsr_id'])
                ->with('dsr:dsr_no,transaction_date,id');
            
            if(isset($request['supplier_name']) && $request['supplier_name']!=''){
                $summary=$summary->where('supplier_name','like','%'.$request['supplier_name'].'%');
            }

            if(isset($request['service_name']) && $request['service_name']!=''){
                $summary=$summary->where('service_name','like','%'.$request['service_name'].'%');
            }

            // if($request['search']!=null && $request['search']!=""){
            //     $summary=$summary->where('supplier_name','like','%'.$request['search'].'%')
            //         ->orWhere('service_name','like','%'.$request['search'].'%')
            //         ->orWhere('tax_percent',$request['search']);
            // }
             
            $summary=$summary->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??50)
                ->get();

            $response=[
                'success'=>true,
                'message'=>'Suppliers listed Successfully',
                'data'=>$summary
            ];

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

    }

     // Get all supplier entry in DSRs
    public function getAllSupplierSummary(Request $request){
            
        $summary=DsrSupplierSummary::with('dsr:dsr_no,transaction_date,id,currency_symbol,exchange_rate,currency,is_invoiced');
        
        if(isset($request['supplier_name']) && $request['supplier_name']!=''){
            $summary=$summary->where('supplier_name','like','%'.$request['supplier_name'].'%');
        }
        if(isset($request['supplier_id']) && $request['supplier_id']!=0){
            $summary=$summary->where('supplier_id',$request['supplier_id']);
        }
        // For Billed 
        if(isset($request['is_billed']) && $request['is_billed']==1){
            $summary=$summary->where('is_billed',$request['is_billed']);
        }
        // For Un billed
        if(isset($request['is_billed']) && $request['is_billed']==2){
            $summary=$summary->where('is_billed',0);
        }

        if(isset($request['service_name']) && $request['service_name']!=''){
            $summary=$summary->where('service_name','like','%'.$request['service_name'].'%');
        }

        $total=$summary->count();
            
        $summary=$summary->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
            ->orderBy('id','desc')
            ->get();

        $response=[
            'success'=>true,
            'message'=>'All Suppliers Summary listed Successfully',
            'total'=>$total,
            'data'=>$summary
        ];

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

    }


}
