<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Suiterus\Adg\Models\SPMS\PerformanceEvaluation;

class CalculateMfoAverages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'calculate:mfo-averages';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Compute MFO averages';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $mfos = PerformanceEvaluation::all();
        foreach ($mfos as $mfo) {
            $mfoRateQ = 0.00;
            $countQ = 0;
            $mfoRateE = 0.00;
            $countE = 0;
            $mfoRateT = 0.00;
            $countT = 0;
            $mfoAverage = 0.00;
            $count = 0;

            foreach ($mfo->metricEvaluations as $metric_evaluation) {
                if (!is_null($metric_evaluation->average)) {
                    $mfoAverage += $metric_evaluation->average;
                }
                if (!is_null($metric_evaluation->rate_q)) {
                    $mfoRateQ += $metric_evaluation->rate_q;
                    $countQ++;
                }
                if (!is_null($metric_evaluation->rate_e)) {
                    $mfoRateE += $metric_evaluation->rate_e;
                    $countE++;
                }
                if (!is_null($metric_evaluation->rate_t)) {
                    $mfoRateT += $metric_evaluation->rate_t;
                    $countT++;
                }

                $count++;
            }

            $mfoRateQ = ($countQ > 0) ? $mfoRateQ / $countQ : null;
            $mfoRateE = ($countE > 0) ? $mfoRateE / $countE : null;
            $mfoRateT = ($countT > 0) ? $mfoRateT / $countT : null;
            $mfoAverage = ($count > 0) ? $mfoAverage / $count : null;

            $mfo->update([
                'rate_q_ave' => $mfoRateQ,
                'rate_e_ave' => $mfoRateE,
                'rate_t_ave' => $mfoRateT,
                'average' => $mfoAverage,
            ]);
        }
        return 0;
    }
}
