<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

use Illuminate\Support\Facades\Log;
use App\Models\CwoSubscription;
use App\Models\CarWashOwner;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;
use DB;
class CronController extends Controller
{

    public function unsubscribe(Request $request){
        $dt = Carbon::now(); 
        $today = date("Y-m-d");
        echo "today - " . $today . "<br>";
        $getSubscription = CwoSubscription::where('status', '1')
                                        ->where('end_date', '<', $today)
                                        ->limit(20)
                                        ->get();
        // print_r($getSubscription->toArray());exit;                              
        if($getSubscription != ''){
            foreach ($getSubscription as $s) {
                echo "cwo subscription id: " . $s->id . "<br>";
                $cwoSubscription = CwoSubscription::findorfail($s->id);
                $cwoSubscription->update([       
                    'status'=>'0',
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                $getCwoCount = CarWashOwner::where('id', $s->cwo_id)->where('cwo_subscription_id', $s->id)->count();
                echo "cwo count" . $getCwoCount . "<br><br>";
                if($getCwoCount > 0){
                    $cwoDetails = CarWashOwner::findorfail($s->cwo_id);
                    $cwoDetails->update([       
                        'is_paid'=>'0',
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }

            }
        }

    }

    public function unsubscribeFreeTrial(Request $request){
        $dt = Carbon::now(); 
        $today = date("Y-m-d");
        echo "today - " . $today . "<br>";
        $getSubscription = CarWashOwner::where('free_trial', 1)
                                        ->where('is_paid', 1)
                                        ->where('end_date', '<', $today)
                                        ->limit(20)
                                        ->get();
        // print_r($getSubscription->toArray());exit;                                  
        if($getSubscription != ''){
            foreach ($getSubscription as $s) {
                echo "cwo id: " . $s->id . "<br>";
                $cwoDetails = CarWashOwner::findorfail($s->id);
                $cwoDetails->update([       
                    'is_paid'=>'0',
                    'free_trial'=>'0',
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);

            }
        }

    }


    public function unsubscribeCustom(Request $request){
        $dt = Carbon::now(); 
        $today = date("Y-m-d");
        echo "today - " . $today . "<br>";
        $getSubscription = CarWashOwner::where('free_trial', 0)
                                        ->where('cwo_subscription_id', 0)
                                        ->where('is_paid', 1)
                                        ->where('end_date', '<', $today)
                                        ->limit(20)
                                        ->get();
        // echo "<pre>";print_r($getSubscription->toArray());exit;                                  
        if($getSubscription != ''){
            foreach ($getSubscription as $s) {
                echo "cwo id: " . $s->id . "<br>";
                $cwoDetails = CarWashOwner::findorfail($s->id);
                $cwoDetails->update([       
                    'is_paid'=>'0',
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);

            }
        }

    }


    
    public function subscriptionCustom(Request $request)
    {
        $setMonthlySubscriptionBillingDate=date('Y-m-d');
        $setMonthlySubscriptionEndDate=Carbon::parse(date('Y-m-d'))->subMonth()->format('Y-m-d');
        // dd($setMonthlySubscriptionBillingDate,$setMonthlySubscriptionEndDate);
        // Fetch the last invoice number (for other purposes)
        $invoiceNo = DB::table('invoice')->orderBy('id', 'DESC')->first();
        $getInvoiceNo = $invoiceNo->invoice_no ?? '';
                 $today = date("Y-m-d");
                    $days = 5;
                    $days_ago = date('Y-m-d', strtotime('+'.$days.' days', strtotime($today)));
        // 5 days from today previous
        $cwomaster = DB::table('cwo_master')
        ->join('cwo_subscriptions', 'cwo_subscriptions.id', '=', 'cwo_master.cwo_subscription_id')
        ->where('cwo_master.end_date','>=',date('Y-m-d'))
        ->where('cwo_master.end_date','<=',$days_ago)
        ->where('is_bill_generated', 0)
        ->get();
     

      //  dd($cwomaster);
    
        
    
    
        // Initialize an array to store details of paid users
        $paidUsersArray = [];
   
        // Loop through each CWO master record
      //  dd($cwomaster);
      if(!empty($cwomaster)){
        $totalSubscriptionDaysCount=0;
        foreach ($cwomaster as $cwodet) {
            $fetchcwoid=DB::table('cwo_master')->where('cwo_subscription_id',$cwodet->id)->first();
            $cwomaster1=DB::table('cwo_master')->select('cwo_subscription_id','start_date','end_date','account_no')->where('id',$fetchcwoid->id)->first();
            $cwoSubscriptions=DB::table('cwo_subscriptions')->where('id',$cwomaster1->cwo_subscription_id)->first();
           // dd($cwoSubscriptions);
            $cwoType=$cwoSubscriptions->type??'';
            if($cwoType==1){
                $totalSubscriptionDaysCount=30;
            }
            if($cwoType==2){
                $totalSubscriptionDaysCount=365;
            }
            if($cwoType==3){
                $totalSubscriptionDaysCount=90;
            }
          //   dd($cwomaster1->cwo_subscription_id,$totalSubscriptionDaysCount);
            $whatsapp_start_date_ago = date('Y-m-d', strtotime('-'.$totalSubscriptionDaysCount.' days', strtotime(date('Y-m-d'))));
          
            // dd($totalSubscriptionDaysCount,$cwomaster,$cwodet->id,$cwomaster1->cwo_subscription_id);
            $whatsappEndDate=date('Y-m-d');
 
            $washedData = DB::table('wash_details')
            ->where('cwo_id', $fetchcwoid->id)
            ->whereIn('status', [3, 5])
            ->whereNotNull('driver_phone')
            ->whereBetween('date_washed', [
                $whatsapp_start_date_ago,
                $whatsappEndDate
            ])
            ->count();
        //   dd("new",$washedData);
            $subscriptionamount=$cwoSubscriptions->amount??'';
            $totalwhatsappcharges=($washedData * 2 * 0.3);
         
            $whatsappStartDate = Carbon::parse($cwodet->start_date)->subDay()->format('Y-m-d');
         //   $whatsappEndDate = Carbon::parse($cwodet->end_date)->format('Y-m-d');
            $invoiceType = $cwoSubscriptions->type??'';
            $newAmount = $cwoSubscriptions->amount ?? 0;
          //  dd($newAmount,$totalwhatsappcharges);
            $totalamount = number_format($totalwhatsappcharges + $newAmount, 2, '.', '');

          //  dd($totalwhatsappcharges);

           

            // $paidUsersArray[] = [
            //     'cwo_id' => $cwodet->cwo_id,
            //     'bill_date' => $cwodet->start_date,
            //     'due_date' => $cwodet->end_date,
            //     'whatsapp_start_date' => $whatsappStartDate,
            //     'whatsapp_end_date' => $whatsappEndDate, 
            //     'total_amount' => $totalamount,
            //     'is_paid' => 0,
            //     'created_at' => now(),
            //     'updated_at' => now(),
            // ];

            // if (!empty($paidUsersArray)) {
           $insertid=     DB::table('invoice')->insertGetId([
                    'cwo_id' => $cwodet->cwo_id,
                    'bill_date' => date('Y-m-d'),
                    'due_date' => $cwodet->end_date,
                    'amount' => $subscriptionamount,
                    'type' => $invoiceType,
                    'whatsapp_start_date' => $whatsapp_start_date_ago,
                    'whatsapp_end_date' => date('Y-m-d'), 
                    'whatsapp_amount' => $totalwhatsappcharges, 
                    'total_amount' => $totalamount,
                    'is_paid' => 0,
                    // 'paid_date' => date('Y-m-d'),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            // }
            $invoiceUpdate=DB::table('invoice')->where('id',$insertid)->update([
                'invoice_no' => date('Y').'/'.$insertid
            ]);

            //update cwo_master trial_expiry_date  flag
            $cwoId=$cwodet->cwo_id;
            DB::table('cwo_master')->where('id',$cwoId)->update([
                'is_bill_generated'=>1
            ]);
        }
     
        // Insert all the records in one go to the invoice table
       
    
        // Return the array in JSON format
        return response()->json(['message' => 'Cron set for the day']);
    }
    else{
        return response()->json(['message' => 'No Record']);
    }

    }

    public function subscriptionCustomOne(){

         $invoiceNo = DB::table('invoice')->orderBy('id', 'DESC')->first();
         $getInvoiceNo = $invoiceNo->invoice_no ?? '';
                  $today = date("Y-m-d");
                     $days = 5;
                     $days_ago = date('Y-m-d', strtotime('+'.$days.' days', strtotime($today)));
                     // echo $today . '-' . $days_ago;exit;
         // 5 days from today previous
         $cwomaster = DB::table('cwo_master')
         ->join('cwo_subscriptions', 'cwo_subscriptions.id', '=', 'cwo_master.cwo_subscription_id')
         ->where('cwo_master.end_date','>=',date('Y-m-d'))
         ->where('cwo_master.end_date','<=',$days_ago)
         ->where('cwo_master.is_bill_generated', 0)
         ->get();
         // echo count($cwomaster);exit;
         // dd($cwomaster);
         echo "<pre>";print_r($cwomaster);exit;
        $setMonthlySubscriptionBillingDate = Carbon::now()->format('Y-m-d');
        $setMonthlySubscriptionStartDate = Carbon::now()->subDays(30)->format('Y-m-d');
        echo $setMonthlySubscriptionBillingDate . '->' . $setMonthlySubscriptionStartDate . '<br>';
        
       
         // if(!empty($cwomaster)){
        // if($cwomaster != ''){
        if(count($cwomaster) > 0){
            // exit;
     
           // dd($cwomaster);
           $totalWhatsappAmount=0;
           $subscriptionamount=0;
            foreach ($cwomaster as $cwodet) {
                // echo "send mail to -> " . $cwodet->cwo_id;exit;
                $recipient_name = $cwodet->cwo_name;
                $recipient_email = $cwodet->cwo_email;
                $subject = 'Autoclick Bill Generated';
                // $link = '#';
                $link = route('cwodownloadInvoice', ['invoice_id' => 1]);
                $email = sendMailBilling(array($recipient_name, $recipient_email), $link, $subject);
                // echo $email;exit;
                exit;

             
                $fetchcwoid=DB::table('cwo_master')->where('cwo_subscription_id',$cwodet->id)->first();
                $cwoSubscriptions=DB::table('cwo_subscriptions')->where('id',$fetchcwoid->cwo_subscription_id)->first();
                 $cwoType=$cwoSubscriptions->type??'';
                 $subscriptionamount=$cwoSubscriptions->amount??'';
                // dd($subscriptionamount);
                 $invoiceType = $cwoSubscriptions->type??'';
           
              
                //fetch inqueue status  for car_wash_subscription_details
                $carwashInqueueCheckDate = DB::table('car_wash_subscription_details')
                ->where('subscription_id', 1)
                ->where('cwo_id', $fetchcwoid->id)
                ->orderBy('service_start_date', 'DESC')
                ->get();
                $counter=0;

                 $startQueueEndDate=$setMonthlySubscriptionBillingDate;

                        echo $fetchcwoid->id . '<br>';
                        $carwashdetails=DB::table('wash_details')->where('cwo_id',$fetchcwoid->id)
                        ->whereDate('created_at','>=',$setMonthlySubscriptionStartDate)
                        ->whereDate('created_at','<=',$setMonthlySubscriptionBillingDate)
                        ->whereNotNull('driver_phone')
                        // ->where('status',0)
                        ->orderBy('entry_date','DESC')
                        ->get();
                      
                         if(!empty($carwashdetails)){
                            // echo "<pre>";print_r($carwashdetails);exit;
                            foreach($carwashdetails as $single){
                               // dd($startQueueEndDate,$carwashInqueueCheckDate);
                              // dd($single);
                              $created_at= Carbon::parse($single->created_at)->format('Y-m-d');
                            // dd($created_at);
                            //  DB::enableQueryLog(); // Start logging queries
                                $carwashInqueueCheckDate = DB::table('car_wash_subscription_details')
                                ->where('subscription_id', 1)
                                ->where('cwo_id', $fetchcwoid->id)
                                ->where('service_start_date','<=',$created_at)
                                ->where(function($query) use($startQueueEndDate){
                                    $query
                                    ->where('service_end_date',$startQueueEndDate)
                                    ->orWhereNull('service_end_date');
                                })
                               // ->first();
                               ->first();
                             //  dd(DB::getQueryLog());
                              // dd($created_at,$startQueueEndDate,$carwashInqueueCheckDate);
                               // dd($carwashInqueueCheckDate,$single->created_at);
                               $checkStatus=$carwashInqueueCheckDate->status??0;
                               if($checkStatus==1){
                                $counter++;
                               }
                            }
                         }
                         $queueCounter=$counter;
               //   dd($queueCounter);// Working;
                         echo $queueCounter . '<br>';

//-----------------------------------------------------------------------------------------------------------

 //fetch wash completed status  for car_wash_subscription_details
            $carwashCompletedCheckDate = DB::table('car_wash_subscription_details')
            ->where('subscription_id', 2)
            ->where('cwo_id', $fetchcwoid->id)
            ->orderBy('service_start_date', 'DESC')
            ->get();

             $counterWash=0;

        //    $cwo_id=$fetchcwoid->id;
        //    $startQueueDate=$startDate->format('Y-m-d');
        $startQueueEndDateWashed=$setMonthlySubscriptionBillingDate;


         $carwashcompleteddetails=DB::table('wash_details')->where('cwo_id',$fetchcwoid->id)
         ->where('date_washed','>=',$setMonthlySubscriptionStartDate)
         ->where('date_washed','<=',$setMonthlySubscriptionBillingDate)
         ->whereNotNull('driver_phone')
         // ->whereIn('status',[3,5])
         ->orderBy('entry_date','DESC')
         ->get();
       //  dd($carwashcompleteddetails,$setMonthlySubscriptionStartDate,$setMonthlySubscriptionBillingDate);
          if(!empty($carwashcompleteddetails)){
             foreach($carwashcompleteddetails as $singlevalue){

               $date_washed= $singlevalue->date_washed;
            //   dd($date_washed);
             //  DB::enableQueryLog(); // Start logging queries
                 $carwashInqueueCheckDate = DB::table('car_wash_subscription_details')
                 ->where('subscription_id', 2)
                 ->where('cwo_id', $fetchcwoid->id)
                 ->where('service_start_date','<=',$date_washed)
                 ->where(function($query) use($startQueueEndDateWashed){
                     $query
                     ->where('service_end_date',$startQueueEndDateWashed)
                     ->orWhereNull('service_end_date');
                 })
                // ->first();
                ->first();
               //  dd(DB::getQueryLog());
               // dd($created_at,$startQueueEndDate,$carwashInqueueCheckDate);
                // dd($carwashInqueueCheckDate,$single->created_at);
                $checkStatusWash=$carwashInqueueCheckDate->status??0;
                if($checkStatusWash==1){
                 $counterWash++;
                }
             }
          }
          echo $counterWash . '<br><br><br>';
        
         // $washCompletedCount=$counterWash;

   
         
         $totalWhatsappAmount = number_format(($queueCounter + $counterWash) * 0.3, 2, '.', '');
         $totalamount = number_format($totalWhatsappAmount + $subscriptionamount, 2, '.', '');
        //  dd($queueCounter,$counterWash);
        //  dd([
        //      "In Queue Wash" => $queueCounter,
        //      "Completed Wash" => $counterWash,
        //      "Total WhatsApp Amount" => $totalWhatsappAmount,
        //      "Total Amount" => $totalamount
        //  ]);
         
            
      $insertid=     DB::table('invoice')->insertGetId([
          'cwo_id' => $cwodet->cwo_id,
          'bill_date' => date('Y-m-d'),
          'due_date' => $cwodet->end_date,
          'amount' => $subscriptionamount,
          'type' => $invoiceType,
          'whatsapp_start_date' => $setMonthlySubscriptionStartDate,
          'whatsapp_end_date' => $setMonthlySubscriptionBillingDate,
          'whatsapp_amount'=> $totalWhatsappAmount??'',
          'total_amount' => $totalamount??'',
          'is_paid' => 0,
          'inqueue_notifications_count' => $queueCounter,
          'washed_completed_notifications_count' => $counterWash,
          'total_notifications_count' => $queueCounter+$counterWash,
          // 'paid_date' => date('Y-m-d'),
          'created_at' => now(),
          'updated_at' => now(),

      ]);
  // }
  $invoiceUpdate=DB::table('invoice')->where('id',$insertid)->update([
      'invoice_no' => date('Y').'/'.$insertid
  ]);



  //update cwo_master trial_expiry_date  flag
  $cwoId=$cwodet->cwo_id;
  DB::table('cwo_master')->where('id',$cwoId)->update([
      'is_bill_generated'=>1
  ]);
    $recipient_name = $cwodet->cwo_name;
    $recipient_email = $cwodet->cwo_email;
    $subject = 'Autoclick Bill Generated';
    // $link = '#';
    $link = route('cwodownloadInvoice', ['invoice_id' => $insertid]);
    $email = sendMailBilling(array($recipient_name, $recipient_email), $link, $subject);
    // echo $email;exit;
                }
            
   

           

             
            } else { //only whatsApp starts
                exit;
                // echo "only whatsApp";exit;
                $cwomaster = DB::table('cwo_master')->where('is_bill_generated', 0)->get();
                // echo count($cwomaster);exit;
                if(count($cwomaster) > 0){ // if cwo exists count greater than 0 starts
                    $totalWhatsappAmount=0;
                    $subscriptionamount=0;
                    foreach ($cwomaster as $cwodet) { // foreach cwo starts
                        $end_date = $cwodet->end_date;
                        $time=strtotime($end_date);
                        $day=date("d",$time);
                        // $year=date("Y",$time);
                        $year = date('Y');
                        $month = date('m');
                        $d = $year . '-' . $month . '-' . $day;
                        $days = 5;
                        $days_ago = date('Y-m-d', strtotime('-'.$days.' days', strtotime($d)));

                        // echo $year . '-' .$day. "<br>";
                        // echo $days_ago . '->' . $d . '<br>';
                        if($days_ago == $today) { // if matches today starts
                            $setMonthlySubscriptionBillingDate = Carbon::now()->format('Y-m-d');
                            $setMonthlySubscriptionStartDate = Carbon::now()->subDays(30)->format('Y-m-d');
                            echo $cwodet->id . '->' . $days_ago . '->' . $d . '->' . $setMonthlySubscriptionBillingDate .  '->' . $setMonthlySubscriptionStartDate .'<br>';

                            //fetch inqueue status  for car_wash_subscription_details
                            $carwashInqueueCheckDate = DB::table('car_wash_subscription_details')
                            ->where('subscription_id', 1)
                            ->where('cwo_id', $cwodet->id)
                            ->orderBy('service_start_date', 'DESC')
                            ->get();
                            $counter=0;

                            $startQueueEndDate=$setMonthlySubscriptionBillingDate;

                            $carwashdetails=DB::table('wash_details')->where('cwo_id',$cwodet->id)
                            ->whereDate('created_at','>=',$setMonthlySubscriptionStartDate)
                            ->whereDate('created_at','<=',$setMonthlySubscriptionBillingDate)
                            ->whereNotNull('driver_phone')
                            // ->where('status',0)
                            ->orderBy('entry_date','DESC')
                            ->get();

                            if(!empty($carwashdetails)){
                                foreach($carwashdetails as $single){
                                    // dd($startQueueEndDate,$carwashInqueueCheckDate);
                                    // dd($single);
                                    $created_at= Carbon::parse($single->created_at)->format('Y-m-d');
                                    // dd($created_at);
                                    // DB::enableQueryLog(); // Start logging queries
                                    $carwashInqueueCheckDate = DB::table('car_wash_subscription_details')
                                    ->where('subscription_id', 1)
                                    ->where('cwo_id', $cwodet->id)
                                    ->where('service_start_date','<=',$created_at)
                                    ->where(function($query) use($startQueueEndDate){
                                        $query
                                        ->where('service_end_date',$startQueueEndDate)
                                        ->orWhereNull('service_end_date');
                                    })
                                   ->first();
                                    // dd(DB::getQueryLog());
                                    // dd($created_at,$startQueueEndDate,$carwashInqueueCheckDate);
                                    // dd($carwashInqueueCheckDate,$single->created_at);
                                    $checkStatus=$carwashInqueueCheckDate->status??0;
                                    if($checkStatus==1){
                                        $counter++;
                                    }
                                }
                            }
                            $queueCounter=$counter;
                            // dd($queueCounter);// Working;
                            // echo $queueCounter;exit;

                            //fetch wash completed status  for car_wash_subscription_details
                            $carwashCompletedCheckDate = DB::table('car_wash_subscription_details')
                            ->where('subscription_id', 2)
                            ->where('cwo_id', $cwodet->id)
                            ->orderBy('service_start_date', 'DESC')
                            ->get();

                            $counterWash=0;

                            $startQueueEndDateWashed=$setMonthlySubscriptionBillingDate;

                            $carwashcompleteddetails=DB::table('wash_details')->where('cwo_id',$cwodet->id)
                            ->where('date_washed','>=',$setMonthlySubscriptionStartDate)
                            ->where('date_washed','<=',$setMonthlySubscriptionBillingDate)
                            ->whereNotNull('driver_phone')
                            // ->whereIn('status',[3,5])
                            ->orderBy('entry_date','DESC')
                            ->get();

                            if(!empty($carwashcompleteddetails)){
                                foreach($carwashcompleteddetails as $singlevalue){

                                   $date_washed= $singlevalue->date_washed;
                                   // dd($date_washed);
                                   // DB::enableQueryLog(); // Start logging queries
                                    $carwashInqueueCheckDate = DB::table('car_wash_subscription_details')
                                    ->where('subscription_id', 2)
                                    ->where('cwo_id', $cwodet->id)
                                    ->where('service_start_date','<=',$date_washed)
                                    ->where(function($query) use($startQueueEndDateWashed){
                                        $query
                                        ->where('service_end_date',$startQueueEndDateWashed)
                                        ->orWhereNull('service_end_date');
                                    })
                                    ->first();
                                    // dd(DB::getQueryLog());
                                    // dd($created_at,$startQueueEndDate,$carwashInqueueCheckDate);
                                    // dd($carwashInqueueCheckDate,$single->created_at);
                                    $checkStatusWash=$carwashInqueueCheckDate->status??0;
                                    if($checkStatusWash==1){
                                        $counterWash++;
                                    }
                                 }
                              }

                            $totalWhatsappAmount = number_format(($queueCounter + $counterWash) * 0.3, 2, '.', '');
                            $totalamount = number_format($totalWhatsappAmount + $subscriptionamount, 2, '.', '');
                            echo $totalWhatsappAmount . '->' . $totalamount . '->' . $queueCounter . '->' . $counterWash;

                            $insertid = DB::table('invoice')->insertGetId([
                                'cwo_id' => $cwodet->id,
                                'bill_date' => date('Y-m-d'),
                                'due_date' => $d,
                                'amount' => 0,
                                // 'type' => $invoiceType,
                                'type' => 0,
                                'whatsapp_start_date' => $setMonthlySubscriptionStartDate,
                                'whatsapp_end_date' => $setMonthlySubscriptionBillingDate,
                                'whatsapp_amount'=> $totalWhatsappAmount??'',
                                'total_amount' => $totalWhatsappAmount??'',
                                'is_paid' => 0,
                                'inqueue_notifications_count' => $queueCounter,
                                'washed_completed_notifications_count' => $counterWash,
                                'total_notifications_count' => $queueCounter+$counterWash,
                                // 'paid_date' => date('Y-m-d'),
                                'is_whatsapp_paid' => 0,
                                'is_subscription_paid' => 1,
                                'is_paid' => 0,
                                'created_at' => now(),
                                'updated_at' => now(),

                            ]);

                            $invoiceUpdate=DB::table('invoice')->where('id',$insertid)->update([
                                'invoice_no' => date('Y').'/'.$insertid
                            ]);
                            DB::table('cwo_master')->where('id',$cwodet->id)->update([
                                'is_bill_generated'=>1
                            ]);
                            $recipient_name = $cwodet->cwo_name;
                            $recipient_email = $cwodet->cwo_email;
                            $subject = 'Autoclick Bill Generated';
                            // $link = '#';
                            $link = route('cwodownloadInvoice', ['invoice_id' => $insertid]);
                            $email = sendMailBilling(array($recipient_name, $recipient_email), $link, $subject);
                            // echo $email;exit;

                        } // if matches today ends
                    } // foreach cwo ends
                } // if cwo exists count greater than 0 ends
            } //only whatsApp ends
            exit;
            return response()->json(['message' => 'Cron set for the day']);
      
    }

   

    public function dumpwashdata()
    {
       // dd(Auth::user());
        // Fetch data based on the conditions
        $washDetails = DB::table('cwo_master')
                       // ->whereBetween('date_washed', ['2024-12-15', '2025-02-03'])
                     //   ->whereIn('status', [3,5])
                       // ->whereNotNull('driver_phone')
                        ->orderBy('id','DESC')
                        ->get();
    
        // Insert the fetched data into the target table (e.g., 'new_wash_details')
    
        foreach ($washDetails as $washDetail) {
            DB::table('car_wash_subscription_details')->insert([
                'cwo_id' => $washDetail->id, // Assuming cwo_id is in the source table
                'subscription_id' => 2, // Wash Completed Notification --> 2 In Queue Notification --->1
                'service_name' => 'Wash Completed Notification',
                'service_start_date' =>"2024-12-01",
                'service_end_date' => NULL,
                'status' => 1, // Default value is 1 if not present
                'updated_by' => 13, // Nullable field
                'created_at' => now(),
                'updated_at' => NULL
            ]);

            DB::table('car_wash_subscription_details')->insert([
                'cwo_id' => $washDetail->id, // Assuming cwo_id is in the source table
                'subscription_id' => 1, // Wash Completed Notification --> 2 In Queue Notification --->1
                'service_name' => 'In Queue Notification',  
                'service_start_date' =>"2024-12-01",
                'service_end_date' => NULL,
                'status' => 0, // Default value is 1 if not present
                'updated_by' => 13, 
                'created_at' => now(),
                'updated_at' => NULL
            ]);
        }
    
        return response()->json(['message' => 'Data fetched and inserted successfully!']);
    }

    public function unsubscribeIfBillNotpaid(Request $request){
        $dt = Carbon::now(); 
        $today = date("Y-m-d");
        echo "today - " . $today . "<br>";
        $getData = DB::table('invoice')->where('is_paid', 0)
                                        ->where('due_date', '<', $today)
                                        // ->limit(20)
                                        ->get();
        // print_r($getData->toArray());exit;                              
        if($getData != ''){
            foreach ($getData as $s) {
                // echo "cwo subscription id: " . $s->id . "<br>";
                // $cwoSubscription = CwoSubscription::findorfail($s->id);
                // $cwoSubscription->update([       
                //     'status'=>'0',
                //     'updated_at'=>$dt->toDayDateTimeString()
                // ]);
                $getCwoCount = CarWashOwner::where('id', $s->cwo_id)->count();
                echo "cwo count" . $getCwoCount . "<br>";
                if($getCwoCount > 0){
                    echo $s->cwo_id . "<br><br>";
                    $cwoDetails = CarWashOwner::findorfail($s->cwo_id);
                    $cwoDetails->update([       
                        'is_paid'=>'0',
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }

            }
        }

    }
    

   
    
    



}