<?php

namespace App\Models;

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

class UserLocale extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'locale_id',
    ];

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

    public function locale()
    {
        return $this->belongsTo(Locale::class);
    }

    // Scopes
    public function scopeByUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    public function scopeByLocale($query, $localeId)
    {
        return $query->where('locale_id', $localeId);
    }

    // Helper Methods
    public static function setUserLocale($userId, $localeId)
    {
        return static::updateOrCreate(
            ['user_id' => $userId],
            ['locale_id' => $localeId]
        );
    }

    /**
     * Get user's saved locale with all relations loaded
     * Returns UserLocale object (not just locale)
     */
    public static function getUserLocaleWithRelations($userId)
    {
        try {
            return static::where('user_id', $userId)
                        ->with([
                            'locale' => function ($query) {
                                $query->with(['country', 'language']);
                            }
                        ])
                        ->first();
        } catch (\Exception $e) {
            \Log::error('Error getting user locale with relations', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * Get user's locale object only (safe method)
     */
    public static function getUserLocale($userId)
    {
        try {
            $userLocale = static::getUserLocaleWithRelations($userId);
            return $userLocale?->locale;
        } catch (\Exception $e) {
            \Log::error('Error getting user locale', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * Check if user has saved locale
     */
    public static function userHasLocale($userId)
    {
        try {
            return static::where('user_id', $userId)->exists();
        } catch (\Exception $e) {
            \Log::error('Error checking if user has locale', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     * Get user's country and language IDs safely
     */
    public static function getUserLocaleIds($userId)
    {
        try {
            $userLocale = static::getUserLocaleWithRelations($userId);
            
            if (!$userLocale || !$userLocale->locale) {
                return null;
            }

            return [
                'locale_id' => $userLocale->locale->id,
                'country_id' => $userLocale->locale->country_id,
                'language_id' => $userLocale->locale->language_id,
            ];
        } catch (\Exception $e) {
            \Log::error('Error getting user locale IDs', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * Safe method to delete user locale
     */
    public static function deleteUserLocale($userId)
    {
        try {
            return static::where('user_id', $userId)->delete();
        } catch (\Exception $e) {
            \Log::error('Error deleting user locale', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
}