<?php

namespace App\Console\Commands;

use App\Models\OrderGrouping;
use App\Models\OrderGroupingDetail;
use App\Models\OrderSchedule;
use App\Models\Setting;
use Illuminate\Console\Command;
use DB;

class OrderGroupingDetailCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order_grouping_detail:cron';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Order Grouping Detail Cron';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // return 0;
        // Group Normal Orders
        DB::transaction(function()
        {
            $orderSchedules = OrderSchedule::select('pickup_city','pickup_location_id','pickup_postal_code','order_type','pickup_date','pickup_time_id','pickup_address')->selectRaw("SUM(quantity) as pickup_quantity")->selectRaw("SUM(merchant_cost) as merchant_cost")->selectRaw("Count(*) as order_count")->where('status',0)->where('order_type',1)->groupBy('pickup_city','pickup_location_id','pickup_postal_code','order_type','pickup_date','pickup_time_id','pickup_address')->get();
            // $orderSchedules = OrderSchedule::select('pickup_city','pickup_location_id','pickup_postal_code','order_type','pickup_date','pickup_time_id','pickup_address')->selectRaw("SUM(quantity) as pickup_quantity")->selectRaw("Count(*) as order_count")->where('status',0)->whereColumn('pickup_location_id','drop_location_id')->groupBy('pickup_city','pickup_location_id','pickup_postal_code','order_type','pickup_date','pickup_time_id','pickup_address')->get();
           
            \Log::info("ordergroupingdetails".$orderSchedules);
            if(count($orderSchedules) > 0)
            {                                  
                $orderGroup = OrderGroupingDetail::createOrderGroupingDetail($orderSchedules); 
                \Log::info("ordergroupingdetails".$orderGroup);          
            }
            else
            {
                dd("Insert Error :");
            }
            
        });

        //Group Express Orders
        DB::transaction(function()
        {
            $orderSchedules = OrderSchedule::where('status',0)->where('order_type',2)->get();
                      
            \Log::info("ordergroupingdetails".$orderSchedules);
            if(count($orderSchedules) > 0)
            {                                  
                $orderGroup = OrderGroupingDetail::createExpressOrderGroupingDetail($orderSchedules); 
                \Log::info("ordergroupingdetails".$orderGroup);          
            }
            else
            {
                dd("Insert Error :");
            }
            
        });

         DB::transaction(function()
        {

            $max_pickup_quantity = Setting::getSettingValue('max_pickup_qty');
            $max_pickup_addr = Setting::getSettingValue('max_pickup_addr');
            $orderGroupingDetails = OrderGroupingDetail::select('pickup_location_id','order_type','pickup_date','pickup_time_id')->selectRaw('SUM(pickup_quantity) as pickup_quantity')->selectRaw('SUM(order_count) as order_count')->selectRaw('COUNT(order_grouping_detail_id) as pickup_address_count')->where('order_type',1)->where('is_grouped',0)->groupBy('pickup_location_id','order_type','pickup_date','pickup_time_id')->get();
           
            if(count($orderGroupingDetails )>0)
            {
                foreach($orderGroupingDetails as $orderGroupingDetail)
                {
                    
                    if(($orderGroupingDetail->pickup_quantity <= $max_pickup_quantity &&$orderGroupingDetail->pickup_address_count == $max_pickup_addr) || $orderGroupingDetail->pickup_quantity == $max_pickup_quantity &&$orderGroupingDetail->pickup_address_count <= $max_pickup_addr)
                    {
                        $max_order_grouping_flg = OrderGroupingDetail::max('order_grouping_flg');
                        $order_grouping_flg = $max_order_grouping_flg + 1;
                        $orderGrouping = OrderGroupingDetail::where('pickup_location_id',$orderGroupingDetail->pickup_location_id)->where('pickup_date',$orderGroupingDetail->pickup_date)
                        ->where('pickup_time_id',$orderGroupingDetail->pickup_time_id)
                        ->where('order_type',1)
                        ->where('is_grouped',0)
                        ->update([
                            'is_grouped' => 1,
                            'order_grouping_flg' => $order_grouping_flg
                        ]);


                      
                    }
                }
            }


        });

        // DB::transaction(function()
        // {
        //     $orderGroupingDetails = OrderGroupingDetail::select('pickup_location_id','pickup_postal_code','order_type','pickup_date','pickup_time_id')->selectRaw('SUM(pickup_quantity) as pickup_quantity')->selectRaw('SUM(order_count) as order_count')->selectRaw('COUNT(order_grouping_detail_id) as pickup_address_count')->where('order_type',1)->where('is_grouped',0)->groupBy('pickup_location_id','pickup_postal_code','order_type','pickup_date','pickup_time_id')->get();
           
        //     if(count($orderGroupingDetails )>0)
        //     {
        //         foreach($orderGroupingDetails as $orderGroupingDetail)
        //         {
                    
        //             if(($orderGroupingDetail->pickup_quantity <= 12 &&$orderGroupingDetail->pickup_address_count == 3) || ($orderGroupingDetail->pickup_quantity == 12 &&$orderGroupingDetail->pickup_address_count <= 3))
        //             {
        //                 $max_order_grouping_flg = OrderGroupingDetail::max('order_grouping_flg');
        //                 $order_grouping_flg = $max_order_grouping_flg + 1;
        //                 $orderGrouping = OrderGroupingDetail::where('pickup_location_id',$orderGroupingDetail->pickup_location_id)
        //                 ->where('pickup_postal_code',$orderGroupingDetail->pickup_postal_code)
        //                 ->where('pickup_date',$orderGroupingDetail->pickup_date)
        //                 ->where('pickup_time_id',$orderGroupingDetail->pickup_time_id)
        //                 ->where('order_type',1)
        //                 ->where('is_grouped',0)
        //                 ->update([
        //                     'is_grouped' => 1,
        //                     'order_grouping_flg' => $order_grouping_flg
        //                 ]);

                       
                        
        //             }
        //         }
        //     }


        // });

        // DB::transaction(function()
        // {
        //     $orderGroupingDetails = OrderGroupingDetail::select('pickup_location_id','pickup_postal_code','pickup_address','order_type','pickup_date','pickup_time_id')->selectRaw('SUM(pickup_quantity) as pickup_quantity')->selectRaw('SUM(order_count) as order_count')->selectRaw('COUNT(order_grouping_detail_id) as pickup_address_count')->where('order_type',1)->where('is_grouped',0)->groupBy('pickup_location_id','pickup_postal_code','pickup_address','order_type','pickup_date','pickup_time_id')->get();
           
        //     if(count($orderGroupingDetails )>0)
        //     {
        //         foreach($orderGroupingDetails as $orderGroupingDetail)
        //         {
                    
        //             if($orderGroupingDetail->pickup_quantity == 12)
        //             {
        //                 $max_order_grouping_flg = OrderGroupingDetail::max('order_grouping_flg');
        //                 $order_grouping_flg = $max_order_grouping_flg + 1;
        //                 $orderGrouping = OrderGroupingDetail::where('pickup_location_id',$orderGroupingDetail->pickup_location_id)
        //                 ->where('pickup_postal_code',$orderGroupingDetail->pickup_postal_code)
        //                 ->where('pickup_date',$orderGroupingDetail->pickup_date)
        //                 ->where('pickup_time_id',$orderGroupingDetail->pickup_time_id)
        //                 ->where('order_type',1)
        //                 ->where('is_grouped',0)
        //                 ->update([
        //                     'is_grouped' => 1,
        //                     'order_grouping_flg' => $order_grouping_flg
        //                 ]);                        
                      
        //             }
        //         }
        //     }


        // });

        

        DB::transaction(function()
        {
            $varProceed = true;
            while($varProceed)
            {
                $max_pickup_quantiy = OrderGroupingDetail::where('order_type',1)->where('is_grouped',0)->max('pickup_quantity');
                $max_pickup_qty = Setting::getSettingValue('max_pickup_qty');
                if($max_pickup_quantiy)
                {
                    \Log::info("max_pickup_quantiy".$max_pickup_quantiy);

                    $need_pickup_quantity = $max_pickup_qty - $max_pickup_quantiy ;
                    $max_order_grouping_flg = OrderGroupingDetail::max('order_grouping_flg');
                    $order_grouping_flg = $max_order_grouping_flg + 1;  

                    $orderGroupingDetail = OrderGroupingDetail::where('order_type',1)->where('is_grouped',0)->where('pickup_quantity',$max_pickup_quantiy)->first();
                    
                    \Log::info("orderGroupingDetail".$orderGroupingDetail);

                    if($orderGroupingDetail)    
                    {
                        $orderGroups = OrderGroupingDetail::where('pickup_location_id',$orderGroupingDetail->pickup_location_id)
                        ->where('order_type',1)
                        ->where('pickup_date',$orderGroupingDetail->pickup_date)
                        ->where('pickup_time_id',$orderGroupingDetail->pickup_time_id)
                        ->where('order_grouping_detail_id','!=',$orderGroupingDetail->order_grouping_detail_id)
                        ->where('pickup_quantity','<=',$need_pickup_quantity)
                        ->where('is_grouped',0)
                        ->orderBy('pickup_quantity','desc')
                        ->get();
                        \Log::info("orderGroups".$orderGroups);
                        if(count($orderGroups)>0)
                        {
                            $total_pickup_quantity = 0;
                            $loop = 0;
                        
                            foreach($orderGroups as $orderGroup)
                            {
                                $total_pickup_quantity = $orderGroup->pickup_quantity + $orderGroupingDetail->pickup_quantity;
                                if($total_pickup_quantity <= $max_pickup_qty && $loop < 2)
                                {
                                    $orderGroup->order_grouping_flg = $order_grouping_flg;
                                    $orderGroup->is_grouped = 1;
                                    $orderGroup->save(); 
                                    $loop++;
                                    \Log::info("loop".$loop);
                                }
                            }
                        }               
                        $orderGroupingDetail->order_grouping_flg = $order_grouping_flg;
                        $orderGroupingDetail->is_grouped = 1;
                        $orderGroupingDetail->save();
                    }
                    else
                    {
                        dd("Reached All");
                    }
                }
                else
                {
                    $varProceed = false;
                }
            }
        });

        DB::transaction(function()  //// group by express orders
        {
            $orderGroupingDetails = OrderGroupingDetail::where('is_grouped','=',0)->where('order_type',2)->get();
            // \Log::info("expressOrderGroupingDetails".$orderGroupingDetails);
            if(count($orderGroupingDetails) > 0)
            {   
				$flg = OrderGroupingDetail::select('order_grouping_flg')->max('order_grouping_flg');
                  
                $count = 0;    
				$count = $flg + 1;					
                foreach($orderGroupingDetails as $orderGroupingDetail)
                {
                    
                //    $data['pickup_quantity'] = $orderGroupingDetail->pickup_quantity;     
                //    $data['order_count'] = $orderGroupingDetail->order_count;     
                //    $data['pickup_address_count'] = 1;   
                //    $data['count'] = $count;  
                //    $orderGrouping = OrderGrouping::createOrderGrouping($orderGroupingDetail,$data);
					
                   $orderGroupingDetail->order_grouping_flg = $count;
                   $orderGroupingDetail->is_grouped = 1;
				   $orderGroupingDetail->save();
                   $count++;
                }
            }
            else
            {
                dd("Insert Error :");
            }
        });

        
        //  DB::transaction(function()
        // {
        //     $orderGroupingDetails = OrderGroupingDetail::where('order_type',1)->where('pickup_time_id',1)->where('status',0)->get();
           
        //     // \Log::info("ordergroupingdetails".$orderGroupingDetails);
            
        //     if(count($orderGroupingDetails)>0)
        //     {
        //         $total_pickup_quantity = 0 ;
        //         $groupingQuantityArray = [];
        //         $groupingIds = [];
        //         foreach($orderGroupingDetails as $orderGroupingDetail)
        //         {                   
        //             $groupingQuantityArray[] = $orderGroupingDetail->pickup_quantity;
        //             $groupingIds[] =   $orderGroupingDetail->order_grouping_detail_id;
        //         }

        //         $total_pickup_quatity = 0;
        //         for($i=0;$i < count($groupingQuantityArray);$i++)
        //         {
        //             for($j=$i+1;$j< count($groupingQuantityArray);$j++)
        //             {
        //                 $total_pickup_quatity = $groupingQuantityArray[$i] + $groupingQuantityArray[$j];

        //                 if($total_pickup_quatity > 12)
        //                 {
        //                     break;
        //                 }
        //             }
        //             break;
        //         }
        //         \Log::info(json_encode($groupingQuantityArray));
        //         \Log::info(json_encode($groupingIds));
        //         \Log::info(json_encode($total_pickup_quatity));
        //     }
            
        // });
    }
}
