<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class Setting extends Model
{
    protected $fillable = ['company_id','key','value'];

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public static function get(int $companyId, string $key, $default = null)
    {
        $cacheKey = "settings_{$companyId}_{$key}";
        $sentinel = '__NOT_FOUND__';
        $cached = Cache::remember($cacheKey, 3600, function () use ($companyId, $key, $sentinel) {
            $value = static::where('company_id', $companyId)->where('key', $key)->value('value');
            return $value ?? $sentinel;
        });
        return ($cached === $sentinel) ? $default : $cached;
    }

    public static function set(int $companyId, string $key, $value): void
    {
        static::updateOrCreate(
            ['company_id' => $companyId, 'key' => $key],
            ['value' => $value]
        );
        Cache::forget("settings_{$companyId}_{$key}");
    }

    public static function forgetAll(int $companyId): void
    {
        foreach (array_keys(static::defaults()) as $key) {
            Cache::forget("settings_{$companyId}_{$key}");
        }
    }

    public static function defaults(): array
    {
        return [
            // ── General ───────────────────────────────────────────────────────
            'fiscal_year_start_month'    => '1',
            'timezone'                   => 'UTC',
            'date_format'                => 'DD/MM/YYYY',
            'currency_code'              => 'USD',
            'currency_symbol'            => '$',
            'amount_decimals'            => '2',
            'qty_decimals'               => '2',
            'rate_decimals'              => '4',
            'thousand_separator'         => ',',
            'amount_in_words_language'   => 'en',
            'max_attachment_size_kb'     => '10240',
            'autosave_interval_seconds'  => '120',

            // Beep sound
            'beep_on_save'               => '1',

            // Voucher Signatory
            'signatory_prepared_by'      => 'Prepared By',
            'signatory_checked_by'       => 'Checked By',
            'signatory_custom1'          => '',
            'signatory_custom2'          => '',
            'signatory_approved_by'      => 'Approved By',

            // SMTP
            'smtp_host'                  => '',
            'smtp_port'                  => '587',
            'smtp_username'              => '',
            'smtp_password'              => '',
            'smtp_from_name'             => '',
            'smtp_from_email'            => '',
            'smtp_encryption'            => 'tls',

            // ── Accounting ────────────────────────────────────────────────────
            'books_closing_date'           => '',
            'books_closing_password'       => '',
            'allow_prior_period_posting'   => '0',
            'prior_period_warning'         => '1',
            'voucher_approval_required'    => '1',
            'allow_negative_cash_bank'     => '0',
            'use_multi_currency'           => '0',
            'use_cheque_printing'          => '0',
            'use_cheque_register'          => '0',
            'use_fixed_assets_module'      => '0',

            // ── Inventory ─────────────────────────────────────────────────────
            'allow_negative_inventory'   => '0',
            'use_multi_warehouse'        => '0',
            'use_manufacturing'          => '0',
            'use_serial_number'          => '0',
            'use_lot_number'             => '0',
            'use_fifo_valuation'         => '0',
            'stock_valuation_method'     => 'weighted_average',

            // ── AR & AP ───────────────────────────────────────────────────────
            'price_level_enabled'        => '0',
            'customer_aging_basis'       => 'invoice_date',
            'vendor_aging_basis'         => 'bill_date',

            // ── Payroll ───────────────────────────────────────────────────────
            'use_payroll_module'                 => '0',
            'payroll_tax_numerator'              => '1',
            'payroll_tax_denominator'            => '3',
            'payroll_tax_max_exempt'             => '450000',
            'payroll_tax_slabs'                  => '', // filled via defaultPayrollTaxSlabs()
            'payroll_investment_pct'             => '3',
            'payroll_investment_max'             => '1000000',
            'payroll_investment_rebate_rate'     => '15',
            'salary_transfer_letter_header'      => '', // filled via defaultSalaryTransferLetterHeader()
            'salary_transfer_letter_footer'      => '', // filled via defaultSalaryTransferLetterFooter()
        ];
    }

    public static function defaultPayrollTaxSlabs(): string
    {
        return json_encode([
            ['label' => 'First', 'currency' => 'BDT', 'amount' => '375000', 'rate' => '0'],
            ['label' => 'Next',  'currency' => 'BDT', 'amount' => '300000', 'rate' => '10'],
            ['label' => 'Next',  'currency' => 'BDT', 'amount' => '400000', 'rate' => '15'],
            ['label' => 'Next',  'currency' => 'BDT', 'amount' => '500000', 'rate' => '20'],
            ['label' => 'Next',  'currency' => 'BDT', 'amount' => '2000000', 'rate' => '25'],
            ['label' => 'Rest',  'currency' => 'BDT', 'amount' => 'rest', 'rate' => '30'],
        ]);
    }

    public static function defaultSalaryTransferLetterHeader(): string
    {
        return '<p>To</p>'
            . '<p>The Manager<br>Dhaka Bank Limited<br>Gulshan Branch<br>Gulshan-1, Dhaka-1212.</p>'
            . '<p><br></p>'
            . '<p><strong>Subject: Request to Transfer the Salary</strong></p>'
            . '<p><br></p>'
            . '<p>Please Transfer the Salary of as per the following list. Please Debit our Current Bank Account Number 983274544 we are maintaining with your Bank and Credit the following recipients bank accounts:</p>';
    }

    public static function defaultSalaryTransferLetterFooter(): string
    {
        return '<p>Your action would be highly appreciated in this regard.</p>'
            . '<p><br></p>'
            . '<p>Thanking You,</p>'
            . '<p><br></p>'
            . '<p>-----------------------&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-----------------------</p>'
            . '<p>Managing Director&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Director Finance</p>';
    }

    public static function payrollSetting(string $key, $stored = null)
    {
        return match ($key) {
            'payroll_tax_slabs'             => $stored ?: static::defaultPayrollTaxSlabs(),
            'salary_transfer_letter_header' => $stored ?: static::defaultSalaryTransferLetterHeader(),
            'salary_transfer_letter_footer' => $stored ?: static::defaultSalaryTransferLetterFooter(),
            default                         => $stored,
        };
    }
}
