<?php

namespace App\Models;

use CodeIgniter\Model;

class CompanySettingsModel extends Model
{
    protected $table         = 'company_settings';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'name',
        'legal_name',
        'logo_path',
        'currency_code',
        'currency_symbol',
        'decimal_places',
        'address',
        'city',
        'country',
        'postal_code',
        'phone',
        'email',
        'website',
        'tax_id',
        'commercial_registration',
        'timezone',
        'locale',
        'date_format',
        'fiscal_year_start_month',
        'tpin_enabled',
        'tpin_required_by_default',
        'tpin_max_failed_attempts',
        'tpin_lockout_minutes',
    ];

    /**
     * Returns the singleton company settings row, creating defaults if missing.
     */
    public function getSettings(): array
    {
        $row = $this->first();

        if ($row) {
            return $row;
        }

        $now = date('Y-m-d H:i:s');
        $this->insert([
            'name'                    => 'My Company',
            'legal_name'              => 'My Company W.L.L.',
            'currency_code'           => 'BHD',
            'currency_symbol'         => 'BD',
            'decimal_places'          => 3,
            'country'                 => 'Bahrain',
            'timezone'                => 'Asia/Bahrain',
            'locale'                  => 'en_BH',
            'date_format'             => 'd/m/Y',
            'fiscal_year_start_month' => 1,
            'tpin_enabled'            => 1,
            'tpin_required_by_default'=> 0,
            'tpin_max_failed_attempts'=> 5,
            'tpin_lockout_minutes'    => 15,
            'created_at'              => $now,
            'updated_at'              => $now,
        ]);

        return $this->first();
    }
}
