<?php

namespace App\Http\Controllers\Api;

use App\Models\Administrator;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AdministratorController
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $administrator = Administrator::all();
        return response()->json($administrator, 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function createAdmin(Request $request)
    {
      try {
        $user = User::where('id',$request->id);
        if (!$user) {
            return response()->json(
                ['message' => 'Error: El usuario no existe.'], 404, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
        }

        $validated = Validator::make($request->all(),[
          'id' => 'required|uuid'
        ]);

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

        $userId = Administrator::insert([
          'id' => $request->id
        ]);
        return response()->json(
          ['message' => 'Administrador creado exitosamente.'], 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
      }catch (Exception $exception) {
        return response()->json(
          ['message' => 'Error: '.$exception->getMessage()], 500, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
      }
    }

    /**
     * Display the specified resource.
     */
    public function deleteAdmin(string $id)
    {
      try {
        Administrator::where('id',$id)
                      ->delete();

        return response()->json(
          ['message' => 'Administrador eliminado exitosamente.'], 200, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
      }catch(Exception $exception) {
        return response()->json(
          ['message' => 'Error: '.$exception->getMessage()], 500, ['Content-Type' => 'application/json; charset=UTF-8'], JSON_UNESCAPED_UNICODE);
      }
    }

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

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