<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\SplitTest;
use App\Models\SplitTestStat;

class SplitTestWinnerChoice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'winner:split-test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Decide who will be the winner according to the criteria';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Get the split test to make decision about winning campaign
        $split_tests = SplitTest::whereNull('winning_campaign_id')
         ->whereNotNull('decision_datetime')
         ->where('decision_datetime', '<=', \Carbon\Carbon::now())->get();

        foreach($split_tests as $split_test) {
          $stat_id = SplitTestStat::whereSplitTestId($split_test->id)->value('id');
          if($split_test->winning_criteria == 'open') {
            $data = SplitTestStat::statLogOpensWinningDecision($stat_id)->get()->toArray();
          } else {
            $data = SplitTestStat::statLogClicksWinningDecision($stat_id)->get()->toArray();
          }

          if(!empty($data)) {
            // Get max value
            $max = max(array_column($data, 'maxi'));
            // Get Max opens broadcast
            foreach($data as $d) {
              if($d['maxi'] == $max) {
                $broadcast = $d['broadcast']; 
                break;
              }
            }

            $broadcast_id = \App\Models\Broadcast::whereName($broadcast)->whereAppId($split_test->app_id)->value('id');
            // Update winning campaign id
            SplitTest::whereId($split_test->id)->update([
              'winning_campaign_id' => $broadcast_id,
              'winning_campaign_name' => $broadcast,
              'status' => 'Resume'
            ]);
          }
        } // end foreach
    }
}
