<?php
/** @var array<string, mixed>|null $config */
$config = is_array($config ?? null) ? $config : null;
$fakturowniaSettings = is_array($fakturowniaSettings ?? null) ? $fakturowniaSettings : [];
$isEdit = $config !== null;
$cid = (int) ($config['id'] ?? 0);

$name = (string) ($config['name'] ?? '');
$numberFormat = (string) ($config['number_format'] ?? 'FV/%N/%M/%Y');
$numberingType = (string) ($config['numbering_type'] ?? 'monthly');
$saleDateSource = (string) ($config['sale_date_source'] ?? 'issue_date');
$orderReference = (string) ($config['order_reference'] ?? 'none');
$paymentToDays = (int) ($config['payment_to_days'] ?? 7);
$defaultKind = (string) ($config['default_kind'] ?? 'vat');
$isDelegated = ((int) ($config['is_delegated'] ?? 0)) === 1;
$isActive = $isEdit ? ((int) ($config['is_active'] ?? 0)) === 1 : true;
$fakturowniaConfigured = trim((string) ($fakturowniaSettings['account_prefix'] ?? '')) !== ''
    && !empty($fakturowniaSettings['has_api_token']);
$fakturowniaActive = !empty($fakturowniaSettings['is_active']);

$success = trim((string) ($successMessage ?? ''));
$error = trim((string) ($errorMessage ?? ''));
?>

<section class="card">
  <p class="muted" style="margin-bottom:8px"><a href="/settings/accounting">Ksiegowosc</a> &raquo; <a href="/settings/accounting/invoices">Faktury</a></p>
  <h2 class="section-title"><?= $isEdit ? 'Edycja konfiguracji faktury' : 'Nowa konfiguracja faktury' ?></h2>

  <?php if ($error !== ''): ?>
    <div class="mt-12"><?php $type='danger'; $message=(string) $error; $dismissible=true; include dirname(__DIR__) . '/components/alert.php'; ?></div>
  <?php endif; ?>
  <?php if ($success !== ''): ?>
    <div class="mt-12"><?php $type='success'; $message=(string) $success; $dismissible=true; include dirname(__DIR__) . '/components/alert.php'; ?></div>
  <?php endif; ?>
</section>

<section class="card mt-16">
  <form action="/settings/accounting/invoices/save" method="post" novalidate class="mt-12">
    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
    <?php if ($isEdit): ?>
      <input type="hidden" name="id" value="<?= $cid ?>">
    <?php endif; ?>

    <div class="form-grid-2">
      <label class="form-field">
        <span class="field-label">Nazwa *</span>
        <input class="form-control" type="text" name="name" maxlength="128" required value="<?= $e($name) ?>">
      </label>
      <label class="form-field">
        <span class="field-label">Format numeru *</span>
        <input class="form-control" type="text" name="number_format" maxlength="64" required placeholder="FV/%N/%M/%Y" value="<?= $e($numberFormat) ?>">
        <small class="field-hint"><code>%N</code> = numer, <code>%M</code> = miesiac (01-12), <code>%Y</code> = rok (4 cyfry)</small>
      </label>
    </div>

    <div class="form-grid-3 mt-0">
      <label class="form-field">
        <span class="field-label">Numerowanie</span>
        <select class="form-control" name="numbering_type">
          <option value="monthly"<?= $numberingType === 'monthly' ? ' selected' : '' ?>>Miesieczne</option>
          <option value="yearly"<?= $numberingType === 'yearly' ? ' selected' : '' ?>>Roczne</option>
        </select>
      </label>
      <label class="form-field">
        <span class="field-label">Data sprzedazy</span>
        <select class="form-control" name="sale_date_source">
          <option value="issue_date"<?= $saleDateSource === 'issue_date' ? ' selected' : '' ?>>Data wystawienia</option>
          <option value="order_date"<?= $saleDateSource === 'order_date' ? ' selected' : '' ?>>Data zamowienia</option>
          <option value="payment_date"<?= $saleDateSource === 'payment_date' ? ' selected' : '' ?>>Data platnosci</option>
        </select>
      </label>
      <label class="form-field">
        <span class="field-label">Numer referencyjny zamowienia</span>
        <select class="form-control" name="order_reference">
          <option value="none"<?= $orderReference === 'none' ? ' selected' : '' ?>>Brak</option>
          <option value="orderpro"<?= $orderReference === 'orderpro' ? ' selected' : '' ?>>orderPRO</option>
          <option value="integration"<?= $orderReference === 'integration' ? ' selected' : '' ?>>Zewnetrzny</option>
        </select>
      </label>
    </div>

    <div class="form-grid-3 mt-0">
      <label class="form-field">
        <span class="field-label">Termin platnosci (dni)</span>
        <input class="form-control" type="number" name="payment_to_days" min="0" max="365" value="<?= $paymentToDays ?>">
      </label>
      <label class="form-field">
        <span class="field-label">Typ dokumentu</span>
        <select class="form-control" name="default_kind">
          <option value="vat"<?= $defaultKind === 'vat' ? ' selected' : '' ?>>Faktura VAT</option>
          <option value="proforma"<?= $defaultKind === 'proforma' ? ' selected' : '' ?>>Proforma</option>
          <option value="invoice_other"<?= $defaultKind === 'invoice_other' ? ' selected' : '' ?>>Inna</option>
        </select>
      </label>
      <label class="form-field" style="display:flex;align-items:center;gap:6px;flex-direction:row">
        <input type="checkbox" name="is_active" value="1"<?= $isActive ? ' checked' : '' ?>>
        <span class="field-label" style="margin:0">Konfiguracja aktywna</span>
      </label>
    </div>

    <div class="form-field mt-12">
      <label style="display:flex;align-items:center;gap:6px">
        <input type="checkbox" name="is_delegated" value="1" data-invoice-delegated<?= $isDelegated ? ' checked' : '' ?>>
        <span class="field-label" style="margin:0">Deleguj wystawianie do Fakturowni</span>
      </label>
      <small class="field-hint">Gdy zaznaczone, faktury beda generowane po stronie Fakturowni (numer + PDF). W przeciwnym razie numeracja i PDF lokalne.</small>
    </div>

    <div class="form-field mt-12" data-invoice-delegation<?= $isDelegated ? '' : ' style="display:none"' ?>>
      <span class="field-label">Konto Fakturowni</span>
      <?php if ($fakturowniaConfigured && $fakturowniaActive): ?>
        <span class="badge badge--success">Globalna konfiguracja aktywna</span>
      <?php elseif ($fakturowniaConfigured): ?>
        <span class="badge badge--muted">Globalna konfiguracja nieaktywna</span>
      <?php else: ?>
        <span class="badge badge--muted">Brak konfiguracji</span>
      <?php endif; ?>
      <small class="field-hint">Delegowane faktury uzywaja jednej globalnej konfiguracji z <a href="/settings/integrations/fakturownia">Integracje &gt; Fakturownia</a>.</small>
    </div>

    <div class="form-actions mt-16">
      <button type="submit" class="btn btn--primary"><?= $isEdit ? 'Zapisz zmiany' : 'Dodaj konfiguracje' ?></button>
      <a href="/settings/accounting/invoices" class="btn btn--secondary">Anuluj</a>
    </div>
  </form>
</section>
