<?php
/**
 * Slate — admin dashboard.
 *
 * Minimal landing page after login. Plugins extend this via the
 * `admin_dashboard_widgets` filter.
 */
require_once dirname(__DIR__) . '/config.php';
Auth::require();

$pageTitle = __('dashboard', 'Dashboard');
require __DIR__ . '/partials/header.php';

// ── Stats ────────────────────────────────────────────────────
$pluginCounts = Database::row(
    "SELECT
        SUM(CASE WHEN status='active'    THEN 1 ELSE 0 END) AS active,
        SUM(CASE WHEN status='installed' THEN 1 ELSE 0 END) AS installed,
        SUM(CASE WHEN status='inactive'  THEN 1 ELSE 0 END) AS inactive
     FROM plugins"
) ?: ['active' => 0, 'installed' => 0, 'inactive' => 0];

$userCount     = (int)Database::value("SELECT COUNT(*) FROM users WHERE tenant_id = ?", [current_tenant_id()]);
$customerCount = (int)Database::value("SELECT COUNT(*) FROM customers WHERE tenant_id = ?", [current_tenant_id()]);

$recent = (Auth::can('audit.view') || Auth::isSuperAdmin())
        ? AuditLog::recent(8)
        : [];

$pluginWidgets = Hook::applyFilters('admin_dashboard_widgets', []);
$user = Auth::user();
?>

<div class="page-header">
    <div>
        <h1><?= __('good_to_see_you', 'Good to see you') ?>, <?= e(explode(' ', $user['name'])[0]) ?>.</h1>
        <p class="page-header-sub"><?= __('dashboard_subtitle', 'Here\'s what\'s happening in your Slate install today.') ?></p>
    </div>
</div>

<!-- Stats grid -->
<div class="stat-grid">
    <div class="stat">
        <div class="stat-label"><?= __('active_plugins', 'Active plugins') ?></div>
        <div class="stat-value"><?= (int)$pluginCounts['active'] ?></div>
        <div class="stat-sub">
            <?= (int)$pluginCounts['installed'] ?> <?= __('installed', 'installed') ?>
            · <?= (int)$pluginCounts['inactive'] ?> <?= __('inactive', 'inactive') ?>
        </div>
    </div>
    <div class="stat">
        <div class="stat-label"><?= __('admin_users', 'Admin users') ?></div>
        <div class="stat-value"><?= $userCount ?></div>
    </div>
    <div class="stat">
        <div class="stat-label"><?= __('customers', 'Customers') ?></div>
        <div class="stat-value"><?= $customerCount ?></div>
    </div>
</div>

<?php foreach ($pluginWidgets as $widget): ?>
    <?php if (is_string($widget)) echo $widget; ?>
<?php endforeach; ?>

<div class="card">
    <div class="card-header">
        <h2><?= __('welcome', 'Welcome to Slate') ?></h2>
    </div>
    <p class="text-muted">
        <?= __('dashboard_intro',
            'Slate is a lean shell. Install plugins to add functionality — booking, products, passes, and more. Each plugin owns its own data and can be deactivated or uninstalled without affecting the others.') ?>
    </p>
    <div class="mt-4 flex gap-2" style="flex-wrap:wrap">
        <a href="<?= e(SLATE_URL) ?>/admin/plugins.php" class="btn btn-primary">
            <?= __('manage_plugins', 'Manage plugins') ?>
        </a>
        <a href="<?= e(SLATE_URL) ?>/admin/settings.php" class="btn">
            <?= __('settings', 'Settings') ?>
        </a>
    </div>
</div>

<?php if ($recent): ?>
<div class="card">
    <div class="card-header">
        <h2><?= __('recent_activity', 'Recent activity') ?></h2>
    </div>
    <div class="data-list" data-single-open>
        <?php foreach ($recent as $row):
            $action     = (string)($row['action'] ?? '');
            $actionType = explode('.', $action)[0] ?? 'log';
            $color      = match($actionType) {
                'login'    => 'info',
                'settings' => 'warning',
                'install', 'activate' => 'success',
                'deactivate', 'uninstall' => 'danger',
                default    => 'muted',
            };
            $initials = mb_strtoupper(mb_substr($row['user_name'] ?? 'S', 0, 2));

            // Time-ago helper
            $when = $row['created_at'] ?? '';
            $whenShort = $when ? date('M j, g:ia', strtotime($when)) : '—';

            slate_data_row([
                'avatar'       => $initials,
                'avatar_color' => $color,
                'title'        => $action,
                'meta'         => ($row['user_name'] ?? 'System') . ' · ' . $whenShort,
                'badge'        => [$actionType, $color === 'muted' ? '' : $color],
                'detail'       => [
                    'Action'    => $action,
                    'When'      => $when,
                    'Who'       => $row['user_name'] ?? '—',
                    'Target'    => $row['target'] ?? '—',
                ],
            ]);
        endforeach; ?>
    </div>
    <?php slate_data_list_script(); ?>
</div>
<?php endif; ?>

<?php require __DIR__ . '/partials/footer.php'; ?>
