<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Model: RPollOption (Poll Answer Option)
 * 
 * Represents an answer option for a poll.
 * 
 * @property int $id
 * @property int $poll_id
 * @property string $option_text
 * @property string|null $description
 * @property int $sort_order
 * @property string|null $color
 * @property int $votes_count
 * @property bool $is_other
 */
class RPollOption extends Model
{
    use HasFactory;

    protected $table = 'r_poll_options';

    protected $fillable = [
        'poll_id',
        'option_text',
        'description',
        'sort_order',
        'color',
        'votes_count',
        'is_other',
    ];

    protected $casts = [
        'sort_order' => 'integer',
        'votes_count' => 'integer',
        'is_other' => 'boolean',
    ];

    /**
     * Default colors for poll options.
     */
    const DEFAULT_COLORS = [
        '#10B981', // green
        '#3B82F6', // blue
        '#F59E0B', // yellow
        '#EF4444', // red
        '#8B5CF6', // purple
        '#EC4899', // pink
        '#06B6D4', // cyan
        '#F97316', // orange
    ];

    /**
     * Get the poll this option belongs to.
     */
    public function poll(): BelongsTo
    {
        return $this->belongsTo(RPoll::class, 'poll_id');
    }

    /**
     * Increment vote count.
     */
    public function incrementVote(): void
    {
        $this->increment('votes_count');
    }

    /**
     * Get vote percentage.
     */
    public function getPercentageAttribute(): float
    {
        $total = $this->poll->total_votes ?? 0;
        
        if ($total === 0) {
            return 0;
        }

        return round(($this->votes_count / $total) * 100, 1);
    }

    /**
     * Get color or default.
     */
    public function getColorOrDefaultAttribute(): string
    {
        if ($this->color) {
            return $this->color;
        }

        $index = $this->sort_order % count(self::DEFAULT_COLORS);
        return self::DEFAULT_COLORS[$index];
    }
}
