<?php
require_once __DIR__ . '/includes/orders.php';

$pageTitle  = 'Firma mea';
$breadcrumb = [['label' => 'Orders', 'url' => url('orders.php')], ['label' => 'Firma mea']];

$company = order_company();

// Câmpurile formularului: cheia din app_settings e 'order_company_' . key
$fields = [
    ['key' => 'name',    'label' => 'Denumire firmă', 'ph' => 'ex: Zoto Mag SRL',             'span' => 'md:col-span-2'],
    ['key' => 'cui',     'label' => 'CUI / VAT',      'ph' => 'ex: RO12345678',               'span' => ''],
    ['key' => 'reg',     'label' => 'Reg. comerțului','ph' => 'ex: J40/1234/2020',            'span' => ''],
    ['key' => 'address', 'label' => 'Adresă',         'ph' => 'stradă, număr, bloc',          'span' => 'md:col-span-2'],
    ['key' => 'city',    'label' => 'Oraș / județ',   'ph' => 'ex: București, Sector 3',      'span' => ''],
    ['key' => 'country', 'label' => 'Țară',           'ph' => 'ex: România',                  'span' => ''],
    ['key' => 'phone',   'label' => 'Telefon',        'ph' => 'ex: +40 7xx xxx xxx',          'span' => ''],
    ['key' => 'email',   'label' => 'Email',          'ph' => 'ex: comenzi@firma.ro',         'span' => ''],
    ['key' => 'web',     'label' => 'Website',        'ph' => 'ex: www.firma.ro',             'span' => 'md:col-span-2'],
    ['key' => 'bank',    'label' => 'Bancă',          'ph' => 'ex: Banca Transilvania',       'span' => 'md:col-span-2'],
    ['key' => 'iban',    'label' => 'IBAN',           'ph' => 'ex: RO49BTRL1234567890000',    'span' => 'md:col-span-2'],
];

$labelsRo = order_labels('ro');
$labelsEn = order_labels('en');

require __DIR__ . '/includes/header.php';
?>

<div x-data="companyPage({
       values: <?= htmlspecialchars(json_encode($company), ENT_QUOTES, 'UTF-8') ?>,
       labels: <?= htmlspecialchars(json_encode(['ro' => $labelsRo, 'en' => $labelsEn]), ENT_QUOTES, 'UTF-8') ?>,
       csrf: '<?= e(csrf_token()) ?>'
     })">

  <div class="flex items-center gap-3 flex-wrap mb-4">
    <h1 class="text-2xl font-bold text-slate-900">Firma mea</h1>
    <span class="text-sm text-slate-400">datele care apar în antetul comenzilor (PDF / XLS)</span>
    <div class="flex-1"></div>
    <span class="text-sm text-emerald-600 font-medium" x-show="saved" x-cloak x-transition>✓ salvat</span>
  </div>

  <?= order_tabs('firma') ?>

  <div class="grid grid-cols-1 lg:grid-cols-3 gap-4">

    <!-- Formular -->
    <div class="lg:col-span-2 bg-white border border-slate-100 rounded-xl shadow-soft p-4">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
        <?php foreach ($fields as $f): ?>
          <div class="<?= $f['span'] ?>">
            <label class="block text-xs font-medium text-slate-600 mb-1"><?= e($f['label']) ?></label>
            <input type="text" x-model="v.<?= e($f['key']) ?>" @change="save('<?= e($f['key']) ?>')"
              placeholder="<?= e($f['ph']) ?>"
              class="w-full px-3 py-2 text-sm border border-slate-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-500">
          </div>
        <?php endforeach; ?>
      </div>
      <p class="text-[11px] text-slate-400 mt-3">
        Se salvează automat la ieșirea din câmp. Câmpurile goale nu apar pe document.
      </p>
    </div>

    <!-- Previzualizare antet -->
    <div class="bg-white border border-slate-100 rounded-xl shadow-soft p-4">
      <div class="flex items-center justify-between gap-2 mb-3">
        <h2 class="text-sm font-semibold text-slate-800">Cum arată pe comandă</h2>
        <select x-model="lang"
          class="px-2 py-1 text-xs text-slate-600 border border-slate-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-brand-500">
          <option value="ro">Română</option>
          <option value="en">English</option>
        </select>
      </div>

      <div class="border border-slate-200 rounded-lg p-3 bg-slate-50/60">
        <div class="text-[13px] font-bold text-slate-900" x-text="v.name || (labels[lang].company_ph)"
             :class="v.name ? '' : 'text-slate-400'"></div>
        <template x-for="line in headerLines()" :key="line">
          <div class="text-[11px] text-slate-500 leading-relaxed" x-text="line"></div>
        </template>
        <div class="mt-3 pt-2 border-t-2 border-slate-900"></div>
        <div class="mt-1 text-right text-[13px] font-bold text-slate-900" x-text="labels[lang].doc_title"></div>
        <div class="text-right text-[11px] font-mono text-brand-600 font-bold">CMD-<?= date('Y') ?>-0001</div>
      </div>

      <p class="text-[11px] text-slate-400 mt-3">
        Limba se alege pe fiecare comandă în parte — aici e doar previzualizarea etichetelor.
      </p>
    </div>
  </div>
</div>

<script>
function companyPage(cfg) {
  return {
    v: cfg.values,
    labels: cfg.labels,
    csrf: cfg.csrf,
    lang: 'ro',
    saved: false,

    // Aceleași linii ca în antetul documentului printat.
    headerLines() {
      const t = this.labels[this.lang], v = this.v, out = [];
      const id = [v.cui ? `${t.vat_id}: ${v.cui}` : '', v.reg ? `${t.reg}: ${v.reg}` : ''].filter(Boolean).join(' · ');
      if (id) out.push(id);
      const addr = [v.address, v.city, v.country].filter(Boolean).join(', ');
      if (addr) out.push(addr);
      const contact = [v.phone ? `${t.phone}: ${v.phone}` : '', v.email, v.web].filter(Boolean).join(' · ');
      if (contact) out.push(contact);
      const bank = [v.bank, v.iban ? `${t.iban}: ${v.iban}` : ''].filter(Boolean).join(' · ');
      if (bank) out.push(bank);
      return out;
    },

    async save(key) {
      try {
        const fd = new FormData();
        fd.append('csrf_token', this.csrf);
        fd.append('key', 'order_company_' + key);
        fd.append('value', this.v[key] ?? '');
        const r = await fetch('<?= url('api/save-setting.php') ?>', { method: 'POST', body: fd });
        const j = await r.json();
        if (!j.ok) throw new Error(j.error || 'Eroare');
        this.saved = true;
        setTimeout(() => { this.saved = false; }, 1500);
      } catch (e) {
        alert('Nu am putut salva: ' + e.message);
      }
    }
  };
}
</script>

<?php require __DIR__ . '/includes/footer.php'; ?>
