<?php

namespace App\Listeners;

use App\Events\ResetProcessStatisticStartDateEvent;
use App\Process;
use App\ProcessStatistic;
use Carbon\Carbon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Queue\InteractsWithQueue;

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

    /**
     * Handle the event.
     *
     * @param  ResetProcessStatisticStartDateEvent  $event
     * @return void
     */
    public function handle(ResetProcessStatisticStartDateEvent $event)
    {
        $process = $event->process;
        $process->load(["processDailies"=>function($query){
            /** @var Builder $query */
            $query->orderBy("date")->withCount(["processDailyParticipants"]);
        },"processStatistic"=>function($query){
            /** @var Builder $query */
            $query->select("process_id","started_at");
        }]);

        $dailies = $process->processDailies ?? false;
        if ($dailies){
            foreach ($dailies as $daily){
                if ($daily->process_daily_participants_count > 0){
                    $this->comparisonReplace($process->processStatistic,$daily->date." 09:00:00");
                    return;
                }
            }
        }
        $this->comparisonReplace($process->processStatistic,null);
    }

    private function comparisonReplace($statistic, $date)
    {
        if ($statistic && $statistic->started_at != $date){
            ProcessStatistic::query()->where("process_id",$statistic->process_id)->update(["started_at"=>$date]);
        }
    }
}
