<?php

namespace App\Listeners;

use App\Events\UpdateOrderPackageExceptionListenerEvent;
use App\OrderPackage;
use App\Services\OrderPackageExceptionTypeCountingRecordService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\DB;

class UpdateOrderPackageExceptionTypeCountingRecordListener implements ShouldQueue
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param UpdateOrderPackageExceptionListenerEvent $event
     * @return void
     */
    public function handle(UpdateOrderPackageExceptionListenerEvent $event)
    {
        $order_package_ids = $event->order_package_ids;
        $dates = OrderPackage::query()->select(DB::raw("DATE_FORMAT( sent_at, '%Y-%m-%d' ) AS sent_at_date "))->whereIn('id', $order_package_ids)->get();
        /**
         * @var $service OrderPackageExceptionTypeCountingRecordService
         */
        $service = app('OrderPackageExceptionTypeCountingRecordService');
        foreach ($dates as $date) {
            $service->updateOrCreateByDate($date->sent_at_date);
        }
    }
}
