<?php

namespace App\Http\Controllers;

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

class FormTemplateController extends Controller
{
    // Mostrar todos los formularios
    public function index()
    {
        $formTemplates = FormTemplate::all();
        return view('form-templates.index', compact('formTemplates'));
    }

    // Mostrar formulario de creación
    public function create()
    {
        return view('form-templates.create');
    }

    // Guardar nuevo formulario
    public function store(Request $request)
{
    $request->validate([
        'name' => 'required|string|max:255',
        'schema' => 'required|json',
    ]);

    FormTemplate::create([
        'name' => $request->form_name,
        'schema' => json_decode($request->schema, true),
    ]);

    return redirect()->route('form-templates.index')->with('success', 'Formulario creado correctamente.');
}


    // Mostrar un solo formulario (opcional)
    public function show(FormTemplate $formTemplate)
    {
        return view('form-templates.show', compact('formTemplate'));
    }

    // Mostrar vista de edición
    public function edit(FormTemplate $formTemplate)
    {
        return view('form-templates.edit', compact('formTemplate'));
    }

    // Actualizar formulario existente
    public function update(Request $request, FormTemplate $formTemplate)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'schema' => 'required|json',
        ]);

        $formTemplate->update([
            'name' => $request->form_name,
            'schema' => json_decode($request->schema, true),
        ]);

        return redirect()->route('form-templates.index')->with('success', 'Formulario actualizado correctamente.');
    }

    // Eliminar un formulario
    public function destroy(FormTemplate $formTemplate)
    {
        $formTemplate->delete();
        return redirect()->route('form-templates.index')->with('success', 'Formulario eliminado.');
    }
}
