<?php
/**
 * Forms plugin — bootstrap.
 *
 * Registers:
 *   - Admin nav items (forms list + submissions inbox)
 *   - Dashboard widget (submissions in last 7 days)
 *   - Public route prefix `/forms` → public/router.php
 *
 * Heavy lifting (validation, field rendering, webhook dispatch, etc.)
 * lives in FormsAPI.
 */

require_once __DIR__ . '/FormsAPI.php';

class Forms extends Plugin {

    public function boot(): void {
        Hook::addFilter('admin_nav_items',          [$this, 'addAdminNav']);
        Hook::addFilter('admin_dashboard_widgets',  [$this, 'addDashboardWidget']);
        Hook::addFilter('public_routes',            [$this, 'addPublicRoutes']);
    }

    public function addAdminNav(array $items): array {
        if (!Auth::can('forms.view') && !Auth::isSuperAdmin()) return $items;

        $items[] = [
            'slug'  => 'forms',
            'label' => __('forms', 'Forms'),
            'href'  => $this->url('admin/index.php'),
            'icon'  => 'clipboard-list',
            'perm'  => 'forms.view',
            'order' => 230,
            'group' => 'content',
        ];
        $items[] = [
            'slug'  => 'forms-submissions',
            'label' => __('forms_submissions', 'Submissions'),
            'href'  => $this->url('admin/submissions.php'),
            'icon'  => 'mail',
            'perm'  => 'forms.view',
            'order' => 231,
            'group' => 'content',
        ];
        return $items;
    }

    public function addPublicRoutes(array $routes): array {
        $routes['forms'] = [
            'handler' => $this->dir('public/router.php'),
            'methods' => ['GET', 'POST'],
        ];
        return $routes;
    }

    public function addDashboardWidget(array $widgets): array {
        if (!Auth::can('forms.view')) return $widgets;

        FormsAPI::ensureSchema();
        $tid = current_tenant_id();
        try {
            $recent = (int) Database::value(
                "SELECT COUNT(*) FROM forms_submissions
                  WHERE tenant_id = ? AND created_at >= (NOW() - INTERVAL 7 DAY)",
                [$tid]
            );
            $unread = (int) Database::value(
                "SELECT COUNT(*) FROM forms_submissions
                  WHERE tenant_id = ? AND read_at IS NULL",
                [$tid]
            );
            $formCount = (int) Database::value(
                "SELECT COUNT(*) FROM forms_definitions
                  WHERE tenant_id = ? AND status = 'published'",
                [$tid]
            );
        } catch (\Throwable $e) {
            return $widgets;
        }

        ob_start(); ?>
        <div class="card">
            <div class="card-header">
                <h2><?= __('forms', 'Forms') ?></h2>
                <?php if ($unread > 0): ?>
                    <span class="badge badge-warning"><?= (int)$unread ?> unread</span>
                <?php endif; ?>
            </div>
            <div class="stat-grid">
                <div class="stat">
                    <div class="stat-label">Live forms</div>
                    <div class="stat-value"><?= (int)$formCount ?></div>
                </div>
                <div class="stat">
                    <div class="stat-label">Submissions, 7d</div>
                    <div class="stat-value"><?= (int)$recent ?></div>
                </div>
            </div>
            <div class="mt-2">
                <a href="<?= e($this->url('admin/submissions.php')) ?>" class="btn btn-sm">View inbox →</a>
                <a href="<?= e($this->url('admin/index.php')) ?>" class="btn btn-sm btn-ghost">Manage forms</a>
            </div>
        </div>
        <?php
        $widgets[] = ob_get_clean();
        return $widgets;
    }
}
