<?php
// pages/components/dashboard_summary.php
// Summary KPI widget extracted from dashboard for HTMX on-demand and auto-refresh loading
// All inline HTML is captured with output buffering

// Load data via AnalyticsProvider (wraps legacy dashboard_statsbar or returns demo values)
$emailsSent = 0;
$monthsAgo = 0;
$beginningIso = '';

// KPI buckets
$bouncedPercent = 0;
$bouncedCount = 0;
$openedPercent = 0;
$openedCount = 0;
$clickPercent = 0;
$clickCount = 0;
$orderPercent = 0;
$orderCount = 0;
$mobilePercent = 0;
$mobileCount = 0;
$revenue = '0';
$voucherSum = '0';
$bot = null;

$summary = \Components\Data\DataRegistry::analytics()->getDashboardSummary(mh_get('dashboard_action', '') == 'refresh');
// Support JSON requests for dynamic updates
if (mh_get('format') === 'json') {
    header('Content-Type: application/json');
    // Ensure no incidental output (e.g. legacy comments) pollutes the JSON response
    if (ob_get_level() > 0) {
        ob_clean();
    }
    echo json_encode($summary);
    exit;
}

$emailsSent     = (int)($summary['emailsSent'] ?? 0);
$monthsAgo      = (int)($summary['monthsAgo'] ?? 0);
$beginningIso   = (string)($summary['beginningIso'] ?? '');
$bouncedPercent = (int)($summary['bouncedPercent'] ?? 0);
$bouncedCount   = (int)($summary['bouncedCount'] ?? 0);
$openedPercent  = (int)($summary['openedPercent'] ?? 0);
$openedCount    = (int)($summary['openedCount'] ?? 0);
$clickPercent   = (int)($summary['clickPercent'] ?? 0);
$clickCount     = (int)($summary['clickCount'] ?? 0);
$orderPercent   = (int)($summary['orderPercent'] ?? 0);
$orderCount     = (int)($summary['orderCount'] ?? 0);
$mobilePercent  = (int)($summary['mobilePercent'] ?? 0);
$mobileCount    = (int)($summary['mobileCount'] ?? 0);
$revenue        = (string)($summary['revenue'] ?? '0');
$voucherSum     = (string)($summary['voucherSum'] ?? '0');
$bot            = $summary['bot'] ?? null;
$cache_timestamp_out  = $summary['cache_timestamp_out'] ?? null;

$radialRadius = 44;
$radialSize = 60;
$radialStroke = 10;
$rowHeight = 'h-20';

$classesLabel = 'text-secondary text-xs';
$classesRadialValue = 'absolute text-zinc-600 font-medium text-sm';

// Self URL for HTMX refresh
$selfUrl = \Components\Router::url('dashboard_summary', ['partial' => 1, 'dashboard_action' => 'refresh']);
ob_start();
?>
<div class="relative rounded-xl -shadow-sm ring-1 ring-divider p-8 pb-10 bg-elevated" id="dashboard-summary"
     x-data="{ 
        summary: <?= htmlspecialchars(json_encode($summary)) ?>,
        lastRefresh: new Date('<?= $cache_timestamp_out ?>')
     }"
     hx-get="<?= $selfUrl ?>&format=json"
     hx-trigger="every 60s"
     hx-swap="none"
     @htmx:after-request="summary = JSON.parse($event.detail.xhr.response); lastRefresh = new Date();"
     data-no-global-loader="1"
     data-no-local-loader="1"
>
    <?php
    // Local loading overlay shown while the widget updates
    echo \Components\Base::loaderOverlay('loading-dashboard-summary', 'z-10');
    ?>
    <script>
        (function(){
            try {
                if(window.MBLoader){
                    MBLoader.bindHtmxOverlay('dashboard-summary','loading-dashboard-summary', 150);
                }
            } catch (e) { /* no-op */ }
        })();
    </script>
    <div class="absolute top-0 right-0 flex items-start justify-between mb-2">
        <div class="sr-only">Summary</div>
        <button type="button"
                class="ml-auto inline-flex items-center gap-1 rounded-bl-md  rounded-tr-xl px-2 py-1 text-xs font-normal text-secondary hover:text-primary hover:bg-muted"
                title="Refresh"
                hx-get="<?= $selfUrl ?>&format=json"
                hx-swap="none"
                @htmx:after-request="summary = JSON.parse($event.detail.xhr.response); lastRefresh = new Date();">
                <span x-timeago.seconds="lastRefresh"> ... </span>
            <span class="font-normal! ">

            <?= \Components\Base::SVG_REFRESH; ?>
            </span>
        </button>
    </div>

    <div class="flex justify-center-safe items-start gap-1 ">
        <!-- Mobile -->
        <div class="flex flex-col items-center">
            <div class="<?= $rowHeight; ?> flex items-center">
                <?php
                echo \Components\RadialProgress::render($mobilePercent, [
                    'radius' => $radialRadius,
                    'size' => $radialSize,
                    'strokeWidth' => $radialStroke,
                    'colorClass' => 'text-event-opened',
                    'trackColor' => 'text-event-opened/20',
                    'labelClass' => $classesRadialValue,
                    'alpineKey' => 'summary.mobilePercent',
                ]);
                ?>
            </div>
            <div class="<?= $classesLabel ?> flex items-center justify-center">
                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-1">
                    <rect width="14" height="20" x="5" y="2" rx="2" ry="2"/>
                    <path d="M12 18h.01"/>
                </svg>
                <span>mobile:</span>
            </div>
            <div class="<?= $classesLabel ?>" x-text="summary.mobileCount"><?= htmlspecialchars((string)$mobileCount) ?></div>
        </div>

        <div class="flex items-center <?= $rowHeight; ?> px-4">
            <div class="h-10 border-r border-divider"></div>
        </div>

        <!-- Emails sent summary -->
        <div class="min-w-36 flex flex-col text-center justify-center mr-4">
            <div class="text-3xl tracking-tight font-medium flex items-center justify-center text-primary leading-none <?= $rowHeight; ?> t-digit-group"
                 x-data="animatedNumber(summary.emailsSent)"
                 x-effect="update(summary.emailsSent)"
                 :class="isAnimating && 'is-animating'">
                <template x-for="(digit, index) in digits" :key="index">
                    <span class="t-digit"
                          :data-stagger="index"
                          x-text="digit"></span>
                </template>
            </div>
            <div class="<?= $classesLabel ?> ">Emails gesendet</div>
            <div class="<?= $classesLabel ?> ">
                <?= mh_lng('MAILBEEZ_STATSBAR_LABEL_BEGIN_OF_TIME', 'since'); ?>
                <span x-data="{ date: new Date('<?php echo date('Y-m-d\TH:i:s', strtotime($bot)); ?>')  }" x-timeago="date"> ... </span>
<!--
                seit <time datetime="<?= htmlspecialchars((string)$beginningIso) ?>" lang="de" class="underline">vor <?= htmlspecialchars((string)$monthsAgo) ?> Monaten</time>
-->

            </div>
        </div>

        <div class="text-2xl text-zinc-300 flex items-center <?= $rowHeight; ?>">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="m9 18 6-6-6-6"/>
            </svg>
        </div>

        <!-- Bounced -->
        <div class="flex flex-col items-center">
            <div class="<?= $rowHeight; ?> flex items-center">
                <?php
                echo \Components\RadialProgress::render($bouncedPercent, [
                    'radius' => $radialRadius,
                    'size' => $radialSize,
                    'strokeWidth' => $radialStroke,
                    'colorClass' => 'text-event-bounced',
                    'trackColor' => 'text-event-bounced/20',
                    'labelClass' => $classesRadialValue,
                    'alpineKey' => 'summary.bouncedPercent',
                ]);
                ?>
            </div>
            <div class="<?= $classesLabel ?>">bounced:</div>
            <div class="<?= $classesLabel ?>" x-text="summary.bouncedCount"><?= htmlspecialchars((string)$bouncedCount) ?></div>
        </div>

        <div class="text-2xl text-zinc-300 flex items-center <?= $rowHeight; ?>">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="m9 18 6-6-6-6"/>
            </svg>
        </div>

        <!-- Opened -->
        <div class="flex flex-col items-center">
            <div class="<?= $rowHeight; ?> flex items-center">
                <?php
                echo \Components\RadialProgress::render($openedPercent, [
                    'radius' => $radialRadius,
                    'size' => $radialSize,
                    'strokeWidth' => $radialStroke,
                    'colorClass' => 'text-event-opened',
                    'trackColor' => 'text-event-opened/20',
                    'labelClass' => $classesRadialValue,
                    'alpineKey' => 'summary.openedPercent',
                ]);
                ?>
            </div>
            <div class="<?= $classesLabel ?>">geöffnet:</div>
            <div class="<?= $classesLabel ?>" x-text="summary.openedCount"><?= htmlspecialchars((string)$openedCount) ?></div>
        </div>

        <div class="text-2xl text-zinc-300 flex items-center <?= $rowHeight; ?>">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="m9 18 6-6-6-6"/>
            </svg>
        </div>

        <!-- Clicked -->
        <div class="flex flex-col items-center">
            <div class="<?= $rowHeight; ?> flex items-center">
                <?php
                echo \Components\RadialProgress::render($clickPercent, [
                    'radius' => $radialRadius,
                    'size' => $radialSize,
                    'strokeWidth' => $radialStroke,
                    'colorClass' => 'text-event-clicked',
                    'trackColor' => 'text-event-clicked/20',
                    'labelClass' => $classesRadialValue,
                    'alpineKey' => 'summary.clickPercent',
                ]);
                ?>
            </div>
            <div class="<?= $classesLabel ?>">geklickt:</div>
            <div class="<?= $classesLabel ?>" x-text="summary.clickCount"><?= htmlspecialchars((string)$clickCount) ?></div>
        </div>

        <div class="text-2xl text-zinc-300 flex items-center <?= $rowHeight; ?>">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="m9 18 6-6-6-6"/>
            </svg>
        </div>

        <!-- Ordered -->
        <div class="flex flex-col items-center">
            <div class="<?= $rowHeight; ?> flex items-center">
                <?php
                echo \Components\RadialProgress::render($orderPercent, [
                    'radius' => $radialRadius,
                    'size' => $radialSize,
                    'strokeWidth' => $radialStroke,
                    'colorClass' => 'text-event-ordered',
                    'trackColor' => 'text-event-ordered/20',
                    'labelClass' => $classesRadialValue,
                    'alpineKey' => 'summary.orderPercent',
                ]);
                ?>
            </div>
            <div class="<?= $classesLabel ?>">bestellt:</div>
            <div class="<?= $classesLabel ?>" x-text="summary.orderCount"><?= htmlspecialchars((string)$orderCount) ?></div>
        </div>

        <div class="text-2xl text-zinc-300 flex items-center <?= $rowHeight; ?>">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="m9 18 6-6-6-6"/>
            </svg>
        </div>

        <!-- Revenue -->
        <div>
            <div class="ml-4 flex flex-col text-center justify-center">
                <div class="text-3xl tracking-tight font-medium flex items-center justify-center text-primary leading-none <?= $rowHeight; ?> t-digit-group"
                     x-data="animatedNumber(summary.revenue)"
                     x-effect="update(summary.revenue)"
                     :class="isAnimating && 'is-animating'">
                    <template x-for="(digit, index) in digits" :key="index">
                        <span class="t-digit"
                              :data-stagger="index"
                              x-text="digit"></span>
                    </template>
                </div>
                <div class="<?= $classesLabel ?>">Umsatz (subtotal)</div>
                <div class="<?= $classesLabel ?>">Summe Gutscheine: <span x-text="summary.voucherSum"><?= htmlspecialchars($voucherSum) ?></span></div>
            </div>
        </div>

    </div>
</div>
<?php
// Emit buffered HTML so this component can be loaded standalone
echo ob_get_clean();
