<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Poll extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id',
        'title',
        'options',
        'image',
        'description',
        'allow_multiple_votes',
        'show_results_after_vote',
        'total_votes',
        'ends_at',
        'status',
        'published_at',
    ];

    protected $casts = [
        'options' => 'array',
        'allow_multiple_votes' => 'boolean',
        'show_results_after_vote' => 'boolean',
        'ends_at' => 'datetime',
        'published_at' => 'datetime',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

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

    public function getResultsAttribute()
    {
        $results = [];
        $total = $this->total_votes;
        
        foreach ($this->options as $index => $option) {
            $votes = $this->votes()->whereJsonContains('selected_options', $index)->count();
            $percentage = $total > 0 ? ($votes / $total) * 100 : 0;
            
            $results[] = [
                'option' => $option,
                'votes' => $votes,
                'percentage' => round($percentage, 2),
            ];
        }
        
        return $results;
    }
}

