<template>
  <div id="form-user">
    <h4 class="Textual Inputs mb-4">
      <span v-if="company"
        >{{ $trans("Create User in") }}
        <b>{{ company.name }} {{ $trans("Company") }}</b></span
      >
      <span v-else-if="user && user.name"
        >{{ $trans("Edit") }} {{ user.name }}</span
      >
      <span v-else>{{ $trans("Create a new user") }}</span>
    </h4>
    <div class="mb-3 row">
      <label class="col-md-4 col-form-label required">{{
        $trans("First Name")
      }}</label>
      <div class="col-md-8">
        <input
          class="form-control"
          type="text"
          placeholder="First Name"
          v-model="newUser.first_name"
        />
      </div>
    </div>
    <div class="mb-3 row">
      <label class="col-md-4 col-form-label">{{ $trans("Last Name") }}</label>
      <div class="col-md-8">
        <input
          class="form-control"
          type="text"
          placeholder="Last Name"
          v-model="newUser.last_name"
        />
      </div>
    </div>
    <div class="mb-3 row">
      <label for="email" class="col-md-4 col-form-label required">{{
        $trans("Email")
      }}</label>
      <div class="col-md-8">
        <input
          class="form-control"
          type="text"
          placeholder="Email Address"
          id="email"
          v-model="newUser.email"
        />
      </div>
    </div>
    <div class="mb-3 row">
      <label class="col-md-4 col-form-label required">{{
        $trans("Phone")
      }}</label>
      <div class="col-md-8">
        <input
          class="form-control"
          type="text"
          placeholder="Phone Number"
          v-model="newUser.phone"
        />
      </div>
    </div>
    <div class="mb-3 row" v-if="!user">
      <label class="col-md-4 col-form-label required">{{
        $trans("Password")
      }}</label>
      <div class="col-md-8">
        <input
          class="form-control"
          type="password"
          placeholder="User Password"
          v-model="newUser.password"
        />
      </div>
    </div>

    <div class="mb-3 row" v-if="currentUser.company_id">
      <label class="col-md-4 col-form-label">{{ $trans("Department") }}</label>
      <div class="col-md-8">
        <select
          class="form-control form-select"
          v-model="newUser.department_id"
        >
          <option :value="undefined" hidden disabled>
            {{ $trans("Select Department") }}
          </option>
          <option
            :value="department.id"
            :key="department.id"
            v-for="department in departments"
          >
            {{ department.name }}
          </option>
        </select>
      </div>
    </div>

    <div class="mb-3 row">
      <label class="col-md-4 col-form-label required">{{
        $trans("Role")
      }}</label>
      <div class="col-md-8">
        <select class="form-control form-select" v-model="newUser.role_id">
          <option :value="undefined" hidden disabled>
            {{ $trans("Select Role") }}
          </option>
          <option :value="role.id" :key="role.id" v-for="role in roles">
            {{ role.name }}
          </option>
        </select>
      </div>
    </div>
    <!--<div class="row" v-if="validationErrors.length">
      <div class="col-md-4"></div>
      <div class="col-md-8">
        <ul class="text-danger">
          <li v-for="(error, i) in validationErrors" class="fw-bolder" :key="i">
            {{ error }}
          </li>
        </ul>
      </div>
    </div> -->
    <div class="row">
      <div class="col-md-4"></div>
      <div class="col-md-8">
        <loading-button
          task="CREATING_COMPANY"
          class="btn btn-primary w-100"
          type="button w-100"
          @clicked="handleSave"
          @keyup.enter="handleSave"
          :disabled="submitDisabled"
        >
          <template #caption>{{ $trans("Save") }}</template>
        </loading-button>
      </div>
    </div>
  </div>
</template>
<script>
import LoadingButton from "@/components/LoadingButton.vue";
export default {
  name: "UserCreator",
  props: ["user", "company"],
  emits: ["saved"],
  components: {
    LoadingButton,
  },
  data: () => ({
    newUser: {},
    errors: {},
    roles: [],
    departments: [],
  }),
  created() {
    if (this.user) {
      this.newUser = { ...this.user };
    }
    if (this.company) {
      this.newUser.company_id = this.company.id;
    }
  },
  computed: {
    submitDisabled() {
      return (
        !this.newUser.first_name ||
        !this.newUser.email ||
        !this.newUser.phone ||
        !this.newUser.role_id ||
        (!this.user && !this.newUser.password)
      );
    },

    validationErrors() {
      let errors = Object.values(this.errors);
      errors = errors.flat();
      return errors || [];
    },
    companies() {
      return this.$store.state.companies;
    },
    currentUser() {
      return this.$store.state.user || {};
    },
  },
  mounted() {
    this.$http.get("roles").then((response) => {
      this.roles = response.data.rows;
    });
    if (this.currentUser.company_id) {
      this.$http.get("departments").then((response) => {
        this.departments = response.data.rows;
      });
    }
  },
  methods: {
    handleSave() {
      this.$http
        .post("users/store", this.$helper.generateFormData(this.newUser))
        .then((response) => {
          if (response.data.status) {
            this.$emit("saved", response.data.row);
            this.$notify({
              type: "success",
              message: response.data.message,
            });
          }
        })
        .catch((error) => {
          if (error.response.status == 400 || error.response.status == 422) {
            this.errors = error.response.data.errors;
            this.$notify({
              type: "error",
              message: "Form contains validation errors",
            });
          }
        });
    },
  },
};
</script>
