<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CompanySetting extends Model
{
    protected $fillable = [
        'company_name',
        'company_email',
        'company_phone',
        'company_fax',
        'company_address',
        'company_city',
        'company_state',
        'company_zip',
        'company_country',
        'company_tax_id',
        'company_registration_number',
        'company_logo',
        'company_favicon',
        'company_icon',
        'company_icon_collapsed',
        'company_notes',
    ];

    /**
     * Get the company settings (singleton)
     */
    public static function getSettings(): self
    {
        return static::firstOrCreate([], [
            'company_name' => config('app.name', 'ProInvoice'),
        ]);
    }

    /**
     * Active document template key from the primary company_settings row (invoice, quotation, receipt).
     * Matches what the invoice view / PDF should use; avoids hardcoding settings row id = 1.
     */
    public static function getDocumentDefaultTemplateKey(string $type): string
    {
        $type = in_array($type, ['invoice', 'quotation', 'receipt'], true) ? $type : 'invoice';
        $column = $type.'_default_template';

        try {
            $settings = static::query()->orderBy('id')->first();
            if ($settings !== null) {
                $key = $settings->{$column} ?? null;
                if (is_string($key) && $key !== '') {
                    return $key;
                }
            }
        } catch (\Throwable) {
        }

        $fromConfig = config('invoice.'.$column);
        if (is_string($fromConfig) && $fromConfig !== '') {
            return $fromConfig;
        }

        return 'modern';
    }
}
