<?php

namespace App\Http\Controllers;

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

class NoticiaController extends Controller
{
    public function index(Request $request)
    {
        $noticias = Noticia::orderBy('fecha', 'desc')->get();
        
        if ($request->expectsJson()) {
            return response()->json($noticias);
        }
        
        return view('noticias.index', compact('noticias'));
    }

    public function show($id)
    {
        $noticia = Noticia::findOrFail($id);
        
        if (request()->expectsJson()) {
            return response()->json($noticia);
        }
        
        return view('noticias.show', compact('noticia'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'titulo' => 'required|string|max:200',
            'contenido' => 'required',
            'imagen' => 'nullable|string|max:200',
        ]);
        $noticia = Noticia::create($data);
        return response()->json($noticia, 201);
    }

    public function update(Request $request, $id)
    {
        $noticia = Noticia::findOrFail($id);
        $data = $request->validate([
            'titulo' => 'sometimes|string|max:200',
            'contenido' => 'sometimes',
            'imagen' => 'nullable|string|max:200',
        ]);
        $noticia->update($data);
        return response()->json($noticia);
    }

    public function destroy($id)
    {
        $noticia = Noticia::findOrFail($id);
        $noticia->delete();
        return response()->json(null, 204);
    }
}
