<?php

namespace App\Models;

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

class Survey extends Model
{
    use HasFactory;

    // ── Fillable ───────────────────────────────────────────────
    protected $fillable = [
        'created_by',
        'title_en',
        'title_ar',
        'description_en',
        'description_ar',
        'language',
        'audience',
        'hub_id',
        'anonymous_responses',
        'show_results_to_members',
        'closes_at',
        'status',
        'response_count',
        'link_token',
    ];

    // ── Casts ─────────────────────────────────────────────────
    protected $casts = [
        'anonymous_responses'      => 'boolean',
        'show_results_to_members'  => 'boolean',
        'closes_at'                => 'datetime',
        'response_count'           => 'integer',
    ];

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

    public function getTitleAttribute(): string
    {
        return app()->getLocale() === 'ar'
            ? ($this->title_ar ?? $this->title_en)
            : $this->title_en;
    }

    public function getDescriptionAttribute(): ?string
    {
        return app()->getLocale() === 'ar'
            ? ($this->description_ar ?? $this->description_en)
            : $this->description_en;
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    public function isExpired(): bool
    {
        return $this->closes_at && $this->closes_at->isPast();
    }

    // ── Scopes ────────────────────────────────────────────────

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('status', 'active');
    }

    // ── Relationships ─────────────────────────────────────────

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

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

    public function questions(): HasMany
    {
        return $this->hasMany(SurveyQuestion::class)->orderBy('sort_order');
    }

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

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