<?php

namespace App\Http\Controllers\OwnerPanel;

use DB;
use Carbon\Carbon;

use App\Models\User;;
use App\Models\Permission;
use App\Models\WashDetail;
use App\Models\CarWashOwner;
use Illuminate\Http\Request;
use App\Models\CurrencyMaster;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Models\OtherServiceReport;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\View;
use App\Models\OtherServiceReportToProduct;

class OwnerBillingController extends Controller
{
    public function index(Request $request)
    {
        $data['chMenu'] = "";
        $cwo_id = Auth::user()->cwo_id;
        $totalSubscriptionDaysCount=0;
        //fetch current subscription id
        $cwomaster=DB::table('cwo_master')->select('cwo_subscription_id','start_date','end_date','account_no','id','allow_whatsapp_service','allow_whatsapp_inqueue','allow_whatsapp_completed')->where('id',$cwo_id)->first();
        $cwoSubscriptions=DB::table('cwo_subscriptions')->where('id',$cwomaster->cwo_subscription_id)->first();
        $cwoType=$cwoSubscriptions->type??'';
        if($cwoType==1){
            $totalSubscriptionDaysCount=30;
        }
        if($cwoType==2){
            $totalSubscriptionDaysCount=365;
        }
        if($cwoType==3){
            $totalSubscriptionDaysCount=90;
        }
        $whatsapp_start_date_ago = date('Y-m-d', strtotime('-'.$totalSubscriptionDaysCount.' days', strtotime(date('Y-m-d'))));
        $whatsappEndDate=date('Y-m-d');
        $washedData = DB::table('wash_details')
        ->where('cwo_id', $cwo_id)
        ->whereIn('status', [3, 5])
        ->whereBetween('date_washed', [
            $whatsapp_start_date_ago,   
            $whatsappEndDate
        ])
        ->get();
        $washedDataNoMessages = DB::table('wash_details')
        ->where('cwo_id', $cwo_id)
        ->whereIn('status', [3, 5])
        ->whereNotNull('driver_phone')
        ->whereBetween('date_washed', [
            $whatsapp_start_date_ago,   
            $whatsappEndDate
        ])
        ->count();
        // dd($washedDataNoMessages);
        //  dd($washedData,$cwomaster->start_date, $cwomaster->end_date);
        //previous billed details
      //  $previousBill=DB::table('cwo_subscriptions')->where('cwo_id',$cwo_id)->where('id','!=',$cwomaster->cwo_subscription_id)->orderBy('start_date','DESC')->where('status',1)->limit(12)->get();
        $previousBill=DB::table('invoice')->where('cwo_id', $cwo_id)->where('is_paid',1)->orderBy('bill_date','DESC')->limit(12)->get();
        $checkInvoice=DB::table('invoice')->where('cwo_id', $cwo_id)->where('is_paid',0)->first();
        $dataBag['cwo_master']=$cwomaster;
        $dataBag['allRecords'] = [];
        $dataBag['records'] = $cwoSubscriptions;
        $dataBag['washedDataCount'] = $washedData->count();
        $dataBag['washedDataNoMessages'] = $washedDataNoMessages;
        $dataBag['previousBill'] = $previousBill;
        $dataBag['checkInvoice'] = $checkInvoice;
        // echo "<pre>";print_r($dataBag['records']);exit;
        return view('owner.billing.list', $dataBag);
    }

    public function downloadInvoice(Request $request){
       
        $data=[];
        $checkInvoice=DB::table('invoice')
        ->where('id', $request->invoice_id)->first();
        if(empty($request->invoice_id) || empty($checkInvoice)){
        abort(404);
        }
        $pdf = PDF::loadView('owner.billing.invoice_view', ['data'=>$checkInvoice]);
        $currentDate=date('d-m-Y');
        return $pdf->download("invoice_{$currentDate}.pdf");
    }

 
    
    public function optInOutWhatsapp(Request $request)
    {
        try {
            $cwo_id = $request->cwo_id;
            $currentmasterstatus=$request->currentmasterstatus;
            $allowWhatsappInQueue = $request->status_in_queue ?? 0;
            $allowWhatsappCompleted = $request->status_completed ?? 0;
            if($currentmasterstatus==0){
                $updateMaster=DB::table('cwo_master')
                ->where('id', $cwo_id)
                ->update([
                    'allow_whatsapp_service' => 0,
                    'allow_whatsapp_inqueue' => 0,
                    'allow_whatsapp_completed' => 0
                ]);

               $checknewMasterStatus=DB::table('cwo_master')
               ->where('id', $cwo_id)
               ->where('allow_whatsapp_service',0)
               ->where('allow_whatsapp_inqueue',0)
               ->where('allow_whatsapp_completed',0)
               ->count();
               if($checknewMasterStatus==1){
                DB::table('opt_whatsapp_charges')->insert(['cwo_id'=>$cwo_id,'whatsapp_stop_date'=>date('Y-m-d'),'status'=>1,'created_at'=>now()]);
               }
            
            }
            else{
            // Initialize values to prevent undefined variable issues
            $allowWhatsappInQueue = $request->status_in_queue ?? 0;
            $allowWhatsappCompleted = $request->status_completed ?? 0;
    
            // Determine update status based on new logic
            if ($allowWhatsappInQueue == 1 && $allowWhatsappCompleted == 1) {
                $updateStatus = 2;
            } elseif ($allowWhatsappInQueue == 1 && $allowWhatsappCompleted == 0) {
                $updateStatus = 1;
            } elseif ($allowWhatsappInQueue == 0 && $allowWhatsappCompleted == 1) {
                $updateStatus = 1; // New condition to handle this case
            } else {
                $updateStatus = 0; // Default case when both are 0
                
            }
    
            // Update the database
            $checkStatus = DB::table('cwo_master')
                ->where('id', $cwo_id)
                ->update([
                    'allow_whatsapp_service' => $updateStatus,
                    'allow_whatsapp_inqueue' => $allowWhatsappInQueue,
                    'allow_whatsapp_completed' => $allowWhatsappCompleted
                ]);

            //    if($request->currentmasterstatus==1 && ($allowWhatsappInQueue==0   && $allowWhatsappCompleted==0)){
            
            //      DB::table('opt_whatsapp_charges')->insert(['cwo_id'=>$cwo_id,'whatsapp_stop_date'=>date('Y-m-d'),'status'=>1,'created_at'=>now()]);
                
            //    }
                // $checknewAnotherMasterStatus=DB::table('cwo_master')
                // ->where('id', $cwo_id)
                // ->where('allow_whatsapp_service',0)

                // ->count();
                // if($checknewAnotherMasterStatus==1){
                //  DB::table('opt_whatsapp_charges')->insert(['cwo_id'=>$cwo_id,'whatsapp_stop_date'=>date('Y-m-d'),'status'=>1,'created_at'=>now()]);
                // }
    
            // Response based on update result
            if ($checkStatus) {
                return response()->json([
                    'success' => true,
                    'message' => 'Status updated successfully!',
                    'new_status' => $updateStatus
                ]);
            }
    
         
        }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ], 500);
        }
    }

    public function listingServices(Request $request){
     $listing=DB::table('car_wash_subscription_details')->orderBy('service_start_date','desc')->where('cwo_id',Auth::user()->cwo_id)->paginate();
     dd($listing);
    }
     public function addService(Request $request){  
        $dataBag['chMenu'] = '';
        $dataBag['cwoid'] = Auth::user()->cwo_id;
        // $dataBag['permission'] = Permission::where('is_active', 1)->orderBy('id', 'asc')->get();
        return view('owner.billing.service',$dataBag);
     }
     public function saveSubscription(Request $request){
        $carwashSubscriptionDetails=DB::table('car_wash_subscription_details')->insert([
            'cwo_id'=>$request->cwo_id,
            'subscription_id'=>$request->service_type,
            'service_name'=>$request->service_type==1?'In Queue Notification':'Wash Completion Notification',
            'service_start_date'=>$request->service_start_date??'',
            'status'=>$request->is_active,
            'created_at'=>now(),
            'updated_by'=>Auth::user()->id,
        ]);

        if($request->service_type){

           //For In queue Notifictation
           if($request->service_type=="1"){
          
            $checkLastServiceStartDate=DB::table('car_wash_subscription_details')->where('subscription_id',1)->where('cwo_id',$request->cwo_id)->where('service_start_date','<=',$request->service_start_date)->first();
          // dd("In Queue",Carbon::parse($request->service_start_date)->subDay()->format('Y-m-d'));
            $lastServiceid=$checkLastServiceStartDate->id;
            $updateLastServiceDate=DB::table('car_wash_subscription_details')->where('id',$lastServiceid)->update([
            'service_end_date'=>Carbon::parse($request->service_start_date)->subDay()->format('Y-m-d'),
            'status'=>0
            ]);

           }
           if($request->service_type=="2"){
          //       dd("Completed",Carbon::parse($request->service_start_date)->subDay()->format('Y-m-d'));
            $checkLastServiceStartDate=DB::table('car_wash_subscription_details')->where('subscription_id',2)->where('cwo_id',$request->cwo_id)->where('service_start_date','<=',$request->service_start_date)->first();
            $lastServiceid=$checkLastServiceStartDate->id;
            $updateLastServiceDate=DB::table('car_wash_subscription_details')->where('id',$lastServiceid)->update([
            'service_end_date'=>Carbon::parse($request->service_start_date)->subDay()->format('Y-m-d'),
            'status'=>0
            ]); 
        }
          

        }
        return redirect()->route('owner.billing.getSubscription')
        ->with('success', 'Service Type has been added successfully')
        ->with('msg_class', 'alert alert-success');
    
     }

     public function getSubscription(Request $request)
     {
      //  dd($request->all());
         $service_start_date = $request->start_date ?? '';
         $service_end_date = $request->end_date ?? '';
         $search = $request->search ?? '';
         $dataBag['chMenu'] = "";
         $cwo_id = Auth::user()->cwo_id;
     

         $query = DB::table('car_wash_subscription_details')
             ->where('cwo_id', $cwo_id)
             ->orderBy('service_start_date', 'desc');
         if ($search != '') {
             $query->where('car_wash_subscription_details.subscription_id', '=', $search);
         }
         if ($service_start_date != '') {
             $query->where('car_wash_subscription_details.service_start_date', '>=', $service_start_date);
         }
         if ($service_end_date != '') {
             $query->where('car_wash_subscription_details.service_end_date', '<=', $service_end_date);
         }    
     
         $data = $query->paginate(10); 
     
         $dataCnt = $data->total(); // Get the total count of records
     
         $dataBag['allRecords'] = $dataCnt;
         $dataBag['records'] = $data;
     
         return view('owner.billing.subscription', $dataBag);
     }
     
     
    
    
    
    

}
