<!-- 
 This component is the child of ../views/AddNew.vue
-->

<template>
  <div class="cu-page-con">
    <h2>Add New Item</h2>
		<div class="v-error" v-if="error"><h3>Error:<pre> {{ error }}</pre></h3></div>

    <form id="vueapp-form" @submit.prevent="submitForm">
      <div class="form-row">
        <label for="pid">Person ID:</label>
        <input type="text" id="pid" v-model="name.personId" />
      </div>
      <div class="form-row">
        <label for="firstname">First Name--:</label>
        <input type="text" id="firstname" v-model="name.firstName" />
      </div>
      <div class="form-row">
        <label for="lastname">Last Name:</label>
        <input type="text" id="lastname" v-model="name.lastName" />
      </div>
      <button type="submit" class="button">Save</button>
    </form>
    <div class="cu-msg">
      <p class="vue-green" v-if="isSaved">Saved sucessfully!</p>
      <p class="vue-red" v-if="hasError">Errors: {{ errorText }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, isProxy, toRaw } from "vue";
import { useFetch } from '../composables/useFetch.js'

const apiURL = jsData.api_url;
const name = ref({ personId: "", firstName: "", lastName: "" });
const isSaved = ref(false);
const hasError = ref(false);
const errorText = ref("");

const { makeFetch, results, error } = useFetch();
await makeFetch(apiURL);

if (isProxy(results.value)) {
  const rawObj = toRaw(results.value);
  name.value.personId = Object.keys(rawObj)[0];
  name.value.firstName = rawObj[Object.keys(rawObj)[0]].firstName;
  name.value.lastName = rawObj[Object.keys(rawObj)[0]].lastName;
}

function submitForm() {
  fetch(apiURL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-WP-Nonce": jsData.nonce,
    },
    body: JSON.stringify({ data: name.value }),
  })
    .then((response) => response.json())
    .then((data) => {
      isSaved.value = true;
      console.log("submitForm dataCallback " + data);
    })
    .catch((error) => {
      hasError.value = true;
      errorText.value = error;
      console.log("submitForm Error", error);
    });
}
//submitForm()
</script>

<style scoped>
.form-row {
  margin: 16px 0px;
}
</style>
