<?php
/**
 * Forms — submissions inbox.
 *
 * Filter by form + read/unread. CSV export honours the current
 * filter set. Click into a row → submission detail (right-rail).
 */
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();

// ── CSV export ───────────────────────────────────────────────
if (($_GET['export'] ?? '') === 'csv') {
    Auth::requirePerm('forms.export');
    $formId = (int)($_GET['form_id'] ?? 0);
    if ($formId <= 0) {
        http_response_code(400);
        echo 'Specify a form_id to export.';
        exit;
    }

    $form = FormsAPI::getFormById($formId);
    if (!$form) {
        http_response_code(404);
        echo 'Form not found.';
        exit;
    }

    $rows = Database::rows(
        "SELECT * FROM forms_submissions
          WHERE tenant_id = ? AND form_id = ?
       ORDER BY created_at DESC",
        [$tid, $formId]
    );

    $fieldNames = [];
    foreach ($form['fields'] as $f) {
        if (!empty($f['name'])) $fieldNames[] = $f['name'];
    }

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="forms-' . preg_replace('/[^a-z0-9-]/i', '-', $form['slug']) . '-'
         . date('Ymd-His') . '.csv"');
    $out = fopen('php://output', 'w');
    // BOM so Excel picks UTF-8
    fwrite($out, "\xEF\xBB\xBF");
    // Neutralise CSV/formula injection: a cell starting with = + - @ (or a
    // tab/CR) is run as a formula by Excel/Sheets. Submitted values are
    // attacker-controlled, so prefix risky cells with a quote.
    $csvSafe = static function ($v): string {
        $s = (string)$v;
        if ($s !== '' && in_array($s[0], ['=', '+', '-', '@', "\t", "\r"], true)) {
            return "'" . $s;
        }
        return $s;
    };
    fputcsv($out, array_merge(['ref', 'created_at', 'ip', 'submitter_email'], $fieldNames));
    foreach ($rows as $r) {
        $data = json_decode($r['data_json'] ?? '{}', true) ?: [];
        $row  = [$r['ref'], $r['created_at'], $r['ip'], $r['submitter_email']];
        foreach ($fieldNames as $n) {
            $v = $data[$n] ?? '';
            if (is_bool($v)) $v = $v ? 'yes' : 'no';
            if (is_array($v)) $v = json_encode($v, JSON_UNESCAPED_UNICODE);
            $row[] = (string)$v;
        }
        fputcsv($out, array_map($csvSafe, $row));
    }
    fclose($out);
    AuditLog::record('forms.exported', (string)$formId, ['count' => count($rows)]);
    exit;
}

// ── POST handlers (mark read, delete) ────────────────────────
$flash = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $flash = ['type' => 'error', 'msg' => 'Security check failed.'];
    } else {
        $action = $_POST['_action'] ?? '';
        $sid    = (int)($_POST['id'] ?? 0);
        if ($sid > 0) {
            if ($action === 'mark_read') {
                Database::update('forms_submissions', ['read_at' => date('Y-m-d H:i:s')],
                    'id = ? AND tenant_id = ?', [$sid, $tid]);
                $flash = ['type' => 'success', 'msg' => 'Marked as read.'];
            } elseif ($action === 'mark_unread') {
                Database::update('forms_submissions', ['read_at' => null],
                    'id = ? AND tenant_id = ?', [$sid, $tid]);
                $flash = ['type' => 'success', 'msg' => 'Marked as unread.'];
            } elseif ($action === 'delete' && Auth::can('forms.manage')) {
                Database::delete('forms_submissions', 'id = ? AND tenant_id = ?', [$sid, $tid]);
                AuditLog::record('forms.submission_deleted', (string)$sid);
                $flash = ['type' => 'success', 'msg' => 'Submission deleted.'];
            }
        }
    }
}

// ── Filters ──────────────────────────────────────────────────
$formId   = (int)($_GET['form_id'] ?? 0);
$showRead = ($_GET['show'] ?? 'all'); // all | unread | read

$forms = Database::rows(
    "SELECT id, slug, title FROM forms_definitions WHERE tenant_id = ? ORDER BY title",
    [$tid]
);

$where  = ['s.tenant_id = ?'];
$params = [$tid];
if ($formId > 0) {
    $where[] = 's.form_id = ?';
    $params[] = $formId;
}
if ($showRead === 'unread') {
    $where[] = 's.read_at IS NULL';
} elseif ($showRead === 'read') {
    $where[] = 's.read_at IS NOT NULL';
}
$whereSql = implode(' AND ', $where);

// Pagination
$perPage    = 30;
$page       = max(1, (int)($_GET['page'] ?? 1));
$totalSubs  = (int) Database::value(
    "SELECT COUNT(*) FROM forms_submissions s
       JOIN forms_definitions f ON f.id = s.form_id AND f.tenant_id = s.tenant_id
      WHERE $whereSql", $params);
$totalPages = max(1, (int)ceil($totalSubs / $perPage));
$page       = min($page, $totalPages);
$offset     = ($page - 1) * $perPage;

$rows = Database::rows(
    "SELECT s.*, f.title AS form_title, f.slug AS form_slug
       FROM forms_submissions s
       JOIN forms_definitions f ON f.id = s.form_id AND f.tenant_id = s.tenant_id
      WHERE $whereSql
   ORDER BY s.created_at DESC
      LIMIT {$perPage} OFFSET {$offset}",
    $params
);

$pageTitle  = __('forms_submissions', 'Submissions');
$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')],
]); ?>

<div class="page-header">
    <div>
        <h1>Submissions</h1>
        <p class="page-header-sub"><?= number_format($totalSubs) ?> entries across your published forms.</p>
    </div>
    <?php if ($formId > 0 && Auth::can('forms.export')): ?>
        <a href="?export=csv&form_id=<?= (int)$formId ?>" class="btn btn-primary">Export CSV</a>
    <?php endif; ?>
</div>

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

<div class="card tight">
    <form method="get" class="filter-row">
        <div class="field filter-search">
            <label class="field-label" for="form_id">Form</label>
            <select id="form_id" name="form_id">
                <option value="0">All forms</option>
                <?php foreach ($forms as $f): ?>
                    <option value="<?= (int)$f['id'] ?>" <?= $formId === (int)$f['id'] ? 'selected' : '' ?>>
                        <?= e($f['title']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="field">
            <label class="field-label" for="show">Show</label>
            <select id="show" name="show">
                <option value="all"    <?= $showRead === 'all'    ? 'selected' : '' ?>>All</option>
                <option value="unread" <?= $showRead === 'unread' ? 'selected' : '' ?>>Unread</option>
                <option value="read"   <?= $showRead === 'read'   ? 'selected' : '' ?>>Read</option>
            </select>
        </div>
        <div class="filter-actions">
            <button type="submit" class="btn">Filter</button>
            <a href="<?= e(plugin_url('forms', 'admin/submissions.php')) ?>" class="btn btn-ghost">Reset</a>
        </div>
    </form>
</div>

<?php if (empty($rows)): ?>
    <div class="card">
        <div class="empty">
            <div class="empty-title">No submissions yet</div>
            <p class="text-sm">When someone fills out a form, it'll show up here.</p>
        </div>
    </div>
<?php else: ?>

    <div class="data-list" data-single-open>
        <?php foreach ($rows as $r):
            $data = json_decode($r['data_json'] ?? '{}', true) ?: [];

            $primary = $r['submitter_email'] ?? '';
            if ($primary === '') {
                foreach ($data as $v) {
                    if (is_string($v) && $v !== '') { $primary = $v; break; }
                }
            }

            $detail = [
                'Ref'         => ['label' => 'Ref',         'html' => '<code>' . e($r['ref']) . '</code>'],
                'Form'        => $r['form_title'],
                'Received'    => date('j M Y, H:i', strtotime($r['created_at'])),
                'IP'          => $r['ip'] ?: '—',
                'Email sent'  => (int)$r['email_sent'] === 1 ? 'Yes' : 'No',
            ];
            if (!empty($r['email_error'])) {
                $detail['Email error'] = ['label' => 'Email error', 'value' => $r['email_error']];
            }

            $detailUrl = plugin_url('forms', 'admin/submission.php') . '?id=' . (int)$r['id'];

            $actions = '<a href="' . e($detailUrl) . '" class="btn btn-sm btn-primary">Open</a>';
            $actions .= ' <form method="post" style="display:inline; margin:0;">' . csrf_field()
                      . '<input type="hidden" name="id" value="' . (int)$r['id'] . '">';
            if ($r['read_at']) {
                $actions .= '<button name="_action" value="mark_unread" class="btn btn-sm">Mark unread</button>';
            } else {
                $actions .= '<button name="_action" value="mark_read" class="btn btn-sm">Mark read</button>';
            }
            $actions .= '</form>';
            if (Auth::can('forms.manage')) {
                $actions .= ' <form method="post" style="display:inline; margin:0;" onsubmit="return confirm(\'Delete this submission?\')">' . csrf_field()
                          . '<input type="hidden" name="id" value="' . (int)$r['id'] . '">'
                          . '<button name="_action" value="delete" class="btn btn-sm btn-danger">Delete</button>'
                          . '</form>';
            }

            $badge = $r['read_at'] ? ['Read', 'inactive'] : ['New', 'warning'];

            slate_data_row([
                'avatar'       => mb_substr($r['form_title'] ?: 'S', 0, 1),
                'avatar_color' => $r['read_at'] ? 'muted' : 'info',
                'title'        => $primary !== '' ? $primary : '(no email)',
                'meta'         => $r['form_title'] . ' · ' . date('j M Y, H:i', strtotime($r['created_at'])),
                'badge'        => $badge,
                'detail'       => $detail,
                'actions'      => $actions,
            ]);
        endforeach; ?>
    </div>

    <?php slate_data_list_script(); ?>
    <?php slate_pagination($page, $totalPages, $_GET, [
        'total' => $totalSubs, 'per_page' => $perPage, 'label' => 'submissions',
    ]); ?>
<?php endif; ?>

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