<?php

namespace App\Models;

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

class UserLanguage extends Model
{
    use HasFactory;

    protected $primaryKey = 'user_language_id';

    protected $fillable = [
        'user_id',
        'language_code',
        'proficiency',
        'is_primary'
    ];

    protected $casts = [
        'is_primary' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

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

    /**
     * Get the language that owns the user language.
     */
    public function language()
    {
        return $this->belongsTo(Language::class, 'language_code', 'language_code');
    }

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

    /**
     * Scope primary languages
     */
    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    /**
     * Scope by proficiency level
     */
    public function scopeByProficiency($query, $proficiency)
    {
        return $query->where('proficiency', $proficiency);
    }

    /**
     * Scope by language code
     */
    public function scopeByLanguageCode($query, $languageCode)
    {
        return $query->where('language_code', $languageCode);
    }

    /**
     * Set as primary language and unset others
     */
    public function setAsPrimary()
    {
        // Unset other primary languages for this user
        self::where('user_id', $this->user_id)
            ->where('is_primary', true)
            ->update(['is_primary' => false]);

        // Set this as primary
        $this->update(['is_primary' => true]);
    }

    /**
     * Check if user has specific language
     */
    public static function userHasLanguage($userId, $languageCode)
    {
        return self::where('user_id', $userId)
            ->where('language_code', $languageCode)
            ->exists();
    }

    /**
     * Get user's primary language
     */
    public static function getPrimaryLanguage($userId)
    {
        return self::with('language')
            ->where('user_id', $userId)
            ->where('is_primary', true)
            ->first();
    }

    /**
     * Get proficiency options with labels
     */
    public static function getProficiencyOptions()
    {
        return [
            'basic' => 'Basic',
            'intermediate' => 'Intermediate',
            'fluent' => 'Fluent',
            'native' => 'Native'
        ];
    }

    /**
     * Get proficiency label
     */
    public function getProficiencyLabelAttribute()
    {
        $options = self::getProficiencyOptions();
        return $options[$this->proficiency] ?? $this->proficiency;
    }
}
