<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Api\response;
use Exception;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class UserController
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $users = User::all();

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

    public function getById(string $id)
    {
      $user = User::where('id', $id)->first();

      $user->multimedia = asset('storage/' . $user->multimedia);
      return response()->json($user, 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function createUser(Request $request)
    {
      $validator = Validator::make($request->all(), [
        'correo' => 'required|string|max:255|unique:users',
        'contrasena' => 'required|string',
        'nombre_usuario' => 'required|string',
        'nombre_completo' => 'required|string',
        'sexo' => 'required|string',
        'fecha_nacimiento' => 'required|date'
      ]);

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

        User::create([
          'correo' => $request->correo,
          'contrasena' => Hash::make($request->contrasena),
          'nombre_usuario' => $request->nombre_usuario,
          'nombre_completo' => $request->nombre_completo,
          'sexo' => $request->sexo,
          'fecha_nacimiento' => $request->fecha_nacimiento
        ]);
        return response()->json(['message' => 'Usuario creado exitosamente.'], 201);
    }


      public function login(Request $request)
      {
          $request->validate([
              'correo' => 'required|string|email',
              'contrasena' => 'required|string'
          ]);

          $user = User::where('correo', $request->correo)->first();

          if (!$user || !Hash::check($request->contrasena, $user->contrasena)) {
              return response()->json(['message' => 'Credenciales incorrectas'], 401);
          }

          $token = $user->createToken('auth_token', ['*'], now()->addHours(1))->plainTextToken;

          $tokenParts = explode('|', $token);
          $cleanToken = $tokenParts[1] ?? $token;

          return response()->json([
              'user' => $user,
              'token' => $cleanToken
          ], 200);
      }

      public function logout(Request $request)
      {
          $user = $request->user();
          if ($user) {
              $user->tokens()->delete();
              return response()->json(['message' => 'Logout exitoso'], 200);
          }
          return response()->json(['message' => 'Usuario no autenticado'], 401);
      }

      public function changePassword(Request $request){
        $user = User::find($request->id);
        if (!Hash::check($request->currentPassword, $user->contrasena)) {
          return response()->json(['message' => 'La contraseña actual es incorrecta'], 401);
        }

        $user->contrasena = Hash::make($request->newPassword);
        $user->save();

        return response()->json(['message' => 'Contraseña cambiada exitosamente']);
      }


    /**
     * Update the specified resource in storage.
     */
    public function userUpdate(Request $request, string $userId)
    {
      try {
        $user = User::find($userId);

        $user->correo = $request->correo;
        $user->fecha_nacimiento = $request->fecha_nacimiento;
        $user->nombre_completo = $request->nombre_completo;
        $user->nombre_usuario = $request->nombre_usuario;
        $user->sexo = $request->sexo;

        $user->save();

        return response()->json(['message' => 'Usuario editado correctamente'],200);
      }catch (Exception $exception) {
        return response()->json(['message' => 'Error: '.$exception->getMessage()],500);
      }
    }

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

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

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

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

    public function changePhoto(Request $request, string $id){
      $userExist = User::find($id);
        if(!$userExist) {
          return response()->json(
            ['message' => 'No se encontró la noticia'],
            404);
        }
        $path = $userExist->multimedia;
        $file = $request->file('multimedia');
      if($userExist->multimedia){
          if($file){
            $path = $file->store('uploads/user', 'public');

            // Eliminar archivo anterior si existe
            if ($userExist->multimedia && Storage::disk('public')->exists($userExist->multimedia)) {
                Storage::disk('public')->delete($userExist->multimedia);
            }
            $userExist->multimedia = $path;

            $userExist->save();
            return response()->json(['message' => 'Foto editada correctamente'],200);
          }
          }else {
            $pathCreate = $file->store('uploads/news', 'public');

            $userExist->multimedia = $pathCreate;

            $userExist->save();
            return response()->json(['message' => 'Foto creada correctamente'],200);
          }

       }
}
