<?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();
?>

<style>
/* ── Dashboard — tech-flavoured shell. Scoped to .dash ───────────────── */
.dash-hero {
    position: relative; overflow: hidden;
    border: 1px solid var(--border); border-radius: var(--radius-lg);
    background:
        radial-gradient(130% 180% at 100% 0%, rgba(37,99,235,0.08), transparent 55%),
        var(--surface);
    padding: 22px 24px; margin-bottom: var(--space-5);
    display: flex; align-items: center; gap: 20px; flex-wrap: wrap;
}
.dash-hero::before {
    content: ""; position: absolute; inset: 0; pointer-events: none; opacity: .6;
    background-image: radial-gradient(var(--border-strong) 1px, transparent 1.4px);
    background-size: 18px 18px;
    -webkit-mask-image: linear-gradient(115deg, #000, transparent 55%);
            mask-image: linear-gradient(115deg, #000, transparent 55%);
}
.dash-hero-main { position: relative; flex: 1 1 320px; min-width: 0; }
.dash-eyebrow {
    font-family: var(--font-mono); font-size: 10.5px; letter-spacing: 0.18em;
    text-transform: uppercase; color: var(--subtle); margin-bottom: 8px;
}
.dash-title {
    margin: 0; font-family: var(--font-display);
    font-size: 26px; font-weight: 700; letter-spacing: -0.025em; line-height: 1.1;
}
.dash-sub { margin: 6px 0 0; color: var(--muted); font-size: 13.5px; }
.dash-hero-side {
    position: relative; display: flex; flex-direction: column; align-items: flex-end; gap: 8px;
}
.dash-status {
    display: inline-flex; align-items: center; gap: 7px;
    font-size: 12px; font-weight: 600; color: var(--success);
    background: var(--success-soft); border: 1px solid transparent;
    padding: 5px 11px; border-radius: 999px;
}
.dash-status .dot {
    width: 7px; height: 7px; border-radius: 999px; background: var(--success);
    box-shadow: 0 0 0 3px var(--success-soft);
}
.dash-clock {
    font-family: var(--font-mono); font-size: 11.5px; color: var(--muted);
    letter-spacing: 0.02em;
}

.dash-stats {
    display: grid; grid-template-columns: repeat(3, 1fr);
    gap: var(--space-4); margin-bottom: var(--space-5);
}
.dash-stat {
    position: relative; overflow: hidden;
    display: flex; align-items: center; gap: 14px;
    border: 1px solid var(--border); border-radius: var(--radius-lg);
    background: var(--surface);
    box-shadow: 0 1px 2px rgba(15,17,23,.04);
    padding: 16px 18px;
    transition: border-color .15s ease, box-shadow .15s ease, transform .15s ease;
}
.dash-stat:hover {
    border-color: var(--border-strong);
    box-shadow: 0 6px 20px rgba(15,17,23,.07);
    transform: translateY(-2px);
}
/* Soft tinted icon chip — light wash background, accent-coloured glyph. */
.dash-stat-ico {
    flex: none; width: 44px; height: 44px; border-radius: 12px;
    display: grid; place-items: center;
    background: var(--accent-soft); color: var(--accent);
}
/* override the global .nav-icon color (it hardcodes a sidebar grey on the svg) */
.dash-stat-ico svg { width: 21px; height: 21px; color: var(--accent); }
.dash-stat-body { flex: 1 1 auto; min-width: 0; }
.dash-stat-k {
    font-family: var(--font-mono); font-size: 10px; letter-spacing: 0.1em;
    text-transform: uppercase; color: var(--subtle);
}
.dash-stat-s { font-size: 11.5px; color: var(--muted); margin-top: 4px; }
/* Value pushed to the right edge so the tile reads end-to-end (no dead gap). */
.dash-stat-v {
    flex: none; margin-left: 10px;
    font-size: 30px; font-weight: 700; letter-spacing: -0.03em; line-height: 1;
    font-variant-numeric: tabular-nums;
}

/* Masonry card layout — every dashboard card (plugin data + utilities) flows
   into balanced columns, so there's never a tall single column with empty
   space beside it. The browser fits as many ~340px columns as the width
   allows (≈3 on wide desktops, 2 on tablets, 1 on mobile). */
.dash-grid {
    column-width: 340px;
    column-gap: var(--space-4);
}
.dash-grid > .card {
    break-inside: avoid;
    -webkit-column-break-inside: avoid;
    margin: 0 0 var(--space-4);
}

/* Quick actions — every row identical: soft accent chip, same muted arrow,
   same font/size. Hover is only a subtle row highlight (no aggressive fills). */
.dash-qa { display: flex; flex-direction: column; gap: 8px; }
.dash-qa a {
    display: flex; align-items: center; gap: 12px;
    padding: 11px 12px; border-radius: 12px;
    color: var(--text); font-size: 13.5px; font-weight: 600;
    background: var(--surface-2);
    transition: background .14s ease;
}
.dash-qa a:hover { background: var(--surface-sunken); text-decoration: none; }
.dash-qa-ico {
    flex: none; width: 38px; height: 38px; border-radius: 11px;
    display: grid; place-items: center;
    background: var(--accent-soft);
}
.dash-qa-ico svg { width: 18px; height: 18px; color: var(--accent); }
.dash-qa-arr { margin-left: auto; color: var(--subtle); transition: transform .14s ease; }
.dash-qa a:hover .dash-qa-arr { transform: translateX(3px); }

/* Compact activity feed */
.dash-feed { list-style: none; margin: 0; padding: 0; }
.dash-feed-item { display: flex; gap: 11px; padding: 9px 0; border-bottom: 1px dashed var(--border); }
.dash-feed-item:first-child { padding-top: 0; }
.dash-feed-item:last-child { border-bottom: 0; padding-bottom: 0; }
.dash-feed-dot { width: 8px; height: 8px; margin-top: 4px; border-radius: 999px; flex: none; background: var(--subtle); }
.dash-feed-dot.is-success { background: var(--success); }
.dash-feed-dot.is-danger  { background: var(--danger); }
.dash-feed-dot.is-info    { background: var(--info); }
.dash-feed-dot.is-warning { background: var(--warning); }
.dash-feed-body { min-width: 0; }
.dash-feed-title {
    font-family: var(--font-mono); font-size: 12px; font-weight: 600; color: var(--text);
    overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.dash-feed-meta { font-size: 11px; color: var(--muted); margin-top: 2px; }

@media (max-width: 700px) {
    .dash-grid { column-width: auto; column-count: 1; }
}
@media (max-width: 720px) {
    .dash-stats { grid-template-columns: 1fr; }
    .dash-hero-side { align-items: flex-start; width: 100%; }
    .dash-title { font-size: 22px; }
}
</style>

<div class="dash-hero">
    <div class="dash-hero-main">
        <div class="dash-eyebrow"><?= __('dashboard', 'Dashboard') ?></div>
        <h1 class="dash-title"><?= __('good_to_see_you', 'Good to see you') ?>, <?= e(explode(' ', $user['name'])[0]) ?>.</h1>
        <p class="dash-sub"><?= __('dashboard_subtitle', 'Here\'s what\'s happening in your Slate install today.') ?></p>
    </div>
    <div class="dash-hero-side">
        <span class="dash-status"><span class="dot"></span> <?= __('all_systems_operational', 'All systems operational') ?></span>
        <span class="dash-clock"><?= e(date('D · j M Y')) ?></span>
    </div>
</div>

<!-- Stats -->
<div class="dash-stats">
    <div class="dash-stat">
        <span class="dash-stat-ico"><?= slate_admin_nav_icon('box') ?></span>
        <div class="dash-stat-body">
            <div class="dash-stat-k"><?= __('active_plugins', 'Active plugins') ?></div>
            <div class="dash-stat-s">
                <?= (int)$pluginCounts['installed'] ?> <?= __('installed', 'installed') ?>
                · <?= (int)$pluginCounts['inactive'] ?> <?= __('inactive', 'inactive') ?>
            </div>
        </div>
        <div class="dash-stat-v"><?= (int)$pluginCounts['active'] ?></div>
    </div>
    <div class="dash-stat">
        <span class="dash-stat-ico"><?= slate_admin_nav_icon('shield') ?></span>
        <div class="dash-stat-body">
            <div class="dash-stat-k"><?= __('admin_users', 'Admin users') ?></div>
            <div class="dash-stat-s"><?= __('with_dashboard_access', 'With dashboard access') ?></div>
        </div>
        <div class="dash-stat-v"><?= $userCount ?></div>
    </div>
    <div class="dash-stat">
        <span class="dash-stat-ico"><?= slate_admin_nav_icon('users') ?></span>
        <div class="dash-stat-body">
            <div class="dash-stat-k"><?= __('customers', 'Customers') ?></div>
            <div class="dash-stat-s"><?= __('registered_accounts', 'Registered accounts') ?></div>
        </div>
        <div class="dash-stat-v"><?= $customerCount ?></div>
    </div>
</div>

<div class="dash-grid">
    <?php if ($pluginWidgets): ?>
        <?php foreach ($pluginWidgets as $widget): ?>
            <?php if (is_string($widget)) echo $widget; ?>
        <?php endforeach; ?>
    <?php else: ?>
        <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">
                <a href="<?= e(SLATE_URL) ?>/admin/plugins.php" class="btn btn-primary"><?= __('manage_plugins', 'Manage plugins') ?></a>
            </div>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-header"><h2><?= __('quick_actions', 'Quick actions') ?></h2></div>
        <nav class="dash-qa">
                <a href="<?= e(SLATE_URL) ?>/admin/plugins.php">
                    <span class="dash-qa-ico"><?= slate_admin_nav_icon('box') ?></span>
                    <?= __('manage_plugins', 'Manage plugins') ?>
                    <span class="dash-qa-arr">→</span>
                </a>
                <a href="<?= e(SLATE_URL) ?>/admin/users.php">
                    <span class="dash-qa-ico"><?= slate_admin_nav_icon('users') ?></span>
                    <?= __('team_and_roles', 'Team &amp; roles') ?>
                    <span class="dash-qa-arr">→</span>
                </a>
                <a href="<?= e(SLATE_URL) ?>/admin/settings.php">
                    <span class="dash-qa-ico"><?= slate_admin_nav_icon('settings') ?></span>
                    <?= __('settings', 'Settings') ?>
                    <span class="dash-qa-arr">→</span>
                </a>
            </nav>
        </div>

        <?php if ($recent): ?>
        <div class="card">
            <div class="card-header"><h2><?= __('recent_activity', 'Recent activity') ?></h2></div>
            <ul class="dash-feed">
                <?php foreach ($recent as $row):
                    $action     = (string)($row['action'] ?? '');
                    $actionType = explode('.', $action)[0] ?? 'log';
                    $dot        = match($actionType) {
                        'login'                   => 'is-info',
                        'settings'                => 'is-warning',
                        'install', 'activate'     => 'is-success',
                        'deactivate', 'uninstall' => 'is-danger',
                        default                   => '',
                    };
                    $when      = $row['created_at'] ?? '';
                    $whenShort = $when ? date('M j, g:ia', strtotime($when)) : '—';
                ?>
                    <li class="dash-feed-item">
                        <span class="dash-feed-dot <?= $dot ?>"></span>
                        <div class="dash-feed-body">
                            <div class="dash-feed-title"><?= e($action) ?></div>
                            <div class="dash-feed-meta"><?= e($row['user_name'] ?? 'System') ?> · <?= e($whenShort) ?></div>
                        </div>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>
</div>

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