<?php
/**
 * Builds the WHERE clause shared by the dashboard table and the CSV export.
 * Returns [sql, params, filters].
 */
function rsvp_filters(): array
{
    $status = $_GET['status'] ?? 'all';
    if (!in_array($status, ['all', 'yes', 'no'], true)) {
        $status = 'all';
    }

    $search = trim((string) ($_GET['q'] ?? ''));
    $from   = trim((string) ($_GET['from'] ?? ''));
    $to     = trim((string) ($_GET['to'] ?? ''));

    $isDate = static fn ($d) => (bool) preg_match('/^\d{4}-\d{2}-\d{2}$/', $d);
    if (!$isDate($from)) { $from = ''; }
    if (!$isDate($to))   { $to = ''; }

    $where  = [];
    $params = [];

    if ($status === 'yes') { $where[] = 'attending = 1'; }
    if ($status === 'no')  { $where[] = 'attending = 0'; }

    if ($search !== '') {
        $where[] = '(full_name LIKE ? OR phone_e164 LIKE ? OR phone LIKE ?)';
        $like = '%' . $search . '%';
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
    }

    if ($from !== '') {
        $where[] = 'created_at >= ?';
        $params[] = $from . ' 00:00:00';
    }
    if ($to !== '') {
        $where[] = 'created_at <= ?';
        $params[] = $to . ' 23:59:59';
    }

    $sql = $where ? ' WHERE ' . implode(' AND ', $where) : '';

    return [$sql, $params, [
        'status' => $status,
        'q'      => $search,
        'from'   => $from,
        'to'     => $to,
    ]];
}

function filter_query(array $filters, array $extra = []): string
{
    $params = array_filter(array_merge($filters, $extra), static fn ($v) => $v !== '' && $v !== null);
    if (isset($params['status']) && $params['status'] === 'all') {
        unset($params['status']);
    }
    return $params ? '?' . http_build_query($params) : '';
}
