<?php

namespace App\Http\Controllers\Api;

use App\Models\NewsModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Exception;
use Illuminate\Support\Facades\Log;

class NewsController
{
    /**
     * Display a listing of the resource.
     */
    public function getAll(Request $request)
    {
      $searchParam = $request->query('title');
      try {
        if($searchParam) {
          $news = NewsModel::join('categories', 'news.id_categorias', '=', 'categories.id')
          ->select('news.*', 'categories.categoria as id_categorias')
          ->where('titulo','like', '%'.$searchParam.'%')
          ->get();
        }else{
          $news = NewsModel::join('categories', 'news.id_categorias', '=', 'categories.id')
          ->select('news.*', 'categories.categoria as id_categorias')
          ->get();
        }
        if ($news->isEmpty()) {
          // Devolver un error 404 si no hay datos
          return response()->json([
              'success' => false,
              'message' => 'No se encontraron noticias.',
          ], 404);
        }
        $news->transform(function ($item) {
          // Construir la URL completa de la imagen
          $item->multimedia = asset('storage/' . $item->multimedia);
          return $item;
        });


      }catch(Exception $error){
        return response()->json($error->getMessage(), 500, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
      }
      return response()->json(
        $news, 200, ['Content-Type' => 'application/json; charset=UTF-8'],
        JSON_UNESCAPED_UNICODE);
    }

    /**
     * Display the specified resource.
     */
    public function getById(string $id) {
      try{
        $news = NewsModel::join('categories', 'news.id_categorias', '=', 'categories.id')
        ->select('news.*', 'categories.categoria as id_categorias')
        ->where('news.id', $id)
        ->first();
        if (!$news) {
          return response()->json(
            "No se encontró el registro"
            ,
            404,
            ['Content-Type' => 'application/json; charset=UTF-8'],
            JSON_UNESCAPED_UNICODE
          );
        }

        $news->multimedia = asset('storage/' . $news->multimedia);

      } catch(Exception $error){
        return response()->json(
          "Error al realizar la consulta: " . $error->getMessage(),
          500,
          ['Content-Type' => 'application/json; charset=UTF-8'],
          JSON_UNESCAPED_UNICODE
        );
      }
      return response()->json(
        $news, 200, ['Content-Type' => 'application/json; charset=UTF-8'],
        JSON_UNESCAPED_UNICODE);
    }

    public function getByUserId(string $userId) {
      try{
        $news = NewsModel::join('categories', 'news.id_categorias', '=', 'categories.id')
        ->join('users', 'news.id_usuarios', '=', 'users.id')
        ->select('news.*', 'categories.categoria as id_categorias')
        ->where('users.id', $userId)
        ->get();
        if (!$news) {
          return response()->json(
            "No se encontró el registro"
            ,
            404,
            ['Content-Type' => 'application/json; charset=UTF-8'],
            JSON_UNESCAPED_UNICODE
          );
        }

        $news->transform(function ($item) {
          // Construir la URL completa de la imagen
          $item->multimedia = asset('storage/' . $item->multimedia);
          return $item;
        });

        return response()->json(
          $news, 200, ['Content-Type' => 'application/json; charset=UTF-8'],
          JSON_UNESCAPED_UNICODE);

      } catch(Exception $error){
        return response()->json(
          "Error al realizar la consulta: " . $error->getMessage(),
          500,
          ['Content-Type' => 'application/json; charset=UTF-8'],
          JSON_UNESCAPED_UNICODE
        );
      }
    }

    public function createNews(Request $request) {
      $validatedData = Validator::make($request->all(),[
        'titulo' => 'required|string|max:255',
        'descripcion' => 'required|string',
        'pais' => 'required|string',
        'autor' => 'required|string',
        'url' => 'required|string',
        'id_usuarios' => 'required|uuid',
        'id_categorias' => 'required|uuid',
      ]);

      try{
        $file = $request->file('multimedia');
        $path = $file->store('uploads/news', 'public');

        if ($validatedData->fails()) {
          return response()->json([
            'message' => 'Validation failed',
            'errors' => $validatedData->errors() ],
            422);
        }

        $newsCreated = NewsModel::insert([
          'titulo' => $request->titulo,
          'descripcion' => $request->descripcion,
          'pais' => $request->pais,
          'autor' => $request->autor,
          'url' => $request->url,
          'multimedia' => $path,
          'id_usuarios' => $request->id_usuarios,
          'id_categorias' => $request->id_categorias
        ]);
        return response()->json(
          ['message' => 'Se creó la noticia correctamente'],
          200,
          ['Content-Type' => 'application/json; charset=UTF-8'],
          JSON_UNESCAPED_UNICODE);
      }catch(Exception $error){
        return response()->json(
          "Error al realizar la consulta: " . $error->getMessage(),
          500,
          ['Content-Type' => 'application/json; charset=UTF-8'],
          JSON_UNESCAPED_UNICODE
        );
      }
    }

    /**
     * Update the specified resource in storage.
     */
    public function updateNews(Request $request, string $id)
    {
      if (!is_string($id) || empty($id)) {
        return response()->json([
            'message' => 'El ID proporcionado no es válido'
        ], 400);
    }
      try {
        $newsExist = NewsModel::find($id);
        if(!$newsExist) {
          return response()->json(
            ['message' => 'No se encontró la noticia'],
            404);
        }
        $validatedData = Validator::make($request->all(),[
          'titulo' => 'sometimes|string|max:255',
          'descripcion' => 'sometimes|string',
          'pais' => 'sometimes|string',
          'autor' => 'sometimes|string',
          'url' => 'sometimes|string'
        ]);

        if ($validatedData->fails()) {
          return response()->json([
            'message' => 'Validation failed',
            'errors' => $validatedData->errors() ],
            422);
          }
          $path = $newsExist->multimedia;
          $file = $request->file('multimedia');

          if($file){
            $path = $file->store('uploads/news', 'public');

            // Eliminar archivo anterior si existe
            if ($newsExist->multimedia && Storage::disk('public')->exists($newsExist->multimedia)) {
                Storage::disk('public')->delete($newsExist->multimedia);
            }
          }
          NewsModel::where('id', $id)
             ->update([
              'titulo' => $request->titulo,
              'descripcion' => $request->descripcion,
              'pais' => $request->pais,
              'multimedia' => $path,
              'autor' => $request->autor,
              'url' => $request->url
             ]);

        return response()->json([
          'message' => 'Noticia actualizada exitosamente'
        ], 200);
      } catch (Exception $error) {
        // Manejar errores
        return response()->json([
            'message' => 'Error al actualizar la noticia',
            'error' => $error->getMessage()
        ], 500);

  }

    }

    /**
     * Remove the specified resource from storage.
     */
    public function deleteNews(string $id)
    {
      $newsId = $id;

      if (!$newsId){
          return response()->json(['message' => 'No se encontro el registro'],404);
      }

      //delete requirement
      $deleted = NewsModel::where('id', $newsId)->delete();

      //Delete
      if ($deleted){
          return response()->json(['message' => 'Se eliminó la noticia'],200);
      }else{
          return response()->json(['message' => 'Fallo en la eliminación de la noticia'],400);
      }
    }
}
