<script setup>
/** Company profile — field set aligned with TLP Settings › Company (`organization_settings`). */
import BaseButton from "../../components/base/BaseButton.vue";
import BaseIndex from "../../components/base/BaseIndex.vue";
import BaseInputText from "../../components/base/BaseInputText.vue";

import BaseAlert from "../../components/base/BaseAlert.vue";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";

import { api, ensureCsrf } from "../../services/api";

const router = useRouter();

const loading = ref(true);
const saving = ref(false);
const error = ref("");
const status = ref("");
const errors = ref({});

const form = reactive({
  company_name: "",
  kvk_number: "",
  vat_number: "",
  street: "",
  house_number: "",
  postal_code: "",
  city: "",
  country: "",
  phone: "",
  email: "",
  invoice_email: "",
  website: "",
  contact_name: "",
  iban: "",
});

onMounted(load);

async function load() {
  loading.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    const { data } = await api.get("/api/organization");
    defaultsFromApi(data ?? {});
  } catch {
    error.value =
      "Could not load the company profile. Check permissions, migrate/seed the database, or ensure a row exists in the organizations table.";
  } finally {
    loading.value = false;
  }
}

function defaultsFromApi(data) {
  form.company_name = data.company_name ?? data.name ?? "";
  form.kvk_number = data.kvk_number ?? "";
  form.vat_number = data.vat_number ?? "";
  form.street = data.street ?? data.address_line_1 ?? "";
  form.house_number = data.house_number ?? "";
  form.postal_code = data.postal_code ?? "";
  form.city = data.city ?? "";
  form.country = data.country ?? data.country_code ?? "";
  form.phone = data.phone ?? "";
  form.email = data.email ?? "";
  form.invoice_email = data.invoice_email ?? "";
  form.website = data.website ?? "";
  form.contact_name = data.contact_name ?? "";
  form.iban = data.iban ?? "";
}

function fieldError(key) {
  const e = errors.value[key];
  return Array.isArray(e) ? e[0] : e ?? "";
}

async function saveProfile() {
  saving.value = true;
  status.value = "";
  error.value = "";
  errors.value = {};
  try {
    await ensureCsrf();
    const { data } = await api.patch("/api/organization", {
      ...form,
      website: form.website || null,
    });
    defaultsFromApi(data);
    status.value = "Saved.";
  } catch (e) {
    if (e?.response?.status === 422 && e?.response?.data?.errors)
      errors.value = e.response.data.errors;
    else
      error.value =
        e?.response?.data?.message ?? "Could not save organisation settings.";
  } finally {
    saving.value = false;
  }
}
</script>

<template>
  test
  <BaseIndex
    subtitle="Legal name and address shown on invoices and letters (parity with Maestro TL company settings)."
    title="Bedrijfsgegevens"
  >
    <BaseAlert v-if="status" severity="success" closable @close="status = ''">{{
      status
    }}</BaseAlert>
    <BaseAlert v-if="error" severity="error">{{ error }}</BaseAlert>

    <div
      v-if="loading"
      class="card border border-surface rounded-2xl p-8 text-center text-surface-500"
    >
      Loading…
    </div>

    <form
      v-else
      class="flex flex-col gap-10"
      @submit.prevent="saveProfile"
    >
      <section class="flex flex-col gap-4">
        <h3 class="label-small uppercase tracking-wide text-surface-500 m-0">
          Algemeen
        </h3>
        <div class="grid gap-4 md:grid-cols-2">
          <BaseInputText
            v-model.trim="form.company_name"
            label="Bedrijfsnaam"
            required
            fluid
            :error="fieldError('company_name')"
          />
          <BaseInputText
            v-model.trim="form.kvk_number"
            label="KVK-nummer"
            fluid
            :error="fieldError('kvk_number')"
          />
          <BaseInputText
            v-model.trim="form.vat_number"
            label="BTW-nummer"
            fluid
            class="md:col-span-2"
            :error="fieldError('vat_number')"
          />
        </div>
      </section>

      <section class="flex flex-col gap-4">
        <h3 class="label-small uppercase tracking-wide text-surface-500 m-0">
          Adres
        </h3>
        <div class="grid gap-4 md:grid-cols-2">
          <BaseInputText
            v-model.trim="form.street"
            class="md:col-span-2"
            label="Straat"
            fluid
            :error="fieldError('street')"
          />
          <BaseInputText
            v-model.trim="form.house_number"
            label="Huisnummer"
            fluid
            :error="fieldError('house_number')"
          />
          <BaseInputText
            v-model.trim="form.postal_code"
            label="Postcode"
            fluid
            :error="fieldError('postal_code')"
          />
          <BaseInputText
            v-model.trim="form.city"
            label="Plaats"
            fluid
            :error="fieldError('city')"
          />
          <BaseInputText
            v-model.trim="form.country"
            label="Land"
            fluid
            :error="fieldError('country')"
          />
        </div>
      </section>

      <section class="flex flex-col gap-4">
        <h3 class="label-small uppercase tracking-wide text-surface-500 m-0">
          Contact
        </h3>
        <div class="grid gap-4 md:grid-cols-2">
          <BaseInputText
            v-model.trim="form.phone"
            label="Telefoon"
            fluid
            :error="fieldError('phone')"
          />
          <BaseInputText
            v-model.trim="form.email"
            type="email"
            label="Algemeen e-mailadres"
            fluid
            :error="fieldError('email')"
          />
          <BaseInputText
            v-model.trim="form.invoice_email"
            type="email"
            label="Factuur-e-mail"
            fluid
            class="md:col-span-2"
            :error="fieldError('invoice_email')"
          />
          <BaseInputText
            v-model.trim="form.website"
            label="Website"
            fluid
            placeholder="https://…"
            :error="fieldError('website')"
          />
          <BaseInputText
            v-model.trim="form.contact_name"
            label="Algemeen contactpersoon"
            fluid
            :error="fieldError('contact_name')"
          />
          <BaseInputText
            v-model.trim="form.iban"
            label="IBAN"
            fluid
            class="md:col-span-2"
            :error="fieldError('iban')"
          />
        </div>
      </section>

      <div class="flex justify-end gap-3">
        <BaseButton
          variant="secondary"
          outlined
          icon="cancel"
          type="button"
          @click="router.back()"
        >
          Annuleren
        </BaseButton>
        <BaseButton
          variant="primary"
          type="submit"
          icon="save"
          label="Opslaan"
          :loading="saving"
        />
      </div>
    </form>
  </BaseIndex>
  
</template>
