<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\Accounting\ExpenseItem;
use App\Models\Accounting\AccountingHead;
use Illuminate\Http\Request;

class ExpenseItemController extends Controller
{
    public function index()
    {
        $items = ExpenseItem::with('expenseHead')->get();
        return view('pages.accounting.expense-item.index', compact('items'));
    }

    public function create()
    {
        $expenseHeads = AccountingHead::where('type', 'expense')->get();
        return view('pages.accounting.expense-item.create', compact('expenseHeads'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'expense_head_id' => 'required|exists:accounting_heads,id',
        ]);

        ExpenseItem::create($request->all());
        return redirect()->route('expense-item.index')->with('success', 'Expense Item created successfully.');
    }

    public function edit(ExpenseItem $expenseItem)
    {
        $expenseHeads = AccountingHead::where('type', 'expense')->get();
        return view('pages.accounting.expense-item.edit', compact('expenseItem', 'expenseHeads'));
    }

    public function update(Request $request, ExpenseItem $expenseItem)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);

        $expenseItem->update($request->all());
        return redirect()->route('expense-item.index')->with('success', 'Expense Item updated successfully.');
    }

    public function destroy(ExpenseItem $expenseItem)
    {
        $expenseItem->delete();
        return redirect()->route('expense-item.index')->with('success', 'Expense Item deleted successfully.');
    }
} 