<?php

namespace App\Models;

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

class SurveyResponse extends Model
{
    use HasFactory;

    protected $fillable = [
        'survey_id',
        'user_id',
        'answers',
        'submitted_at',
        // Demographic fields — filled by public (non-member) respondents
        'respondent_name',
        'respondent_title',
        'respondent_company',
        'respondent_gender',
        'respondent_age',
        'ip_address',
    ];

    protected $casts = [
        'answers'         => 'array',
        'submitted_at'    => 'datetime',
        'respondent_age'  => 'integer',
    ];

    // ── Helpers ────────────────────────────────────────────────

    /**
     * Display name — member name if logged in, respondent_name if public,
     * fallback to 'Anonymous'.
     */
    public function getDisplayNameAttribute(): string
    {
        if ($this->user) {
            return $this->user->name;
        }
        return $this->respondent_name ?? 'Anonymous';
    }

    public function isAnonymous(): bool
    {
        return is_null($this->user_id) && is_null($this->respondent_name);
    }

    // ── Relationships ──────────────────────────────────────────
    public function survey(): BelongsTo
    {
        return $this->belongsTo(Survey::class);
    }

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