<?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]
            );
            $latest = Database::rows(
                "SELECT s.ref, s.submitter_email, s.read_at, s.created_at, f.title AS form_title
                   FROM forms_submissions s
                   LEFT JOIN forms_definitions f ON f.id = s.form_id AND f.tenant_id = s.tenant_id
                  WHERE s.tenant_id = ? ORDER BY s.id DESC LIMIT 5", [$tid]);
        } catch (\Throwable $e) {
            return $widgets;
        }
        $inboxUrl = $this->url('admin/submissions.php');

        ob_start(); ?>
        <div class="card">
            <div class="card-header">
                <h2><?= __('forms', 'Forms') ?></h2>
                <a href="<?= e($inboxUrl) ?>" class="dwidget-all"><?= __('view_all', 'View all') ?> →</a>
            </div>
            <div class="dwidget-kpis">
                <div class="dwidget-kpi">
                    <div class="dwidget-kpi-k"><?= __('forms_subs_7d', 'Submissions · 7d') ?></div>
                    <div class="dwidget-kpi-v"><?= (int)$recent ?></div>
                </div>
                <div class="dwidget-kpi">
                    <div class="dwidget-kpi-k"><?= __('forms_unread', 'Unread') ?></div>
                    <div class="dwidget-kpi-v"><?= (int)$unread ?></div>
                </div>
            </div>
            <?php if ($latest): ?>
                <div class="dlist">
                    <?php foreach ($latest as $s):
                        $who = trim((string)($s['submitter_email'] ?? '')) ?: __('forms_anon', 'Anonymous');
                        $isUnread = empty($s['read_at']);
                        slate_dlist_row([
                            'avatar'       => $who,
                            'avatar_color' => $isUnread ? 'info' : 'muted',
                            'title'        => $who,
                            'sub'          => trim((string)($s['form_title'] ?? __('forms_form', 'Form'))) . ' · ' . (string)$s['ref'],
                            'amount'       => $isUnread ? __('forms_new', 'New') : '',
                            'time'         => $s['created_at'] ? date('M j', strtotime($s['created_at'])) : '',
                            'href'         => $inboxUrl,
                        ]);
                    endforeach; ?>
                </div>
            <?php else: ?>
                <div class="dlist-empty"><?= __('forms_no_subs', 'No submissions yet') ?></div>
            <?php endif; ?>
        </div>
        <?php
        $widgets[] = ob_get_clean();
        return $widgets;
    }
}
