<?php

namespace App\Http\Controllers;

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

class ExerciseController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            // Validar datos
            $validated = $request->validate([
                'chapter_id' => 'required|integer|exists:chapters,id',
            ]);

            // Calcula el número del ejercicio
            $lastExercise = Exercise::where('chapter_id', $validated['chapter_id'])
                ->orderBy('exercise_number', 'desc')
                ->first();
            
            $exerciseNumber = $lastExercise ? $lastExercise->exercise_number + 1 : 1;

            // Crear un nuevo ejercicio
            $exercise = Exercise::create([
                'exercise_number' => $exerciseNumber,
                'title' => 'Exercise ' . $exerciseNumber,
                'content' => 'Description for Exercise ' . $exerciseNumber,
                'chapter_id' => $validated['chapter_id'],
                'type' => 'input', // Asignar por defecto input
            ]);

            // Retornar una respuesta exitosa
            return response()->json([
                'success' => true,
                'message' => 'Exercise created successfully.',
                'exercise' => $exercise
            ], 201);
        } catch (\Exception $e) {
            // Manejar excepciones y retornar un error
            return response()->json(['error' => 'An error occurred while processing your request: ' . $e->getMessage()], 500);
        }


    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
