<?php

namespace App\Http\Controllers\Admin;

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

class InvestmentCategoryController extends Controller
{
    public function index()
    {
        $categories = InvestmentCategory::orderBy('order')->get();
        return view('admin.investment-categories.index', compact('categories'));
    }

    public function create()
    {
        return view('admin.investment-categories.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:100',
            'order' => 'required|integer|min:0',
            'is_active' => 'boolean'
        ]);

        // Convertir la checkbox en boolean
        $validated['is_active'] = $request->has('is_active');

        InvestmentCategory::create($validated);

        return redirect()->route('admin.investment-categories.index')
            ->with('success', 'Catégorie créée avec succès.');
    }

    public function edit(InvestmentCategory $investmentCategory)
    {
        return view('admin.investment-categories.edit', compact('investmentCategory'));
    }

    public function update(Request $request, InvestmentCategory $investmentCategory)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'icon' => 'nullable|string|max:100',
            'order' => 'required|integer|min:0',
            'is_active' => 'boolean'
        ]);

        // Convertir la checkbox en boolean
        $validated['is_active'] = $request->has('is_active');

        $investmentCategory->update($validated);

        return redirect()->route('admin.investment-categories.index')
            ->with('success', 'Catégorie mise à jour avec succès.');
    }

    public function destroy(InvestmentCategory $investmentCategory)
    {
        $investmentCategory->delete();

        return redirect()->route('admin.investment-categories.index')
            ->with('success', 'Catégorie supprimée avec succès.');
    }
}