<template>
    <div class="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50">
      <div class="bg-white rounded-lg p-6 w-96">
        <h2 class="text-lg font-bold mb-4">Edit Akun</h2>

        <form @submit.prevent="updateAkun">
          <!-- Nama -->
          <div class="mb-3">
            <label class="block font-medium">Nama</label>
            <input v-model="form.nama" type="text" class="border rounded w-full p-2" required />
          </div>

          <!-- Password -->
          <div class="mb-3">
            <label class="block font-medium">Password</label>
            <input v-model="form.password" type="password" class="border rounded w-full p-2" />
            <small class="text-gray-500">Kosongkan jika tidak ingin mengubah password</small>
          </div>

          <!-- Peran -->
          <div class="mb-3">
            <label class="block font-medium">Peran</label>
            <select v-model="form.role" class="border rounded w-full p-2" required>
              <option value="">-- Pilih Peran --</option>
              <option value="owner">Owner</option>
              <option value="kasir">Kasir</option>
            </select>
          </div>

          <!-- Tombol -->
          <div class="flex justify-end gap-2 mt-4">
            <button type="button" @click="$emit('close')" class="bg-gray-300 px-4 py-2 rounded">
              Batal
            </button>
            <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded">
              Ubah
            </button>
          </div>
        </form>
      </div>
    </div>
  </template>

  <script>
  import axios from "axios";

  export default {
    props: {
      akun: {
        type: Object,
        required: true,
      },
    },
    data() {
      return {
        form: {
          nama: this.akun.nama || "",
          password: "",
          role: this.akun.role || "", // gunakan "role" bukan "peran"
        },
      };
    },
    watch: {
      akun: {
        handler(newVal) {
          if (newVal) {
            this.form = {
              nama: newVal.nama || "",
              password: "",
              role: newVal.role || "",
            };
          }
        },
        deep: true,
        immediate: true,
      },
    },
    methods: {
      async updateAkun() {
        try {
          const payload = { ...this.form };
          if (!payload.password) delete payload.password;

          await axios.put(`api/user/${this.akun.id}`, payload);

          this.$emit("refresh");
          this.$emit("close");
        } catch (err) {
          console.error("Gagal update akun:", err.response?.data || err.message);
          alert("Update akun gagal. Silakan cek kembali inputan.");
        }
      },
    },
  };
  </script>
