<?php

namespace App\Http\Controllers;

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

class TermController extends Controller
{
    public function index()
    {
        $terms = Term::orderBy('sort_order')->get();
        return view('admin.terms.index', compact('terms'));
    }

    public function create()
    {
        return view('admin.terms.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'nullable|string',
            'input_type' => 'nullable|string',
            'sort_order' => 'nullable|integer',
            'visible' => 'nullable|boolean',
        ]);

        $data['created_by'] = auth()->id();

        Term::create($data);

        return redirect()->route('admin.terms.index')->with('success', 'Term created');
    }

    public function show(Term $term)
    {
        return view('admin.terms.show', compact('term'));
    }

    public function edit(Term $term)
    {
        return view('admin.terms.edit', compact('term'));
    }

    public function update(Request $request, Term $term)
    {
        $data = $request->validate([
            'title' => 'required|string|max:255',
            'content' => 'nullable|string',
            'input_type' => 'nullable|string',
            'sort_order' => 'nullable|integer',
            'visible' => 'nullable|boolean',
        ]);

        $term->update($data);

        return redirect()->route('admin.terms.index')->with('success', 'Term updated');
    }

    public function destroy(Term $term)
    {
        $term->delete();
        return redirect()->route('admin.terms.index')->with('success', 'Term deleted');
    }
}
