<?php
/**
 * Forms — single submission detail.
 *
 * Right-rail layout: main column shows each field's submitted
 * value; aside has submission metadata + audit trail (received,
 * email, read, webhook dispatch).
 */
require_once dirname(__DIR__, 3) . '/config.php';
require_once dirname(__DIR__) . '/FormsAPI.php';

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

$tid = current_tenant_id();
$id  = (int)($_GET['id'] ?? 0);

$row = Database::row(
    "SELECT s.*, f.title AS form_title, f.slug AS form_slug, f.fields_json AS form_fields_json
       FROM forms_submissions s
       JOIN forms_definitions f ON f.id = s.form_id AND f.tenant_id = s.tenant_id
      WHERE s.id = ? AND s.tenant_id = ?",
    [$id, $tid]
);

if (!$row) {
    http_response_code(404);
    $pageTitle = 'Submission not found';
    require SLATE_ROOT . '/admin/partials/header.php';
    echo '<div class="card"><h1>Submission not found</h1></div>';
    require SLATE_ROOT . '/admin/partials/footer.php';
    exit;
}

// First view marks it read
if (empty($row['read_at'])) {
    Database::update('forms_submissions',
        ['read_at' => date('Y-m-d H:i:s')],
        'id = ? AND tenant_id = ?',
        [$id, $tid]
    );
    $row['read_at'] = date('Y-m-d H:i:s');
}

$data   = json_decode($row['data_json']        ?? '{}', true) ?: [];
$fields = json_decode($row['form_fields_json'] ?? '[]', true) ?: [];

// POST handlers
$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $flash = ['type' => 'error', 'msg' => 'Security check failed.'];
    } else {
        $action = $_POST['_action'] ?? '';
        if ($action === 'delete' && Auth::can('forms.manage')) {
            Database::delete('forms_submissions', 'id = ? AND tenant_id = ?', [$id, $tid]);
            AuditLog::record('forms.submission_deleted', (string)$id);
            header('Location: ' . plugin_url('forms', 'admin/submissions.php')
                . '?form_id=' . (int)$row['form_id']);
            exit;
        }
        if ($action === 'mark_unread') {
            Database::update('forms_submissions', ['read_at' => null],
                'id = ? AND tenant_id = ?', [$id, $tid]);
            header('Location: ' . plugin_url('forms', 'admin/submissions.php') . '?form_id=' . (int)$row['form_id']);
            exit;
        }
    }
}

// Build audit trail from what we know
$audit = [];
$audit[] = ['action' => 'Submission received', 'when' => $row['created_at'], 'muted' => false,
            'detail' => $row['ip'] ? 'from ' . $row['ip'] : ''];
if ((int)$row['email_sent'] === 1) {
    $audit[] = ['action' => 'Admin notification sent', 'when' => $row['created_at'], 'muted' => true];
} elseif (!empty($row['email_error'])) {
    $audit[] = ['action' => 'Admin notification failed', 'when' => $row['created_at'], 'muted' => false,
                'detail' => $row['email_error']];
}
$audit[] = ['action' => 'Read in admin', 'when' => $row['read_at'], 'muted' => true];

// Recent webhook dispatch logs for this submission
$hookLogs = Database::rows(
    "SELECT l.*, w.url AS hook_url
       FROM forms_webhook_log l
       JOIN forms_webhooks w ON w.id = l.webhook_id
      WHERE l.tenant_id = ? AND l.submission_id = ?
   ORDER BY l.created_at",
    [$tid, $id]
);
foreach ($hookLogs as $l) {
    $ok = ($l['status_code'] !== null && (int)$l['status_code'] >= 200 && (int)$l['status_code'] < 300);
    $audit[] = [
        'action' => ($ok ? 'Webhook delivered' : 'Webhook failed') . ' · ' . parse_url($l['hook_url'], PHP_URL_HOST),
        'when'   => $l['created_at'],
        'muted'  => $ok,
        'detail' => $l['status_code'] !== null
                    ? 'HTTP ' . (int)$l['status_code']
                    : ($l['error'] ?: 'no response'),
    ];
}

$pageTitle  = 'Submission ' . $row['ref'];
$currentNav = 'forms-submissions';

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

<?php slate_breadcrumbs([
    ['label' => __('dashboard', 'Dashboard'), 'href' => SLATE_URL . '/admin/'],
    ['label' => __('forms', 'Forms'), 'href' => plugin_url('forms', 'admin/index.php')],
    ['label' => __('forms_submissions', 'Submissions'), 'href' => plugin_url('forms', 'admin/submissions.php') . '?form_id=' . (int)$row['form_id']],
    ['label' => $row['ref']],
]); ?>

<div class="page-header">
    <div>
        <h1>Submission <code style="font-family:var(--font-mono);font-size:16px;"><?= e($row['ref']) ?></code></h1>
        <p class="page-header-sub">
            <a href="<?= e(plugin_url('forms', 'admin/edit.php')) ?>?id=<?= (int)$row['form_id'] ?>"><?= e($row['form_title']) ?></a>
            · <?= e(date('j M Y, H:i', strtotime($row['created_at']))) ?>
        </p>
    </div>
    <div class="toolbar">
        <form method="post" style="display:inline;margin:0;">
            <?= csrf_field() ?>
            <button name="_action" value="mark_unread" class="btn">Mark unread</button>
        </form>
        <?php if (Auth::can('forms.manage')): ?>
            <form method="post" style="display:inline;margin:0;" onsubmit="return confirm('Delete this submission?')">
                <?= csrf_field() ?>
                <button name="_action" value="delete" class="btn btn-danger">Delete</button>
            </form>
        <?php endif; ?>
    </div>
</div>

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

<?php slate_page_layout('with-aside'); ?>

    <div class="page-main">
        <div class="card">
            <div class="card-header"><h2>Form fields</h2></div>
            <ul class="kv-list">
                <?php foreach ($fields as $f):
                    $name  = $f['name']  ?? '';
                    $label = $f['label'] ?? $name;
                    if ($name === '') continue;
                    $value = $data[$name] ?? null;

                    if (is_bool($value)) {
                        $display = $value ? 'Yes' : 'No';
                    } elseif (is_array($value)) {
                        // File field has {path, original, size, mime}
                        if (isset($value['path'])) {
                            $display = ['file' => $value];
                        } else {
                            $display = implode(', ', array_map('strval', $value));
                        }
                    } else {
                        $display = (string)$value;
                    }
                ?>
                    <li class="kv-row">
                        <span class="kv-label"><?= e($label) ?></span>
                        <span class="kv-value"><?php
                            if (is_array($display) && isset($display['file'])) {
                                $file = $display['file'];
                                $href = SLATE_URL . e($file['path']);
                                echo '<a href="' . $href . '" target="_blank">'
                                   . e($file['original'] ?: basename($file['path']))
                                   . '</a> <span class="text-xs text-muted">('
                                   . e(number_format((float)$file['size'] / 1024, 1)) . ' KB)</span>';
                            } elseif ($display === '') {
                                echo '<span class="text-muted">— empty —</span>';
                            } elseif (($f['type'] ?? '') === 'textarea') {
                                echo nl2br(e((string)$display));
                            } else {
                                echo e((string)$display);
                            }
                        ?></span>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>

    <aside class="page-aside">
        <div class="aside-card">
            <div class="aside-card-title">Submission Info</div>
            <ul class="kv-list">
                <li class="kv-row">
                    <span class="kv-label">Reference</span>
                    <span class="kv-value kv-mono"><?= e($row['ref']) ?></span>
                </li>
                <li class="kv-row">
                    <span class="kv-label">Form</span>
                    <span class="kv-value"><?= e($row['form_title']) ?></span>
                </li>
                <li class="kv-row">
                    <span class="kv-label">Status</span>
                    <span class="kv-value">
                        <?php if ($row['read_at']): ?>
                            <span class="badge badge-inactive">Read</span>
                        <?php else: ?>
                            <span class="badge badge-warning">New</span>
                        <?php endif; ?>
                    </span>
                </li>
                <?php if ($row['submitter_email']): ?>
                    <li class="kv-row">
                        <span class="kv-label">Submitter</span>
                        <span class="kv-value"><a href="mailto:<?= e($row['submitter_email']) ?>"><?= e($row['submitter_email']) ?></a></span>
                    </li>
                <?php endif; ?>
                <li class="kv-row">
                    <span class="kv-label">IP</span>
                    <span class="kv-value kv-mono"><?= e($row['ip'] ?: '—') ?></span>
                </li>
                <?php if ($row['user_agent']): ?>
                    <li class="kv-row">
                        <span class="kv-label">User agent</span>
                        <span class="kv-value text-xs" style="text-align:right;"><?= e(mb_strimwidth($row['user_agent'], 0, 80, '…')) ?></span>
                    </li>
                <?php endif; ?>
            </ul>
        </div>

        <div class="aside-card">
            <div class="aside-card-title">Audit Trail</div>
            <ol class="audit-trail">
                <?php foreach ($audit as $a): if (empty($a['when'])) continue; ?>
                    <li class="audit-trail-item<?= !empty($a['muted']) ? ' is-muted' : '' ?>">
                        <div class="audit-trail-action"><?= e($a['action']) ?></div>
                        <div class="audit-trail-meta"><?= e(date('j M Y, H:i', strtotime($a['when']))) ?></div>
                        <?php if (!empty($a['detail'])): ?>
                            <div class="audit-trail-detail"><?= e((string)$a['detail']) ?></div>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ol>
        </div>
    </aside>

<?php slate_page_layout_end(); ?>

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