<?php

// app/Http/Controllers/FormController.php

namespace App\Http\Controllers;

use App\Models\Form;
use App\Models\FormResponse;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\DB;
class FormController extends Controller
{

public function store(Request $request): JsonResponse
{
    try {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'tabs' => 'required|array',
            'tabs.*.id' => 'required|string',
            'tabs.*.title' => 'required|string',
            'tabs.*.rows' => 'required|integer|min:1',
            'tabs.*.columns' => 'required|integer|min:1',
            'tabs.*.elements' => 'required|array',
            'tabs.*.elements.*.position' => 'required|array',
            'tabs.*.elements.*.element' => 'required|array',
        ]);

        // Asumiendo que la tabla se llama 'forms'
        $formId = DB::table('forms')->insertGetId([
            'title' => $validated['title'],
            'configuration' => json_encode([
                'tabs' => $validated['tabs']
            ]),
            'is_published' => false,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Formulario guardado exitosamente',
            'form_id' => $formId
        ], 201);

    } catch (ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error de validación',
            'errors' => $e->errors()
        ], 422);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error interno del servidor',
            'error' => $e->getMessage()
        ], 500);
    }
}
public function getAll(): JsonResponse
{
    try {
        $forms = DB::table('forms')->get();

        // Decodificamos el campo 'configuration' de cada formulario
        $forms = $forms->map(function ($form) {
            $form->configuration = json_decode($form->configuration, true);
            return $form;
        });

        return response()->json([
            'success' => true,
            'forms' => $forms
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error al obtener los formularios',
            'error' => $e->getMessage()
        ], 500);
    }
}


public function getFormById($id): JsonResponse
{
    $form = DB::table('forms')->where('id', $id)->first();

    if (!$form) {
        return response()->json([
            'success' => false,
            'message' => 'Formulario no encontrado',
        ], 404);
    }

    // Decodificar el campo 'configuration' (JSON)
    $configuration = json_decode($form->configuration, true);

    return response()->json([
        'success' => true,
        'form' => [
            'id' => $form->id,
            'title' => $form->title,
            'is_published' => $form->is_published,
            'configuration' => $configuration
        ]
    ]);

}



public function update(Request $request, $id): JsonResponse
{
    try {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'tabs' => 'required|array',
            'tabs.*.id' => 'required|string',
            'tabs.*.title' => 'required|string',
            'tabs.*.rows' => 'required|integer|min:1',
            'tabs.*.columns' => 'required|integer|min:1',
            'tabs.*.elements' => 'required|array',
            'tabs.*.elements.*.position' => 'required|array',
            'tabs.*.elements.*.element' => 'required|array',
        ]);

        $affected = DB::table('forms')
            ->where('id', $id)
            ->update([
                'title' => $validated['title'],
                'configuration' => json_encode([
                    'tabs' => $validated['tabs']
                ]),
                'updated_at' => now()
            ]);

        if ($affected === 0) {
            return response()->json([
                'success' => false,
                'message' => 'No se encontró el formulario para actualizar'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'message' => 'Formulario actualizado exitosamente'
        ], 200);

    } catch (ValidationException $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error de validación',
            'errors' => $e->errors()
        ], 422);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error interno del servidor',
            'error' => $e->getMessage()
        ], 500);
    }
}





public function destroy($id)
{
    try {
        $form = Form::findOrFail($id);

        if ($form->is_published) {
            return response()->json([
                'success' => false,
                'message' => 'No se puede eliminar un formulario ya publicado.'
            ], 403);
        }

        DB::statement('SET FOREIGN_KEY_CHECKS=0');

        $form->delete();

        DB::statement('SET FOREIGN_KEY_CHECKS=1');

        return response()->json([
            'success' => true,
            'message' => 'Formulario eliminado correctamente.'
        ], 200);
    } catch (\Exception $e) {
        DB::statement('SET FOREIGN_KEY_CHECKS=1');

        return response()->json([
            'success' => false,
            'message' => 'Error al eliminar el formulario.',
            'error' => $e->getMessage()
        ], 500);
    }
}



    public function publish($id)
{
    try {
        $form = DB::table('forms')->where('id', $id)->first();

        if (!$form) {
            return response()->json([
                'success' => false,
                'message' => 'Formulario no encontrado',
            ], 404);
        }

        if ($form->is_published) {
            return response()->json([
                'success' => false,
                'message' => 'Formulario ya está publicado',
            ], 400);
        }

        DB::table('forms')->where('id', $id)->update([
            'is_published' => true,
            'updated_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Formulario publicado exitosamente',
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error al publicar el formulario',
            'error' => $e->getMessage()
        ], 500);
    }
}



public function unpublish($id)
{
    try {
        $form = DB::table('forms')->where('id', $id)->first();

        if (!$form) {
            return response()->json([
                'success' => false,
                'message' => 'Formulario no encontrado',
            ], 404);
        }

        if (!$form->is_published) {
            return response()->json([
                'success' => false,
                'message' => 'Formulario ya está despublicado',
            ], 400);
        }

        DB::table('forms')->where('id', $id)->update([
            'is_published' => false,
            'updated_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Formulario despublicado exitosamente',
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Error al despublicar el formulario',
            'error' => $e->getMessage()
        ], 500);
    }
}

public function getPublicado()
{
    $formulario = DB::table('forms')->where('is_published', true)->first();

    if (!$formulario) {
        return response()->json([
            'success' => false,
            'message' => 'No hay formulario publicado'
        ]);
    }

    return response()->json([
        'success' => true,
        'form' => $formulario
    ]);
}



}

