<?php
/**
 * Data collection — member directory (desktop).
 */
require_once __DIR__ . '/../../includes/collect-routing.php';

$uid = (int) currentUserId();
$search = trim((string) ($_GET['search'] ?? ''));
$rows = [];
$totalActive = 0;

try {
    $totalActive = (int) $pdo->query("
        SELECT COUNT(*) FROM members
        WHERE (status IS NULL OR status != 'deceased') AND date_of_death IS NULL
    ")->fetchColumn();
} catch (Throwable $e) {
    $totalActive = 0;
}

$sql = "
    SELECT id, first_name, last_name, phone, email, date_of_birth, membership_number, created_by
    FROM members
    WHERE (status IS NULL OR status != 'deceased') AND date_of_death IS NULL
";
$params = [];
if ($search !== '') {
    $sql .= " AND (
        first_name LIKE ? OR last_name LIKE ? OR phone LIKE ? OR email LIKE ?
        OR COALESCE(membership_number, '') LIKE ?
        OR CONCAT(COALESCE(first_name,''), ' ', COALESCE(last_name,'')) LIKE ?
    )";
    $like = '%' . $search . '%';
    $params = array_fill(0, 6, $like);
}
$sql .= ' ORDER BY last_name ASC, first_name ASC, id ASC LIMIT 2500';

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
} catch (Throwable $e) {
    if (strpos($e->getMessage(), 'created_by') !== false) {
        $sqlNoCreator = str_replace(', created_by', '', $sql);
        $stmt = $pdo->prepare($sqlNoCreator);
        $stmt->execute($params);
        $rows = $stmt->fetchAll();
        foreach ($rows as &$row) {
            $row['created_by'] = null;
        }
        unset($row);
    } else {
        $rows = [];
    }
}

$toast = trim((string) ($_GET['toast'] ?? ''));
$toastError = trim((string) ($_GET['toast_error'] ?? ''));

require_once __DIR__ . '/../../includes/header.php';
?>

<?php if ($toast !== ''): ?>
    <div data-toast="success" data-toast-msg="<?= htmlspecialchars($toast) ?>" style="display:none"></div>
<?php endif; ?>
<?php if ($toastError !== ''): ?>
    <div data-toast="error" data-toast-msg="<?= htmlspecialchars($toastError) ?>" style="display:none"></div>
<?php endif; ?>

<div class="header">
    <h1>Data collection</h1>
    <div class="header-actions">
        <?php if (can('households.manage')): ?>
            <a href="<?= nazareth_url('households') ?>" class="btn btn-secondary">Households</a>
        <?php endif; ?>
        <a href="<?= nazareth_members_route('new') ?>" class="btn">+ New member</a>
        <a href="<?= nazareth_url('mobile') ?>" class="btn btn-secondary">Mobile site</a>
        <a href="<?= nazareth_url('logout') ?>">Logout</a>
    </div>
</div>

<div class="filter-bar">
    <form method="get" action="<?= htmlspecialchars(nazareth_members_route(), ENT_QUOTES, 'UTF-8') ?>" class="collect-search-form">
        <input type="search" name="search" placeholder="Name, phone, email, or membership no."
            value="<?= htmlspecialchars($search) ?>">
        <button type="submit" class="btn">Search</button>
        <?php if ($search !== ''): ?>
            <a href="<?= nazareth_members_route() ?>" class="btn btn-secondary">Clear</a>
        <?php endif; ?>
    </form>
    <?php if ($search !== ''): ?>
        <p class="text-muted collect-list-meta"><?= count($rows) ?> match<?= count($rows) === 1 ? '' : 'es' ?><?php if ($totalActive): ?> · <?= (int) $totalActive ?> active in total<?php endif; ?></p>
    <?php elseif ($totalActive > 0): ?>
        <p class="text-muted collect-list-meta"><?= (int) $totalActive ?> active member<?= $totalActive === 1 ? '' : 's' ?></p>
    <?php endif; ?>
</div>

<div class="table-wrap">
    <table>
        <thead>
            <tr>
                <th>Member no.</th>
                <th>Name</th>
                <th>Contact</th>
                <th>Date of birth</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($rows)): ?>
                <tr>
                    <td colspan="5" class="text-muted">
                        <?php if ($totalActive === 0): ?>
                            No members yet. <a href="<?= nazareth_members_route('new') ?>">Add the first record</a>.
                        <?php elseif ($search !== ''): ?>
                            No members match your search.
                        <?php else: ?>
                            No members to show.
                        <?php endif; ?>
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($rows as $r): ?>
                    <?php
                    $name = trim(($r['first_name'] ?? '') . ' ' . ($r['last_name'] ?? ''));
                    $phone = trim((string) ($r['phone'] ?? ''));
                    $memNo = trim((string) ($r['membership_number'] ?? ''));
                    $mine = isset($r['created_by']) && (int) $r['created_by'] === $uid;
                    $mid = (int) $r['id'];
                    ?>
                    <tr<?= $mine ? ' class="collect-row-mine"' : '' ?>>
                        <td><?= htmlspecialchars($memNo !== '' ? $memNo : '—') ?></td>
                        <td>
                            <a href="<?= nazareth_members_route('view/' . $mid) ?>"><?= htmlspecialchars($name ?: 'Member #' . $mid) ?></a>
                            <?php if ($mine): ?><span class="collect-badge">Your entry</span><?php endif; ?>
                        </td>
                        <td>
                            <?= htmlspecialchars($phone !== '' ? $phone : '—') ?>
                            <?php if (!empty($r['email'])): ?><br><small><?= htmlspecialchars($r['email']) ?></small><?php endif; ?>
                        </td>
                        <td><?= !empty($r['date_of_birth']) ? htmlspecialchars($r['date_of_birth']) : '—' ?></td>
                        <td class="actions">
                            <a href="<?= nazareth_members_route('view/' . $mid) ?>" class="btn btn-sm btn-outline">View</a>
                            <a href="<?= nazareth_members_route('edit/' . $mid) ?>" class="btn btn-sm btn-outline">Edit</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<p class="text-muted collect-list-hint">On a phone or tablet, open the <a href="<?= nazareth_url('mobile') ?>">mobile site</a> for the field collection app.</p>

<style>
.collect-search-form { display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center; }
.collect-search-form input[type="search"] { min-width: 16rem; flex: 1; max-width: 28rem; }
.collect-list-meta { margin: 0.5rem 0 0; font-size: 0.875rem; }
.collect-list-hint { margin-top: 1.25rem; font-size: 0.875rem; }
.collect-badge { display: inline-block; margin-left: 0.35rem; padding: 0.1rem 0.4rem; font-size: 0.7rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.03em; background: #e0e7ff; color: #3730a3; border-radius: 4px; vertical-align: middle; }
.collect-row-mine td:first-child + td { font-weight: 500; }
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
