<?php

declare(strict_types=1);

function myronRenderFormsSummaryWidget(): void
{
    $repo = myronMicFormSubmissionRepository();
    $today = gmdate('Y-m-d 00:00:00');
    $week = gmdate('Y-m-d 00:00:00', time() - 6 * 86400);
    $month = gmdate('Y-m-01 00:00:00');
    $recent = $repo->listRecentAcrossForms(5);
    ?>
    <section class="sg-section mc-forms-summary-widget" aria-label="Forms summary">
      <div class="mc-page-summary">
        <div class="mc-page-summary__item"><span class="mc-page-summary__label">Submissions today</span><strong><?= (int) $repo->countTotal($today) ?></strong></div>
        <div class="mc-page-summary__item"><span class="mc-page-summary__label">This week</span><strong><?= (int) $repo->countTotal($week) ?></strong></div>
        <div class="mc-page-summary__item"><span class="mc-page-summary__label">This month</span><strong><?= (int) $repo->countTotal($month) ?></strong></div>
      </div>
      <div class="mc-workspace__title-row">
        <h3 class="sg-section__title">Recent submissions</h3>
        <a class="sg-button sg-button--secondary" href="<?= myronEscape(myronBuildAdminUrl('design.forms')) ?>">View all</a>
      </div>
      <?php if ($recent === []): ?>
        <p class="sg-section__subtitle">No submissions yet.</p>
      <?php else: ?>
        <ul class="mc-forms-summary-widget__list">
          <?php foreach ($recent as $submission): ?>
            <?php $fields = is_array($submission['fields'] ?? null) ? $submission['fields'] : []; ?>
            <li><strong><?= myronEscape((string) ($submission['form_name'] ?? 'Form')) ?></strong> · <?= myronEscape((string) ($submission['submitted_at'] ?? '')) ?> · <?= myronEscape(substr(myronFormSubmissionPreview($fields), 0, 60)) ?></li>
          <?php endforeach; ?>
        </ul>
      <?php endif; ?>
    </section>
    <?php
}

function myronFormSubmissionPreview(array $fields): string
{
    foreach ($fields as $key => $value) {
        if (str_contains((string) $key, 'email') && trim((string) $value) !== '') {
            return (string) $value;
        }
    }
    foreach ($fields as $value) {
        if (trim((string) $value) !== '') {
            return (string) $value;
        }
    }
    return 'Submission';
}
