<?php

namespace App\Http\Controllers;

use App\Models\ExpenseType;
use Illuminate\Http\Request;

class ExpenseTypeController extends Controller
{
    public function index()
    {
        // Admins and super_admins can see all expense types
        if (auth()->user()->isSuperAdmin() || auth()->user()->isAdmin()) {
            $expenseTypes = ExpenseType::orderBy('is_system', 'desc')
                ->orderBy('name')
                ->get();
        } else {
            // Regular users can only see their own expense types and system types
            $expenseTypes = ExpenseType::where(function ($query) {
                $query->where('user_id', auth()->id())
                    ->orWhere('is_system', true);
            })->orderBy('is_system', 'desc')
              ->orderBy('name')
              ->get();
        }

        return view('expense-types.index', compact('expenseTypes'));
    }

    public function create()
    {
        return view('expense-types.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:expense_types,name,NULL,id,user_id,' . auth()->id(),
        ]);

        auth()->user()->expenseTypes()->create([
            'name' => $validated['name'],
            'is_system' => false,
        ]);

        return redirect()->route('expense-types.index')
            ->with('success', 'Expense type created successfully.');
    }

    public function edit(ExpenseType $expenseType)
    {
        if ($expenseType->is_system && $expenseType->user_id !== auth()->id()) {
            abort(403, 'Cannot edit system expense types.');
        }

        $this->authorize('update', $expenseType);
        return view('expense-types.edit', compact('expenseType'));
    }

    public function update(Request $request, ExpenseType $expenseType)
    {
        if ($expenseType->is_system && $expenseType->user_id !== auth()->id()) {
            abort(403, 'Cannot edit system expense types.');
        }

        $this->authorize('update', $expenseType);

        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:expense_types,name,' . $expenseType->id . ',id,user_id,' . auth()->id(),
        ]);

        $expenseType->update($validated);

        return redirect()->route('expense-types.index')
            ->with('success', 'Expense type updated successfully.');
    }

    public function destroy(ExpenseType $expenseType)
    {
        if ($expenseType->is_system && $expenseType->user_id !== auth()->id()) {
            abort(403, 'Cannot delete system expense types.');
        }

        $this->authorize('delete', $expenseType);

        if ($expenseType->expenses()->exists()) {
            return back()->with('error', 'Cannot delete expense type with associated expenses.');
        }

        $expenseType->delete();

        return redirect()->route('expense-types.index')
            ->with('success', 'Expense type deleted successfully.');
    }
}
