<?php
/**
 * Forms — admin list page.
 * Cards-row list of all forms in the tenant, plus a "New form" CTA.
 */
require_once dirname(__DIR__, 3) . '/config.php';
require_once dirname(__DIR__) . '/FormsAPI.php';

Auth::require();
Auth::requirePerm('forms.view');
FormsAPI::ensureSchema();

$pageTitle  = __('forms', 'Forms');
$currentNav = 'forms';

$tid = current_tenant_id();

// ── POST handlers (delete + status toggle) ──────────────────
$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $flash = ['type' => 'error', 'msg' => 'Security check failed.'];
    } else {
        $action = $_POST['_action'] ?? '';
        $id     = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            if ($action === 'delete' && Auth::can('forms.manage')) {
                Database::delete('forms_submissions', 'form_id = ? AND tenant_id = ?', [$id, $tid]);
                Database::delete('forms_webhooks',    'form_id = ? AND tenant_id = ?', [$id, $tid]);
                Database::delete('forms_definitions', 'id = ? AND tenant_id = ?',     [$id, $tid]);
                AuditLog::record('forms.deleted', (string)$id);
                $flash = ['type' => 'success', 'msg' => 'Form deleted.'];
            } elseif ($action === 'publish' && Auth::can('forms.manage')) {
                Database::update('forms_definitions', ['status' => 'published'],
                    'id = ? AND tenant_id = ?', [$id, $tid]);
                AuditLog::record('forms.published', (string)$id);
                $flash = ['type' => 'success', 'msg' => 'Form published.'];
            } elseif ($action === 'unpublish' && Auth::can('forms.manage')) {
                Database::update('forms_definitions', ['status' => 'draft'],
                    'id = ? AND tenant_id = ?', [$id, $tid]);
                AuditLog::record('forms.unpublished', (string)$id);
                $flash = ['type' => 'success', 'msg' => 'Form moved to draft.'];
            } elseif ($action === 'archive' && Auth::can('forms.manage')) {
                Database::update('forms_definitions', ['status' => 'archived'],
                    'id = ? AND tenant_id = ?', [$id, $tid]);
                AuditLog::record('forms.archived', (string)$id);
                $flash = ['type' => 'success', 'msg' => 'Form archived.'];
            }
        }
    }
}

$forms = Database::rows(
    "SELECT d.*,
            (SELECT COUNT(*) FROM forms_submissions s
              WHERE s.form_id = d.id AND s.tenant_id = d.tenant_id) AS submission_count,
            (SELECT COUNT(*) FROM forms_submissions s
              WHERE s.form_id = d.id AND s.tenant_id = d.tenant_id AND s.read_at IS NULL) AS unread_count
       FROM forms_definitions d
      WHERE d.tenant_id = ?
   ORDER BY d.updated_at DESC, d.id DESC",
    [$tid]
);

require SLATE_ROOT . '/admin/partials/header.php';
?>

<?php slate_breadcrumbs([
    ['label' => __('dashboard', 'Dashboard'), 'href' => SLATE_URL . '/admin/'],
    ['label' => __('forms', 'Forms')],
]); ?>

<div class="page-header">
    <div>
        <h1><?= __('forms', 'Forms') ?></h1>
        <p class="page-header-sub">Public forms you can embed or link to.</p>
    </div>
    <?php if (Auth::can('forms.manage')): ?>
        <a href="<?= e(plugin_url('forms', 'admin/edit.php')) ?>" class="btn btn-primary">
            New form
        </a>
    <?php endif; ?>
</div>

<?php if ($flash): ?>
    <div class="alert alert-<?= e($flash['type']) ?>" role="status"><?= e($flash['msg']) ?></div>
<?php endif; ?>

<?php if (empty($forms)): ?>
    <div class="card">
        <div class="empty">
            <div class="empty-icon">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                    <rect x="8" y="2" width="8" height="4" rx="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="M9 12h6M9 16h6"/>
                </svg>
            </div>
            <div class="empty-title">No forms yet</div>
            <p class="text-sm">Create your first form and we'll give you a public URL + an embed snippet.</p>
            <?php if (Auth::can('forms.manage')): ?>
                <a href="<?= e(plugin_url('forms', 'admin/edit.php')) ?>" class="btn btn-primary mt-3">Create a form</a>
            <?php endif; ?>
        </div>
    </div>
<?php else: ?>

    <div class="data-list" data-single-open>
        <?php foreach ($forms as $f):
            $publicUrl = SLATE_URL . '/forms/' . $f['slug'];
            $editUrl   = plugin_url('forms', 'admin/edit.php') . '?id=' . (int)$f['id'];
            $inboxUrl  = plugin_url('forms', 'admin/submissions.php') . '?form_id=' . (int)$f['id'];
            $isPub     = $f['status'] === 'published';

            $badgeMap = [
                'published' => ['Published', 'active'],
                'draft'     => ['Draft',     'warning'],
                'archived'  => ['Archived',  'inactive'],
            ];
            $badge = $badgeMap[$f['status']] ?? ['Draft', 'warning'];

            $detail = [
                'Public URL' => ['label' => 'Public URL',
                    'html' => $isPub
                        ? '<a href="' . e($publicUrl) . '" target="_blank">' . e($publicUrl) . '</a>'
                        : '<span class="text-muted">— published forms only —</span>',
                ],
                'Embed snippet' => ['label' => 'Embed snippet',
                    'html' => $isPub
                        ? '<code style="word-break:break-all;">&lt;iframe src=&quot;' . e($publicUrl) . '?embed=1&quot; style=&quot;width:100%;border:0;min-height:520px&quot;&gt;&lt;/iframe&gt;</code>'
                        : '<span class="text-muted">— published forms only —</span>',
                ],
                'Fields'    => count($f['unread_count'] !== null ? (json_decode($f['fields_json'] ?? '[]', true) ?: []) : []) . ' configured',
                'Updated'   => date('j M Y, H:i', strtotime($f['updated_at'])),
                'Notify'    => $f['notify_email'] ?: '— none —',
            ];

            $actions = '<a href="' . e($editUrl)  . '" class="btn btn-sm">Edit</a> '
                     . '<a href="' . e($inboxUrl) . '" class="btn btn-sm btn-ghost">View submissions</a>';

            if (Auth::can('forms.manage')) {
                $actions .= ' <form method="post" style="display:inline; margin:0;">' . csrf_field()
                          . '<input type="hidden" name="id" value="' . (int)$f['id'] . '">';
                if ($isPub) {
                    $actions .= '<button name="_action" value="unpublish" class="btn btn-sm btn-ghost">Unpublish</button>';
                } elseif ($f['status'] === 'draft') {
                    $actions .= '<button name="_action" value="publish" class="btn btn-sm btn-primary">Publish</button>';
                }
                $actions .= '</form>';

                $actions .= ' <form method="post" style="display:inline; margin:0;" onsubmit="return confirm(\'Delete this form and all its submissions?\')">' . csrf_field()
                          . '<input type="hidden" name="id" value="' . (int)$f['id'] . '">'
                          . '<button name="_action" value="delete" class="btn btn-sm btn-danger">Delete</button>'
                          . '</form>';
            }

            $titleHtml = e($f['title']);
            if ($f['unread_count'] > 0) {
                $titleHtml .= ' <span class="badge badge-accent">' . (int)$f['unread_count'] . ' unread</span>';
            }

            slate_data_row([
                'avatar'       => mb_substr($f['title'], 0, 1),
                'avatar_color' => 'info',
                'title_html'   => $titleHtml,
                'meta'         => '/forms/' . $f['slug'] . ' · ' . (int)$f['submission_count'] . ' submissions',
                'badge'        => $badge,
                'detail'       => $detail,
                'actions'      => $actions,
            ]);
        endforeach; ?>
    </div>

    <?php slate_data_list_script(); ?>
<?php endif; ?>

<?php require SLATE_ROOT . '/admin/partials/footer.php'; ?>
