<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Poll extends Model
{
    protected $fillable = [
        'question',
        'options',
        'type',
        'football_match_id',
        'is_active',
        'poll_date',
        'manual_votes',     // JSON: {"0": 150, "1": 80} — admin-set boost
    ];

    protected function casts(): array
    {
        return [
            'options'      => 'array',
            'manual_votes' => 'array',
            'is_active'    => 'boolean',
            'poll_date'    => 'date',
        ];
    }

    public function footballMatch(): BelongsTo
    {
        return $this->belongsTo(FootballMatch::class, 'football_match_id');
    }

    public function votes(): HasMany
    {
        return $this->hasMany(PollVote::class);
    }

    /**
     * Returns merged vote counts: real votes + manual_votes boost.
     * Keys are option indexes (0, 1, 2…).
     * This is the single source of truth used everywhere.
     */
    public function getMergedVoteCounts(): array
    {
        // Real votes from poll_votes table
        $real = $this->votes()
            ->selectRaw('option_index, COUNT(*) as total')
            ->groupBy('option_index')
            ->pluck('total', 'option_index')
            ->toArray();

        // Manual boost from admin
        $manual = $this->manual_votes ?? [];

        // Merge: sum real + manual for each option index
        $merged = [];
        $count  = count($this->options);
        for ($i = 0; $i < $count; $i++) {
            $merged[$i] = ($real[$i] ?? 0) + ($manual[$i] ?? 0);
        }

        return $merged;
    }
}
