<?php

namespace App\Models;

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

class Setting extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_name',
        'company_address',
        'company_phone',
        'company_email',
        'company_logo',
        'currency_symbol',
        'financial_year_start',
        'current_year_start',
        'current_year_end',
        'decimal_places',
        'show_zero_balance',
    ];

    protected $casts = [
        'current_year_start' => 'date',
        'current_year_end' => 'date',
        'show_zero_balance' => 'boolean',
    ];

    /**
     * Get the setting instance (singleton pattern)
     */
    public static function instance(): self
    {
        $setting = self::first();
        
        if (!$setting) {
            $setting = self::create([
                'company_name' => 'My Company',
                'currency_symbol' => 'Rs.',
                'financial_year_start' => '07-01',
                'current_year_start' => now()->month >= 7 
                    ? now()->startOfYear()->addMonths(6)->startOfMonth() 
                    : now()->subYear()->startOfYear()->addMonths(6)->startOfMonth(),
                'current_year_end' => now()->month >= 7 
                    ? now()->addYear()->startOfYear()->addMonths(5)->endOfMonth() 
                    : now()->startOfYear()->addMonths(5)->endOfMonth(),
            ]);
        }
        
        return $setting;
    }

    /**
     * Get a setting value by key
     */
    public static function get(string $key, $default = null)
    {
        $setting = self::instance();
        return $setting->$key ?? $default;
    }
}
