<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Hash;

/**
 * Model: RPollResponse (Poll Vote/Response)
 * 
 * Represents a user or guest response to a poll.
 * Supports duplicate prevention through hashing.
 * 
 * @property int $id
 * @property int $poll_id
 * @property int $option_id
 * @property int|null $user_id
 * @property string|null $respondent_hash
 * @property string|null $other_text
 * @property string|null $ip_address
 * @property string|null $user_agent
 */
class RPollResponse extends Model
{
    use HasFactory;

    protected $table = 'r_poll_responses';

    protected $fillable = [
        'poll_id',
        'option_id',
        'user_id',
        'respondent_hash',
        'other_text',
        'ip_address',
        'user_agent',
    ];

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

    /**
     * Get the selected option.
     */
    public function option(): BelongsTo
    {
        return $this->belongsTo(RPollOption::class, 'option_id');
    }

    /**
     * Get the user (if registered).
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Generate respondent hash for guest tracking.
     */
    public static function generateHash(string $ipAddress, string $userAgent): string
    {
        return Hash::make($ipAddress . $userAgent . config('app.key'));
    }

    /**
     * Check if this is an "other" response.
     */
    public function isOtherResponse(): bool
    {
        return $this->option && $this->option->is_other;
    }

    /**
     * Scope: Responses by user.
     */
    public function scopeByUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Scope: Responses by hash (guest).
     */
    public function scopeByHash($query, string $hash)
    {
        return $query->where('respondent_hash', $hash);
    }
}
