<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\ExpenseGroup;
use Illuminate\Http\Request;

class ExpenseGroupController extends Controller
{
    protected function ensureEmployee(Request $request)
    {
        $user = $request->user();
        if (!$user || $user->role !== 'employee') {
            abort(403, 'Forbidden');
        }
        return $user;
    }

    public function index(Request $request)
    {
        $user = $this->ensureEmployee($request);

        $groups = ExpenseGroup::where('user_id', $user->id)
            ->orderBy('name')
            ->get();

        return view('employee.expense-groups.index', compact('groups'));
    }

    public function store(Request $request)
    {
        $user = $this->ensureEmployee($request);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:100'],
        ]);

        $group = ExpenseGroup::firstOrCreate(
            [
                'user_id' => $user->id,
                'name'    => trim($validated['name']),
            ],
            [
                'is_active' => true,
            ]
        );

        return redirect()
            ->route('employee.expense-groups.index')
            ->with('success', 'Expense group "' . $group->name . '" added.');
    }
}
