@extends('layouts.app')
@section('title') Users @endsection
@section('content')

<div x-data="{ open_form: false, edit_form: false, edit_user_name: '', edit_user_email: '', edit_user_id: '',notification_success: true, delete_form: false, delete_user_name: '', delete_user_id: ''}">
  <!-- Notification -->
  <div x-data="notification()" x-init="init()">
    <div
      x-cloak
      x-show="isVisible"
      x-transition:enter="transition ease-out duration-300"
      x-transition:enter-start="opacity-0 transform translate-y-2"
      x-transition:enter-end="opacity-100 transform translate-y-0"
      x-transition:leave="transition ease-in duration-200"
      x-transition:leave-start="opacity-100 transform translate-y-0"
      x-transition:leave-end="opacity-0 transform translate-y-2"
      class="fixed inset-x-0 top-5 z-20 flex items-center justify-center px-4 py-6 pointer-events-none sm:p-6 sm:items-start sm:justify-center"
    >
      <div :class="notification_success ? 'bg-green-600' : 'bg-red-600'" class="max-w-sm w-full shadow-lg text-white rounded-lg pointer-events-auto">
        <div class="p-4">
          <p class="text-sm text-center" x-text="message"></p>
        </div>
      </div>
    </div>
  </div>
  <!-- Notification -->

  <!-- Registration form -->
  <div x-cloak
        @keydown.window.escape="open_form = false"
        x-show="open_form"
        class="relative z-10"
        aria-labelledby="modal-title"
        x-ref="dialog"
        aria-modal="true">
    <div x-show="open_form"
        x-transition:enter="ease-out duration-300"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="ease-in duration-200"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        x-description="Background backdrop, show/hide based on modal state."
        class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
        aria-hidden="true"></div>
  
  
    <div class="fixed inset-0 z-10 w-screen overflow-y-auto">
      <div class="flex min-h-full items-end justify-center p-4 text-center items-center sm:p-0">
        <div x-show="open_form"
            x-transition:enter="ease-out duration-300"
            x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
            x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
            x-transition:leave="ease-in duration-200"
            x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
            x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
            x-description="Modal panel, show/hide based on modal state."
            class="relative transform overflow-hidden rounded-lg border-t-2 border-teal-600 bg-white dark:bg-slate-800 text-left shadow-xl transition-all my-8 w-full max-w-lg"
            @click.away="open_form = false">
          <div class="bg-white dark:bg-slate-800 px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:flex-col sm:items-start">
              <div class="sm:flex sm:flex-row items-center w-full">
                <div class="mt-3 w-full text-center sm:ml-4 sm:mt-0 sm:text-left">
                  <div class="grid gap-3">
                    <div>
                      <span class="block text-2xl">Create a new user</span>
                    </div>
                    <div>
                      <label for="add_user_name_input" class="font-semibold block">User name:</label>
                      <input class="bg-gray-50 border border-gray-300  text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="add_user_name_input" name="add_user_name_input" type="text">
                    </div>
                    <div>
                      <label for="add_user_email_input" class="font-semibold block">User email:</label>
                      <input class="bg-gray-50 border border-gray-300  text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="add_user_email_input" name="add_user_email_input" type="email">
                    </div>
                    <div>
                      <label for="add_user_password_input" class="font-semibold block">User password:</label>
                      <input class="bg-gray-50 border border-gray-300  text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="add_user_password_input" name="add_user_password_input" type="password">
                    </div>
                    <div class="py-3 text-center">
                      <button x-on:click="add_user" class="px-4 py-2 text-m font-medium  bg-white border border-gray-200 rounded-lg hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 bg-gray-700 dark:hover:text-white dark:hover:bg-gray-700">Create</button>
                    </div>
                  </div>
                </div>
              </div>  
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- End registration form -->

  <!-- Edit form -->
  <div x-cloak
        @keydown.window.escape="edit_form = false"
        x-show="edit_form"
        class="relative z-10"
        aria-labelledby="modal-title"
        x-ref="dialog"
        aria-modal="true">
    <div x-show="edit_form"
        x-transition:enter="ease-out duration-300"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="ease-in duration-200"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        x-description="Background backdrop, show/hide based on modal state."
        class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
        aria-hidden="true"></div>
  
  
    <div class="fixed inset-0 z-10 w-screen overflow-y-auto">
      <div class="flex min-h-full items-end justify-center p-4 text-center items-center sm:p-0">
        <div x-show="edit_form"
            x-transition:enter="ease-out duration-300"
            x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
            x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
            x-transition:leave="ease-in duration-200"
            x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
            x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
            x-description="Modal panel, show/hide based on modal state."
            class="relative transform overflow-hidden rounded-lg border-t-2 border-orange-600 bg-white dark:bg-slate-800 text-left shadow-xl transition-all my-8 w-full max-w-lg"
            @click.away="edit_form = false">
          <div class="bg-white dark:bg-slate-800 px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:flex-col sm:items-start">
              <div class="sm:flex sm:flex-row items-center w-full">
                <div class="mt-3 w-full sm:mt-0 ">
                  <div class="grid gap-3">
                    <div>
                      <span class="block text-2xl">Editing user <span class="font-bold" x-text="edit_user_name"></span></span>
                    </div>
                    <div>
                      <label for="edit_user_name_input" class="font-semibold block">User name:</label>
                      <input :value="edit_user_name" class="bg-gray-50 border border-gray-300 dark:text-white  text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="edit_user_name_input" name="edit_user_name_input" type="text">
                      <input :value="edit_user_id" type="hidden" id="edit_user_id">
                    </div>
                    <div>
                      <label for="edit_user_email_input" class="font-semibold block">User email:</label>
                      <input :value="edit_user_email" class="bg-gray-50 border border-gray-300 dark:text-white  text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="edit_user_email_input" name="edit_user_email_input" type="email">
                    </div>
                    <div>
                      <label for="edit_user_password_input" class="font-semibold block">User password:</label>
                      <input placeholder="Leave empty to not change the password." class="bg-gray-50 border border-gray-300  dark:text-white text-sm rounded-lg block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400" id="edit_user_password_input" name="edit_user_password_input" type="password">
                    </div>
                    <div class="py-3 text-center">
                      <button x-on:click="edit_user;edit_user_name='';edit_user_email='';edit_user_password='';edit_form=false;" class="px-4 py-2 text-m font-medium  bg-white border border-gray-200 rounded-lg hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 bg-gray-700 dark:hover:text-white dark:hover:bg-gray-700">Update user</button>
                    </div>
                  </div>
                </div>
              </div>  
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- End edit form -->
  
  <!-- Delete user form -->
  <div x-cloak
        @keydown.window.escape="delete_form = false"
        x-show="delete_form"
        class="relative z-10"
        aria-labelledby="modal-title"
        x-ref="dialog"
        aria-modal="true">
    <div x-show="delete_form"
        x-transition:enter="ease-out duration-300"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="ease-in duration-200"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        x-description="Background backdrop, show/hide based on modal state."
        class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity"
        aria-hidden="true"></div>
  
  
    <div class="fixed inset-0 z-10 w-screen overflow-y-auto">
      <div class="flex min-h-full items-end justify-center p-4 text-center items-center sm:p-0">
        <div x-show="delete_form"
            x-transition:enter="ease-out duration-300"
            x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
            x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
            x-transition:leave="ease-in duration-200"
            x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
            x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
            x-description="Modal panel, show/hide based on modal state."
            class="relative transform overflow-hidden rounded-lg border-t-2 border-red-600 bg-white dark:bg-slate-800 text-left shadow-xl transition-all my-8 w-full max-w-lg"
            @click.away="delete_form = false">
          <div class="bg-white dark:bg-slate-800 px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:flex-col sm:items-start">
              <div class="sm:flex sm:flex-row items-center w-full">
                <div class="mt-3 w-full sm:mt-0">
                  <div class="grid gap-3">
                    <div>
                      <span class="block text-2xl">Deleting user</span>
                    </div>
                    <div>
                      You are about to delete user <span x-text="delete_user_name" class="font-bold"></span>. Proceed?
                      <input type="hidden" id="delete_user_id" name="delete_user_id" :value="delete_user_id">
                    </div>
                    <div class="py-3 text-center">
                      <button x-on:click="delete_user(delete_user_id);delete_form=false;" class="px-4 py-2 text-m font-medium text-red-900 bg-white border border-gray-200 rounded-lg hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:text-red-400 dark:hover:text-white dark:hover:bg-gray-700">Delete user</button>
                    </div>
                  </div>
                </div>
              </div>  
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- End delete user form -->

  <div class="flex gap-3 flex-col my-4 animate-slide-up-fade-in">
    <div class="flex-1 flex-col justify-between h-full border-s-2 border-indigo-400 flex-col bg-white dark:bg-slate-900  rounded-md drop-shadow-md p-4 hover:shadow-lg hover:transition-all">
      <div class="my-2 text-center">
        <button class="px-4 py-2 font-medium border border-gray-200 rounded-lg dark:bg-gray-800 bg-white border-gray-200 dark:border-gray-700"
                x-on:click="open_form=true;">
          Create a new user
        </button>
      </div>
      <div class="my-2">
        @if (count($users) == 0)
          <div class="alert alert-warning">No users found</div>
        @else
          <table class="table-auto w-full overflow-x-auto">
            <thead>
              <tr class="border-y border-slate-200 dark:border-slate-600">
                <th class="p-1 text-center">Name</th>
                <th class="p-1 text-center">E-mail</th>
                <th class="p-1 text-center"></th>
              </tr>
            </thead>
            <tbody>
              @foreach ($users as $user)
                <tr id="user_{{ $user->id }}" class="border-y border-slate-200 dark:border-slate-600">
                    <td class="p-1 text-center">{{ $user->name }}</td>
                    <td class="p-1 text-center">{{ $user->email }}</td>
                    <td class="p-1 text-center">
                      <div class="inline-flex">
                        <button @click="edit_form=true;edit_user_name=$el.dataset.name;edit_user_email=$el.dataset.email;edit_user_id=$el.dataset.user_id;" class="px-2 rounded-s-md border text-sm p-1 dark:bg-gray-800 bg-white border-gray-200 dark:border-gray-700" data-email="{{ $user->email }}" data-name="{{ $user->name }}" data-user_id="{{ $user->id }}">Edit</button>
                        <button @click="delete_form=true;delete_user_id=$el.dataset.user_id;delete_user_name=$el.dataset.name;" class="rounded-e-md border-y border-e text-sm px-2 py-1 dark:bg-gray-800 bg-white border-gray-200 dark:border-gray-700 btn_delete" data-name="{{ $user->name }}" data-user_id="{{ $user->id }}"><i class="fas fa-trash mr-1"></i> Delete</button>
                      </div>
                    </td>
                </tr>
              @endforeach
            </tbody>
          </table>
        @endif
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
  const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
  document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('menu_users').classList.remove('text-gray-500');
    document.getElementById('menu_users').classList.remove('hover:bg-gray-700');
    document.getElementById('menu_users').classList.remove('hover:bg-opacity-25');
    document.getElementById('menu_users').classList.remove('hover:text-gray-100');
    document.getElementById('menu_users').classList.add('text-gray-100');
    document.getElementById('menu_users').classList.add('bg-opacity-25');
    document.getElementById('menu_users').classList.add('bg-gray-700');
    document.getElementById('menu_users').classList.add('border-e-2');
    document.getElementById('menu_users').classList.add('border-indigo-400');
  });
  async function add_user()
  {
    const username = document.getElementById("add_user_name_input").value;
    const email = document.getElementById("add_user_email_input").value;
    const password = document.getElementById("add_user_password_input").value;

    if ( username == "" || password == "" || email == "" )
    {
      alert("NO!");
      return false;
    }
    else
    {
      await fetch("/users/create",{
        method: "POST",
        headers: {
        'X-CSRF-TOKEN': csrfToken,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        },
        body : JSON.stringify({name:username, email:email, password:password}),
      })
      .then( response =>
      {
        return response.json().then(data => {
         return {ok: response.ok, data: data}; 
        });
      })
      .then(resp =>
      {
        if ( resp.ok && resp.data.code == 'ok' )
        {
          showNotification(resp.data.message, true);
          document.getElementById("add_user_name_input").value = '';
          document.getElementById("add_user_email_input").value = '';
          document.getElementById("add_user_password_input").value = '';
          return true;
        }
        else if ( resp.ok && resp.data.code == 'fail')
        {
          showNotification(resp.data.message, false);
          return false;
        }
        else if ( !resp.ok )
        {
          showNotification(resp.data.message, false);
          return false;
        }
      }
      );
    }
  }

  async function edit_user()
  {
    const username = document.getElementById("edit_user_name_input").value;
    const email = document.getElementById("edit_user_email_input").value;
    const password = document.getElementById("edit_user_password_input").value;
    const user_id = document.getElementById("edit_user_id").value;

    if ( username == "" || email == "" )
    {
      alert("NO!");
      return false;
    }
    else
    {
      await fetch("/users/save",{
        method: "POST",
        headers: {
        'X-CSRF-TOKEN': csrfToken,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        },
        body : JSON.stringify({id:user_id, name:username, email:email, password:password}),
      })
      .then( response =>
      {
        return response.json().then(data => {
         return {ok: response.ok, data: data}; 
        });
      })
      .then(resp =>
      {
        if ( resp.ok && resp.data.code == 'ok' )
        {
          showNotification(resp.data.message, true);
          return true;
        }
        else if ( resp.ok && resp.data.code == 'fail')
        {
          showNotification(resp.data.message, false);
          return false;
        }
        else if ( !resp.ok )
        {
          showNotification(resp.data.message, false);
          return false;
        }
      }
      );
    }
  }

  async function delete_user(user_id)
  {
      await fetch("/users/delete",{
        method: "POST",
        headers: {
        'X-CSRF-TOKEN': csrfToken,
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        },
        body : JSON.stringify({id:user_id}),
      })
      .then( response =>
      {
        return response.json().then(data => {
         return {ok: response.ok, data: data}; 
        });
      })
      .then(resp =>
      {
        if ( resp.ok && resp.data.code == 'ok' )
        {
          showNotification(resp.data.message, true);
          document.getElementById(`user_${user_id}`).remove();
          return true;
        }
        else if ( resp.ok && resp.data.code == 'fail')
        {
          showNotification(resp.data.message, false);
          return false;
        }
        else if ( !resp.ok )
        {
          showNotification(resp.data.message, false);
          return false;
        }
      }
      );
  }

  function notification() {
    return {
      isVisible: false,
      notification_status: true,
      message: '',
      init() {
        window.showNotification = this.show.bind(this);
      },
      show(msg, status) {
        this.message = msg;
        this.notification_success = status;
        this.isVisible = true;
        delay = status ? 3000 : 6000;
        setTimeout(() => {
          this.isVisible = false;
        }, delay);
      }
    }
  }
</script>
@endsection
