<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\FinancialCategory;
use App\Models\FinancialTreasury;
use Illuminate\Http\Request;

class AccountingSettingsController extends Controller
{
    public function index()
    {
        $treasuries = FinancialTreasury::all();
        $incomeCategories = FinancialCategory::where('type', 'income')->get();
        $expenseCategories = FinancialCategory::where('type', 'expense')->get();

        return view('accounting.settings.index', compact('treasuries', 'incomeCategories', 'expenseCategories'));
    }

    public function storeCategory(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:income,expense',
            'description' => 'nullable|string',
        ]);

        FinancialCategory::create($validated);

        return back()->with('success', 'Category created successfully.');
    }

    public function updateCategory(Request $request, FinancialCategory $category)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);

        $category->update($validated);

        return back()->with('success', 'Category updated successfully.');
    }

    public function destroyCategory(FinancialCategory $category)
    {
        // Check if category has transactions
        if ($category->transactions()->exists()) {
            return back()->with('error', 'Cannot delete category with associated transactions.');
        }

        $category->delete();

        return back()->with('success', 'Category deleted successfully.');
    }

    public function updateClosing(Request $request)
    {
        $request->validate([
            'lock_date' => 'required|date',
        ]);

        Setting::setValue('general', 'accounting_lock_date', $request->lock_date);

        return back()->with('success', __('Accounting lock date updated successfully.'));
    }
}
