<?php
$mailboxes = is_array($mailboxes ?? null) ? $mailboxes : [];
$em = is_array($editMailbox ?? null) ? $editMailbox : null;
$isEdit = $em !== null;
?>

<section class="card">
  <h2 class="section-title">Skrzynki pocztowe</h2>
  <p class="muted mt-12">Konfiguracja skrzynek SMTP do wysylki wiadomosci e-mail.</p>

  <?php if (!empty($errorMessage)): ?>
    <div class="alert alert--danger mt-12" role="alert"><?= $e((string) $errorMessage) ?></div>
  <?php endif; ?>
  <?php if (!empty($successMessage)): ?>
    <div class="alert alert--success mt-12" role="status"><?= $e((string) $successMessage) ?></div>
  <?php endif; ?>
</section>

<section class="card mt-16">
  <h3 class="section-title">Lista skrzynek</h3>

  <?php if (count($mailboxes) === 0): ?>
    <p class="muted mt-12">Brak skrzynek pocztowych. Dodaj pierwsza skrzynke ponizej.</p>
  <?php else: ?>
    <div class="table-wrap mt-12">
      <table class="table">
        <thead>
          <tr>
            <th>Nazwa</th>
            <th>Serwer</th>
            <th>Port</th>
            <th>E-mail nadawcy</th>
            <th>Status</th>
            <th>Akcje</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($mailboxes as $mb): ?>
            <tr>
              <td>
                <?= $e((string) ($mb['name'] ?? '')) ?>
                <?php if (((int) ($mb['is_default'] ?? 0)) === 1): ?>
                  <span class="badge badge--info" style="margin-left:4px">Domyslna</span>
                <?php endif; ?>
              </td>
              <td><?= $e((string) ($mb['smtp_host'] ?? '')) ?></td>
              <td><?= (int) ($mb['smtp_port'] ?? 0) ?></td>
              <td><?= $e((string) ($mb['sender_email'] ?? '')) ?></td>
              <td>
                <?php if (((int) ($mb['is_active'] ?? 0)) === 1): ?>
                  <span class="badge badge--success">Aktywna</span>
                <?php else: ?>
                  <span class="badge badge--muted">Nieaktywna</span>
                <?php endif; ?>
              </td>
              <td style="white-space:nowrap">
                <a href="/settings/email-mailboxes?edit=<?= (int) ($mb['id'] ?? 0) ?>" class="btn btn--sm btn--secondary">Edytuj</a>
                <form action="/settings/email-mailboxes/toggle" method="post" style="display:inline">
                  <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                  <input type="hidden" name="id" value="<?= (int) ($mb['id'] ?? 0) ?>">
                  <button type="submit" class="btn btn--sm btn--secondary">
                    <?= ((int) ($mb['is_active'] ?? 0)) === 1 ? 'Dezaktywuj' : 'Aktywuj' ?>
                  </button>
                </form>
                <form action="/settings/email-mailboxes/delete" method="post" style="display:inline" class="js-confirm-delete">
                  <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
                  <input type="hidden" name="id" value="<?= (int) ($mb['id'] ?? 0) ?>">
                  <button type="button" class="btn btn--sm btn--danger js-delete-btn">Usun</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</section>

<section class="card mt-16">
  <h3 class="section-title"><?= $isEdit ? 'Edytuj skrzynke pocztowa' : 'Dodaj skrzynke pocztowa' ?></h3>

  <form action="/settings/email-mailboxes/save" method="post" novalidate class="mt-12" id="js-mailbox-form">
    <input type="hidden" name="_token" value="<?= $e($csrfToken ?? '') ?>">
    <?php if ($isEdit): ?>
      <input type="hidden" name="id" value="<?= (int) ($em['id'] ?? 0) ?>">
    <?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="100" required value="<?= $e((string) ($em['name'] ?? '')) ?>" placeholder="np. Glowna skrzynka">
      </label>
      <label class="form-field">
        <span class="field-label">E-mail nadawcy *</span>
        <input class="form-control" type="email" name="sender_email" maxlength="255" required value="<?= $e((string) ($em['sender_email'] ?? '')) ?>" placeholder="noreply@firma.pl">
      </label>
    </div>

    <div class="form-grid-2 mt-0">
      <label class="form-field">
        <span class="field-label">Nazwa nadawcy</span>
        <input class="form-control" type="text" name="sender_name" maxlength="200" value="<?= $e((string) ($em['sender_name'] ?? '')) ?>" placeholder="np. Sklep XYZ">
      </label>
      <div class="form-field"></div>
    </div>

    <h4 class="section-title mt-16">Ustawienia SMTP</h4>

    <div class="form-grid-3 mt-12">
      <label class="form-field">
        <span class="field-label">Serwer SMTP *</span>
        <input class="form-control" type="text" name="smtp_host" maxlength="255" required value="<?= $e((string) ($em['smtp_host'] ?? '')) ?>" placeholder="smtp.firma.pl">
      </label>
      <label class="form-field">
        <span class="field-label">Port *</span>
        <input class="form-control" type="number" name="smtp_port" min="1" max="65535" required value="<?= (int) ($em['smtp_port'] ?? 587) ?>">
      </label>
      <label class="form-field">
        <span class="field-label">Szyfrowanie</span>
        <select class="form-control" name="smtp_encryption">
          <option value="tls"<?= ((string) ($em['smtp_encryption'] ?? 'tls')) === 'tls' ? ' selected' : '' ?>>TLS (STARTTLS)</option>
          <option value="ssl"<?= ((string) ($em['smtp_encryption'] ?? '')) === 'ssl' ? ' selected' : '' ?>>SSL</option>
          <option value="none"<?= ((string) ($em['smtp_encryption'] ?? '')) === 'none' ? ' selected' : '' ?>>Brak</option>
        </select>
      </label>
    </div>

    <div class="form-grid-2 mt-0">
      <label class="form-field">
        <span class="field-label">Uzytkownik SMTP *</span>
        <input class="form-control" type="text" name="smtp_username" maxlength="255" required value="<?= $e((string) ($em['smtp_username'] ?? '')) ?>">
      </label>
      <label class="form-field">
        <span class="field-label">Haslo SMTP <?= $isEdit ? '' : '*' ?></span>
        <input class="form-control" type="password" name="smtp_password" maxlength="255" <?= $isEdit ? '' : 'required' ?> placeholder="<?= $isEdit ? '(bez zmian)' : '' ?>">
        <?php if ($isEdit): ?>
          <small class="field-hint">Pozostaw puste, aby zachowac aktualne haslo</small>
        <?php endif; ?>
      </label>
    </div>

    <div class="form-grid-2 mt-0">
      <label class="form-field" style="display:flex;align-items:center;gap:6px;flex-direction:row">
        <input type="checkbox" name="is_default" value="1"<?= ((int) ($em['is_default'] ?? 0)) === 1 ? ' checked' : '' ?>>
        <span class="field-label" style="margin:0">Domyslna skrzynka</span>
      </label>
      <label class="form-field" style="display:flex;align-items:center;gap:6px;flex-direction:row">
        <input type="checkbox" name="is_active" value="1"<?= $isEdit ? (((int) ($em['is_active'] ?? 0)) === 1 ? ' checked' : '') : ' checked' ?>>
        <span class="field-label" style="margin:0">Aktywna</span>
      </label>
    </div>

    <div class="form-actions mt-16">
      <button type="submit" class="btn btn--primary"><?= $isEdit ? 'Zapisz zmiany' : 'Dodaj skrzynke' ?></button>
      <button type="button" class="btn btn--secondary" id="js-test-connection">Testuj polaczenie</button>
      <?php if ($isEdit): ?>
        <a href="/settings/email-mailboxes" class="btn btn--secondary">Anuluj</a>
      <?php endif; ?>
    </div>
  </form>

  <div id="js-test-result" class="mt-12" style="display:none"></div>
</section>

<script>
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.js-delete-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var form = this.closest('form');
      if (window.OrderProAlerts && window.OrderProAlerts.confirm) {
        window.OrderProAlerts.confirm(
          'Usuwanie skrzynki',
          'Czy na pewno chcesz usunac te skrzynke pocztowa?',
          function() { form.submit(); }
        );
      } else {
        if (confirm('Czy na pewno chcesz usunac te skrzynke pocztowa?')) {
          form.submit();
        }
      }
    });
  });

  var testBtn = document.getElementById('js-test-connection');
  var resultDiv = document.getElementById('js-test-result');
  if (testBtn) {
    testBtn.addEventListener('click', function() {
      var form = document.getElementById('js-mailbox-form');
      var formData = new FormData(form);

      testBtn.disabled = true;
      testBtn.textContent = 'Testowanie...';
      resultDiv.style.display = 'none';

      fetch('/settings/email-mailboxes/test', {
        method: 'POST',
        body: formData
      })
      .then(function(response) { return response.json(); })
      .then(function(data) {
        resultDiv.style.display = 'block';
        if (data.success) {
          resultDiv.className = 'mt-12 alert alert--success';
        } else {
          resultDiv.className = 'mt-12 alert alert--danger';
        }
        resultDiv.textContent = data.message || 'Brak odpowiedzi';
      })
      .catch(function(err) {
        resultDiv.style.display = 'block';
        resultDiv.className = 'mt-12 alert alert--danger';
        resultDiv.textContent = 'Blad polaczenia: ' + err.message;
      })
      .finally(function() {
        testBtn.disabled = false;
        testBtn.textContent = 'Testuj polaczenie';
      });
    });
  }
});
</script>
