<?php
$emailTemplatesList = is_array($emailTemplates ?? null) ? $emailTemplates : [];
$emailMailboxesList = is_array($emailMailboxes ?? null) ? $emailMailboxes : [];
$buyerEmailAddr = '';
foreach ($addressesList as $addr) {
    if (($addr['address_type'] ?? '') === 'customer' && trim((string) ($addr['email'] ?? '')) !== '') {
        $buyerEmailAddr = trim((string) $addr['email']);
        break;
    }
}
if ($buyerEmailAddr === '') {
    foreach ($addressesList as $addr) {
        $email = trim((string) ($addr['email'] ?? ''));
        if ($email !== '') {
            $buyerEmailAddr = $email;
            break;
        }
    }
}
$emailEnabled = $emailTemplatesList !== [] && $emailMailboxesList !== [] && $buyerEmailAddr !== '';
?>

<?php if ($emailEnabled): ?>
<div class="email-send-overlay" id="emailSendOverlay" style="display:none">
  <div class="email-send-modal">
    <div class="email-send-modal__header">
      <h3>Wyslij e-mail</h3>
      <button type="button" class="email-send-modal__close" id="emailSendClose">&times;</button>
    </div>
    <div class="email-send-modal__body">
      <div class="email-send-modal__field">
        <label>Odbiorca</label>
        <input type="text" class="input" value="<?= $e($buyerEmailAddr) ?>" readonly>
      </div>
      <div class="email-send-modal__field">
        <label>Szablon</label>
        <select class="input" id="emailTemplateSelect">
          <option value="">-- wybierz szablon --</option>
          <?php foreach ($emailTemplatesList as $tpl): ?>
            <option value="<?= $e((string) ($tpl['id'] ?? '')) ?>"><?= $e((string) ($tpl['name'] ?? '')) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="email-send-modal__field">
        <label>Skrzynka</label>
        <select class="input" id="emailMailboxSelect">
          <option value="">Domyslna z szablonu</option>
          <?php foreach ($emailMailboxesList as $mbx): ?>
            <option value="<?= $e((string) ($mbx['id'] ?? '')) ?>">
              <?= $e((string) ($mbx['name'] ?? '')) ?> (<?= $e((string) ($mbx['sender_email'] ?? '')) ?>)
              <?= (int) ($mbx['is_default'] ?? 0) === 1 ? ' [domyslna]' : '' ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="email-send-modal__actions-top">
        <button type="button" class="btn btn--secondary btn--sm" id="emailPreviewBtn" disabled>Podglad</button>
      </div>
      <div class="email-send-preview" id="emailPreviewArea" style="display:none">
        <div class="email-send-preview__subject" id="emailPreviewSubject"></div>
        <div class="email-send-preview__body" id="emailPreviewBody"></div>
        <div class="email-send-preview__attachments" id="emailPreviewAttachments" style="display:none"></div>
      </div>
    </div>
    <div class="email-send-modal__footer">
      <button type="button" class="btn btn--secondary" id="emailSendCancel">Anuluj</button>
      <button type="button" class="btn btn--primary" id="emailSendBtn" disabled>Wyslij</button>
    </div>
  </div>
</div>

<script>
(function () {
  var overlay = document.getElementById('emailSendOverlay');
  var openBtn = document.getElementById('btn-send-email');
  var closeBtn = document.getElementById('emailSendClose');
  var cancelBtn = document.getElementById('emailSendCancel');
  var previewBtn = document.getElementById('emailPreviewBtn');
  var sendBtn = document.getElementById('emailSendBtn');
  var templateSelect = document.getElementById('emailTemplateSelect');
  var mailboxSelect = document.getElementById('emailMailboxSelect');
  var previewArea = document.getElementById('emailPreviewArea');
  var previewSubject = document.getElementById('emailPreviewSubject');
  var previewBody = document.getElementById('emailPreviewBody');
  var previewAttachments = document.getElementById('emailPreviewAttachments');
  var orderId = <?= (int) ($orderId ?? 0) ?>;
  var csrfToken = <?= json_encode((string) ($csrfToken ?? '')) ?>;

  if (!overlay || !openBtn) return;

  function openModal() { overlay.style.display = 'flex'; }
  function closeModal() {
    overlay.style.display = 'none';
    previewArea.style.display = 'none';
    templateSelect.value = '';
    previewBtn.disabled = true;
    sendBtn.disabled = true;
  }

  openBtn.addEventListener('click', openModal);
  closeBtn.addEventListener('click', closeModal);
  cancelBtn.addEventListener('click', closeModal);
  overlay.addEventListener('click', function (ev) {
    if (ev.target === overlay) closeModal();
  });

  templateSelect.addEventListener('change', function () {
    var hasTemplate = templateSelect.value !== '';
    previewBtn.disabled = !hasTemplate;
    sendBtn.disabled = !hasTemplate;
    previewArea.style.display = 'none';
  });

  previewBtn.addEventListener('click', function () {
    var tplId = templateSelect.value;
    if (!tplId) return;
    previewBtn.disabled = true;
    previewBtn.textContent = 'Ladowanie...';

    var formData = new FormData();
    formData.append('_token', csrfToken);
    formData.append('template_id', tplId);

    fetch('/orders/' + orderId + '/email-preview', { method: 'POST', body: formData })
      .then(function (r) { return r.json(); })
      .then(function (data) {
        previewSubject.textContent = 'Temat: ' + (data.subject || '');
        previewBody.innerHTML = data.body_html || '';
        if (data.attachments && data.attachments.length > 0) {
          previewAttachments.style.display = 'block';
          previewAttachments.textContent = 'Zalaczniki: ' + data.attachments.join(', ');
        } else {
          previewAttachments.style.display = 'none';
        }
        previewArea.style.display = 'block';
      })
      .catch(function () {
        previewBody.textContent = 'Blad ladowania podgladu';
        previewArea.style.display = 'block';
      })
      .finally(function () {
        previewBtn.disabled = false;
        previewBtn.textContent = 'Podglad';
      });
  });

  sendBtn.addEventListener('click', function () {
    var tplId = templateSelect.value;
    if (!tplId) return;

    sendBtn.disabled = true;
    sendBtn.textContent = 'Wysylanie...';

    var formData = new FormData();
    formData.append('_token', csrfToken);
    formData.append('template_id', tplId);
    var mbxId = mailboxSelect.value;
    if (mbxId) formData.append('mailbox_id', mbxId);

    fetch('/orders/' + orderId + '/send-email', { method: 'POST', body: formData })
      .then(function (r) { return r.json(); })
      .then(function (data) {
        if (data.success) {
          closeModal();
          if (window.OrderProAlerts) {
            window.OrderProAlerts.success(data.message || 'E-mail wyslany');
          }
          setTimeout(function () { location.reload(); }, 1500);
        } else {
          if (window.OrderProAlerts) {
            window.OrderProAlerts.error(data.message || 'Blad wysylki');
          }
        }
      })
      .catch(function () {
        if (window.OrderProAlerts) {
          window.OrderProAlerts.error('Blad polaczenia z serwerem');
        }
      })
      .finally(function () {
        sendBtn.disabled = false;
        sendBtn.textContent = 'Wyslij';
      });
  });
})();
</script>
<?php endif; ?>
