<?php

namespace App\Livewire\Settings;

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

class CategoryAccountingConfig extends Component
{
    public $categories;
    public $incomeAccounts;
    public $cogsAccounts;

    public $categoryAccounts = [];

    protected $rules = [
        'categoryAccounts.*.income_account_id' => 'nullable|exists:accounts,id',
        'categoryAccounts.*.cogs_account_id' => 'nullable|exists:accounts,id',
    ];

    public function mount()
    {
        $this->categories = Category::all();
        // Fetch Revenue accounts (Type: revenue)
        $this->incomeAccounts = Account::where('type', 'revenue')->orderBy('code')->get();
        // Fetch Expense accounts (Type: expense) - specifically COGS related if possible, but all expenses for flexibility
        $this->cogsAccounts = Account::where('type', 'expense')->orderBy('code')->get();

        foreach ($this->categories as $category) {
            $this->categoryAccounts[$category->id] = [
                'income_account_id' => $category->income_account_id,
                'cogs_account_id' => $category->cogs_account_id,
            ];
        }
    }

    public function save()
    {
        $this->validate();

        foreach ($this->categoryAccounts as $categoryId => $accounts) {
            Category::where('id', $categoryId)->update([
                'income_account_id' => $accounts['income_account_id'] ?: null,
                'cogs_account_id' => $accounts['cogs_account_id'] ?: null,
            ]);
        }

        session()->flash('message', __('Category accounting settings updated successfully.'));
    }

    public function render()
    {
        return view('livewire.settings.category-accounting-config');
    }
}
