<?php

namespace App\Livewire\Settings;

use App\Models\Account;
use App\Models\Setting;
use Livewire\Component;

class AccountingSettings extends Component
{
    // Account Codes
    public string $account_cash_drawer = '';
    public string $account_cash_on_hand = '';
    public string $account_bank = '';
    public string $account_receivable = '';
    public string $account_inventory = '';
    public string $account_intermediate_sales = '';
    public string $account_payable = '';
    public string $account_sales_revenue = '';
    public string $account_cogs = '';
    public string $account_cash_overage = '';
    public string $account_cash_shortage = '';
    
    // Hardcoded defaults from AccountingService (for fallback)
    const DEFAULTS = [
        'account_cash_drawer' => '1110',
        'account_cash_on_hand' => '1100',
        'account_bank' => '1200',
        'account_receivable' => '1300',
        'account_inventory' => '1400',
        'account_intermediate_sales' => '1500',
        'account_payable' => '2100',
        'account_sales_revenue' => '4100',
        'account_cogs' => '5100',
        'account_cash_overage' => '4900',
        'account_cash_shortage' => '5900',
    ];

    public function mount()
    {
        foreach (self::DEFAULTS as $key => $default) {
            $this->$key = Setting::get($key, $default);
        }
    }

    public function save()
    {
        $this->validate([
            'account_cash_drawer' => 'required|exists:accounts,code',
            'account_cash_on_hand' => 'required|exists:accounts,code',
            'account_bank' => 'required|exists:accounts,code',
            'account_receivable' => 'required|exists:accounts,code',
            'account_inventory' => 'required|exists:accounts,code',
            'account_intermediate_sales' => 'required|exists:accounts,code',
            'account_payable' => 'required|exists:accounts,code',
            'account_sales_revenue' => 'required|exists:accounts,code',
            'account_cogs' => 'required|exists:accounts,code',
            'account_cash_overage' => 'required|exists:accounts,code',
            'account_cash_shortage' => 'required|exists:accounts,code',
        ]);

        foreach (self::DEFAULTS as $key => $default) {
            Setting::set($key, $this->$key);
        }

        session()->flash('success', __('Accounting settings updated successfully.'));
    }

    public function render()
    {
        $accounts = Account::active()->orderBy('code')->get();

        return view('livewire.settings.accounting-settings', [
            'accounts' => $accounts,
        ]);
    }
}
