<?php

namespace App\Models;

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

class UserSetting extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $fillable = [
        'user_id',
        'default_currency_id',
        'theme',
        'locale',
        'timezone',
        'date_format',
        'first_day_of_week',
        'email_notifications',
        'budget_alerts',
        'bill_reminders',
        'weekly_summary',
        'monthly_summary',
    ];

    /**
     * The attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_notifications' => 'boolean',
            'budget_alerts' => 'boolean',
            'bill_reminders' => 'boolean',
            'weekly_summary' => 'boolean',
            'monthly_summary' => 'boolean',
        ];
    }

    /**
     * Get the user that owns these settings.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the default currency.
     */
    public function defaultCurrency(): BelongsTo
    {
        return $this->belongsTo(Currency::class, 'default_currency_id');
    }

    /**
     * Get or create settings for a user.
     */
    public static function getOrCreate(int $userId): self
    {
        return self::firstOrCreate(
            ['user_id' => $userId],
            [
                'default_currency_id' => Currency::where('code', 'IDR')->first()?->id,
                'theme' => 'system',
                'locale' => 'en',
                'timezone' => 'Asia/Jakarta',
                'date_format' => 'd/m/Y',
                'first_day_of_week' => 'monday',
            ]
        );
    }

    /**
     * Format a date according to user's preference.
     */
    public function formatDate(\DateTimeInterface $date): string
    {
        return $date->format($this->date_format);
    }
}
