<?php /** @var string $title */ ?>
<div class="card">
  <h1><?= htmlspecialchars($title ?? 'Parâmetros do Sistema') ?></h1>
  <p class="muted">Defina moeda, fuso horário, formato de data e dicas da interface.</p>
  <section class="card">
    <div class="form-row cols-2">
      <div class="form-group">
        <label>Moeda</label>
        <select id="sys_currency">
          <option value="BRL">BRL (Real)</option>
          <option value="USD">USD (Dólar)</option>
          <option value="EUR">EUR (Euro)</option>
          <option value="GBP">GBP (Libra)</option>
          <option value="ARS">ARS (Peso Arg.)</option>
        </select>
      </div>
      <div class="form-group">
        <label>Fuso horário</label>
        <input id="sys_timezone" list="tz_list" placeholder="America/Sao_Paulo" />
        <datalist id="tz_list">
          <option value="America/Sao_Paulo"></option>
          <option value="America/Fortaleza"></option>
          <option value="America/Manaus"></option>
          <option value="America/Recife"></option>
          <option value="America/Bahia"></option>
          <option value="America/Belem"></option>
          <option value="America/Porto_Velho"></option>
          <option value="America/Cuiaba"></option>
          <option value="America/Bogota"></option>
          <option value="America/New_York"></option>
          <option value="Europe/Lisbon"></option>
          <option value="Europe/Madrid"></option>
          <option value="Europe/London"></option>
        </datalist>
        <small class="muted">Use uma região válida (IANA), ex.: America/Sao_Paulo</small>
      </div>
      <div class="form-group">
        <label>Formato de data</label>
        <input id="sys_date_format" type="text" placeholder="d/m/Y" />
        <small class="muted">Exemplos: d/m/Y, m-d-Y, Y-m-d</small>
      </div>
      <div class="form-group">
        <label>
          <input id="sys_show_tips" type="checkbox" /> Mostrar dicas na interface
        </label>
      </div>
    </div>
    <div class="header" style="margin-top:.5rem;">
      <div></div>
      <div style="display:flex; gap:.5rem;">
        <button id="btn_save_params" class="btn">Salvar</button>
        <button id="btn_cancel_params" class="btn-outline">Cancelar</button>
      </div>
    </div>
  </section>
  <div style="margin-top:.5rem">
    <strong>Prévia:</strong>
    <span id="preview_date" class="muted" style="margin-left:.25rem">—</span>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
  const $ = (id) => document.getElementById(id);
  const api = '/api/settings';
  const datePreview = () => {
    const fmt = $('sys_date_format').value.trim() || 'd/m/Y';
    try {
      const d = new Date('2025-01-15T13:45:00-03:00');
      const map = {
        'd': String(d.getDate()).padStart(2,'0'),
        'm': String(d.getMonth()+1).padStart(2,'0'),
        'Y': String(d.getFullYear()),
      };
      let out = '';
      for (let i=0; i<fmt.length; i++) {
        const c = fmt[i];
        out += (map[c] ?? c);
      }
      $('preview_date').textContent = out;
    } catch(_) { $('preview_date').textContent = '—'; }
  };
  // Carregar parâmetros atuais
  fetch(api, { headers: { 'Accept': 'application/json' }})
    .then(r => r.ok ? r.json() : Promise.reject(r))
    .then(json => {
      const s = json.settings || {};
      $('sys_currency').value = (s.currency || 'BRL').toUpperCase();
      $('sys_timezone').value = s.timezone || 'America/Sao_Paulo';
      $('sys_date_format').value = s.date_format || 'd/m/Y';
      $('sys_show_tips').checked = !!s.show_tips;
      datePreview();
    })
    .catch(() => { /* silencioso */ });

  $('sys_date_format').addEventListener('input', datePreview);

  $('btn_save_params').addEventListener('click', async () => {
    const payload = {
      currency: $('sys_currency').value.trim().toUpperCase() || 'BRL',
      timezone: $('sys_timezone').value.trim() || 'America/Sao_Paulo',
      date_format: $('sys_date_format').value.trim() || 'd/m/Y',
      show_tips: $('sys_show_tips').checked
    };
    // Validações rápidas de UI
    if (!/^[A-Z]{3}$/.test(payload.currency)) {
      alert('Moeda inválida. Use código ISO de 3 letras, ex.: BRL');
      return;
    }
    if (!payload.timezone.includes('/')) {
      alert('Fuso horário inválido. Use formato IANA, ex.: America/Sao_Paulo');
      return;
    }
    try {
      const res = await fetch(api, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        alert('Erro ao salvar: ' + (err.error || res.status));
        return;
      }
      alert('Parâmetros salvos com sucesso');
    } catch (e) {
      alert('Falha na requisição');
    }
  });

  $('btn_cancel_params').addEventListener('click', () => {
    window.location.reload();
  });
});
</script>
