<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/content/partials/forms-summary-widget.php';

$currentUser = myronRequireAdministrationAccess();
$service = myronNotificationEmailsService();
$failures = myronFormNotificationFailureService();
$caller = myronActionCallerContextForUser($currentUser);

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = (string) ($_POST['action'] ?? '');
        if ($action === 'notification-emails.create') {
            $service->create($_POST, $caller);
            myronRedirectWithFlash(myronBuildAdminUrl('administration.notificationEmails'), 'Destination verification email sent.', 'success');
        } elseif ($action === 'notification-emails.resend') {
            $service->resendVerification((string) ($_POST['ne_id'] ?? ''));
            myronRedirectWithFlash(myronBuildAdminUrl('administration.notificationEmails'), 'Destination verification email resent.', 'success');
        } elseif ($action === 'notification-emails.set-default') {
            $service->setDefault((string) ($_POST['ne_id'] ?? ''));
            myronRedirectWithFlash(myronBuildAdminUrl('administration.notificationEmails'), 'Default destination updated.', 'success');
        } elseif ($action === 'notification-emails.delete') {
            $service->delete((string) ($_POST['ne_id'] ?? ''));
            myronRedirectWithFlash(myronBuildAdminUrl('administration.notificationEmails'), 'Destination deleted.', 'success');
        } elseif ($action === 'failures.retry') {
            $failures->retry((string) ($_POST['failure_id'] ?? ''), (string) ($_POST['submission_id'] ?? ''));
            myronRedirectWithFlash(myronBuildAdminUrl('administration.notificationEmails'), 'Delivery retry attempted.', 'success');
        } elseif ($action === 'failures.dismiss') {
            $failures->dismiss((string) ($_POST['failure_id'] ?? ''));
            myronRedirectWithFlash(myronBuildAdminUrl('administration.notificationEmails'), 'Delivery failure dismissed.', 'success');
        }
        throw new RuntimeException('Unknown verified destination action.');
    } catch (Throwable $exception) {
        myronRedirectWithFlash(myronBuildAdminUrl('administration.notificationEmails'), $exception->getMessage(), 'error');
    }
}

$emails = $service->list(false)['notificationEmails'] ?? [];
$failureRows = $failures->listRecent()['failures'] ?? [];
$csrfToken = myronCsrfToken();

myronRenderAdminShellStart($currentUser, [
    'title' => 'Verified Destinations',
    'titleContext' => 'Administration',
    'activeItem' => 'notification-emails',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Administration', 'href' => myronBuildAdminUrl('identity.users')],
      ['label' => 'Verified Destinations'],
  ]); ?>
  <div class="mc-workspace__title-row"><h1 class="mc-workspace__title">Verified Destinations</h1></div>
  <p class="mc-workspace__subtitle">Manage internal recipient addresses that can receive form submissions and workflow notifications. Forms can route submissions to any verified destination; subscriber and customer opt-in lists are a separate surface.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <section class="sg-section">
      <h2 class="sg-section__title">Add Destination</h2>
      <form method="post" class="sg-form-grid">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
        <input type="hidden" name="action" value="notification-emails.create">
        <label class="sg-field"><span class="sg-field__label">Destination Label</span><input class="sg-field__control" name="label" required placeholder="Leads, Support, Editorial"></label>
        <label class="sg-field"><span class="sg-field__label">Email Address</span><input class="sg-field__control" type="email" name="address" required placeholder="intake@example.com"></label>
        <div class="sg-card__actions"><button class="sg-button sg-button--primary" type="submit">Send Verification</button></div>
      </form>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Destinations</h2>
      <table class="mc-tables-bank__grid">
        <thead><tr><th>Label</th><th>Address</th><th>Status</th><th>Default</th><th>Actions</th></tr></thead>
        <tbody>
          <?php if ($emails === []): ?><tr><td colspan="5">No destinations yet. Add and verify an address before routing form submissions to it.</td></tr><?php endif; ?>
          <?php foreach ($emails as $email): ?>
          <tr>
            <td><?= myronEscape((string) $email['label']) ?></td>
            <td><?= myronEscape((string) $email['address']) ?></td>
            <td><?= (string) ($email['verified_at'] ?? '') !== '' ? 'Verified' : 'Unverified' ?></td>
            <td>
              <form method="post">
                <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
                <input type="hidden" name="action" value="notification-emails.set-default">
                <input type="hidden" name="ne_id" value="<?= myronEscape((string) $email['id']) ?>">
                <button class="sg-button sg-button--secondary" type="submit"<?= (string) ($email['verified_at'] ?? '') === '' || !empty($email['is_default']) ? ' disabled' : '' ?>><?= !empty($email['is_default']) ? 'Default' : 'Set Default' ?></button>
              </form>
            </td>
            <td>
              <?php if ((string) ($email['verified_at'] ?? '') === ''): ?>
              <form method="post" style="display:inline"><input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>"><input type="hidden" name="action" value="notification-emails.resend"><input type="hidden" name="ne_id" value="<?= myronEscape((string) $email['id']) ?>"><button class="sg-button sg-button--secondary" type="submit">Resend</button></form>
              <?php endif; ?>
              <form method="post" style="display:inline"><input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>"><input type="hidden" name="action" value="notification-emails.delete"><input type="hidden" name="ne_id" value="<?= myronEscape((string) $email['id']) ?>"><button class="sg-button sg-button--danger" type="submit" onclick="return confirm('Delete this destination? Forms using it will fall back to the default destination.');">Delete</button></form>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </section>

    <section class="sg-section">
      <h2 class="sg-section__title">Recent Delivery Failures</h2>
      <p class="sg-section__subtitle">Delivery failures are retained for form submission routing and workflow notifications sent through verified destinations.</p>
      <table class="mc-tables-bank__grid">
        <thead><tr><th>Attempted</th><th>Form</th><th>Recipient</th><th>Reason</th><th>Retries</th><th>Actions</th></tr></thead>
        <tbody>
          <?php if ($failureRows === []): ?><tr><td colspan="6">No recent delivery failures.</td></tr><?php endif; ?>
          <?php foreach ($failureRows as $failure): ?>
          <tr>
            <td><?= myronEscape((string) ($failure['attempted_at'] ?? '')) ?></td>
            <td><?= myronEscape((string) ($failure['form_name'] ?? $failure['form_id'] ?? '')) ?></td>
            <td><?= myronEscape((string) ($failure['recipient_email'] ?? '')) ?></td>
            <td><?= myronEscape((string) ($failure['failure_reason'] ?? '')) ?></td>
            <td><?= (int) ($failure['retry_count'] ?? 0) ?></td>
            <td>
              <form method="post" style="display:inline"><input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>"><input type="hidden" name="action" value="failures.retry"><input type="hidden" name="failure_id" value="<?= myronEscape((string) $failure['id']) ?>"><input type="hidden" name="submission_id" value="<?= myronEscape((string) $failure['submission_id']) ?>"><button class="sg-button sg-button--secondary" type="submit">Retry</button></form>
              <form method="post" style="display:inline"><input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>"><input type="hidden" name="action" value="failures.dismiss"><input type="hidden" name="failure_id" value="<?= myronEscape((string) $failure['id']) ?>"><button class="sg-button sg-button--secondary" type="submit">Dismiss</button></form>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </section>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
