<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\CarShowWinner;
use App\Models\PeoplesChoice;
use App\Models\VehicleScores;
use Illuminate\Support\Facades\DB;

class TabulateWinners extends Command
{
    protected $signature = 'carshow:tabulatewinners';
    protected $description = 'Tabulate Show Winners. Year Category 1st places can overlap with Best in Show/People\'s Choice.';

    public function handle()
    {
        CarShowWinner::truncate();

        $this->info('Starting tabulation...');

        // 2. BEST IN SHOW (Category 6)
        $this->recordJudgedWinners(6, 'first', null, null, true);

        // 3. PEOPLE'S CHOICE (Category 3)
        $this->recordPeoplesChoiceWinners(3, 'first');

        // 4. YEAR CATEGORIES
        $yearConfigs = [
            ['id' => 17, 'name' => '0-1942',      'start' => 0,    'end' => 1942],
            ['id' => 18, 'name' => '1943-1969',   'start' => 1943, 'end' => 1969],
            ['id' => 20, 'name' => '1970-2000',   'start' => 1970, 'end' => 2000],
            ['id' => 19, 'name' => '2001-Current', 'start' => 2001, 'end' => 2026],
        ];

        foreach ($yearConfigs as $config) {
            $this->info("Processing Category: {$config['name']}");
            $this->recordJudgedWinners($config['id'], 'first', $config['start'], $config['end'], false);
            $this->recordJudgedWinners($config['id'], 'second', $config['start'], $config['end'], true);
            $this->recordJudgedWinners($config['id'], 'third', $config['start'], $config['end'], true);
            $this->recordJudgedWinners($config['id'], 'fourth', $config['start'], $config['end'], true);
            $this->recordJudgedWinners($config['id'], 'fifth', $config['start'], $config['end'], true);
        }

        $this->info('Winners tabulated successfully.');
    }

    private function recordJudgedWinners($categoryId, $place, $startYear = null, $endYear = null, $excludeExisting = true)
    {
        $query = VehicleScores::join('vehicles', 'vehicle_scores.vehicle', '=', 'vehicles.id')
            ->where('vehicles.doNotJudge', 0);

        if ($excludeExisting) {
            $query->whereNotIn('vehicle_scores.vehicle', function ($q) {
                $q->select('vehicle')->from('car_show_winners');
            });
        }

        if ($startYear !== null) $query->where('vehicles.year', '>=', $startYear);
        if ($endYear !== null) $query->where('vehicles.year', '<=', $endYear);

        $maxScore = (clone $query)
            ->groupBy('vehicles.id')
            ->selectRaw('sum(vehicle_scores.overall_score) as totalscore')
            ->orderBy('totalscore', 'desc')
            ->value('totalscore');

        if ($maxScore) {
            $winners = $query->selectRaw('vehicles.id as vehicle_id, sum(vehicle_scores.overall_score) as totalscore')
                ->groupBy('vehicles.id')
                ->having('totalscore', '=', $maxScore)
                ->get();

            foreach ($winners as $winner) {
                CarShowWinner::updateOrCreate([
                    'category' => $categoryId,
                    'place'    => $place,
                    'vehicle'  => $winner->vehicle_id
                ], [
                    // Added totalscore here
                    'total_score' => $winner->totalscore 
                ]);
            }
        }
    }

    private function recordPeoplesChoiceWinners($categoryId, $place)
    {
        $maxVotes = PeoplesChoice::join('vehicles', 'peoples_choice.vehicle', '=', 'vehicles.id')
            ->where('vehicles.doNotJudge', 0)
            ->whereNotIn('peoples_choice.vehicle', function ($q) {
                $q->select('vehicle')->from('car_show_winners');
            })
            ->groupBy('peoples_choice.vehicle')
            ->selectRaw('sum(pc_count) as totalvotes')
            ->orderBy('totalvotes', 'desc')
            ->value('totalvotes');

        if ($maxVotes) {
            $winners = PeoplesChoice::join('vehicles', 'peoples_choice.vehicle', '=', 'vehicles.id')
                ->selectRaw('peoples_choice.vehicle as vehicle_id, sum(pc_count) as totalvotes')
                ->where('vehicles.doNotJudge', 0)
                ->whereNotIn('peoples_choice.vehicle', function ($q) {
                    $q->select('vehicle')->from('car_show_winners');
                })
                ->groupBy('peoples_choice.vehicle')
                ->having('totalvotes', '=', $maxVotes)
                ->get();

            foreach ($winners as $winner) {
                CarShowWinner::create([
                    'category' => $categoryId,
                    'place'    => $place,
                    'vehicle'  => $winner->vehicle_id,
                    // Added totalvotes here
                    'total_score'    => $winner->totalvotes 
                ]);
            }
        }
    }
}