<?php

namespace App\Http\Controllers\Api;

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

class CommentController
{
    /**
     * Display a listing of the resource.
     */
    public function getAll()
    {
        $comment = Comment::join('users', 'comments.id_usuarios', '=', 'users.id')
        ->select('comments.*', 'users.nombre_completo as id_usuarios')
        ->get();
        // Return as JSON response with UTF-8 encoding
        return response()->json($comment, 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function getById(string $newsId)
    {
      $commentsList = Comment::join('users', 'comments.id_usuarios', '=', 'users.id')
      ->select('comments.*', 'users.nombre_completo as id_usuarios')
      ->where('id_noticias', $newsId)
      ->get();
      return response()->json($commentsList, 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * Display the specified resource.
     */
    public function createComment(Request $request)
    {
      $commentText = $request->input('texto');
      $userId = $request->input('id_usuarios');
      $newsId = $request->input('id_noticias');

      try {
        $commentCreated = Comment::create([
          'id_usuarios' => $userId,
          'id_noticias' => $newsId,
          'texto' => $commentText
        ]);
        return response()->json(['message' => 'Comentario creado exitosamente.'], 201);
      }catch(Exeption $error){
        return response()->json(['message' => 'Fallo al crear el comentario', 'error' => $error->getMessage()], 500);
      }


    }

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

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