<?php

namespace App\Console\Commands;

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

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

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

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // return 0;
        
        DB::transaction(function()
        {
            
            $orderGroupingDetails = OrderGroupingDetail::select('pickup_location_id','pickup_date','pickup_time_id','order_type','order_grouping_flg')->selectRaw("SUM(pickup_quantity) as pickup_quantity")->selectRaw("SUM(order_count) as order_count")->selectRaw("SUM(merchant_cost) as merchant_cost")->selectRaw("COUNT(order_grouping_detail_id) as pickup_address_count")->where('is_grouped',1)->groupBy('pickup_location_id','pickup_date','pickup_time_id','order_type','order_grouping_flg')->orderBy('order_grouping_flg')->get();

            if(count($orderGroupingDetails) > 0)
            {  
                foreach($orderGroupingDetails as $orderGroupingDetail)
                {

                   $orderGrouping = OrderGrouping::createOrderGrouping($orderGroupingDetail);
                }
            }
        });
        DB::transaction(function()
        {
            $orderGroupingDetails = OrderGroupingDetail::get();
            //\Log::info("orderGroupingDetails".$orderGroupingDetails);

            if(count($orderGroupingDetails) > 0)
            {  
                foreach($orderGroupingDetails as $orderGroupingDetail)
                {

                   $orderGrouping = OrderSchedule::updateOrderGroupingFlg($orderGroupingDetail);
                   
                }
            }
        });
    }
}
