<?php
/**
 * Mobile directory: all active members; search; tap for details, then Edit.
 */
require_once __DIR__ . '/init.php';
require_once __DIR__ . '/../includes/auth.php';
$pageTitle = 'Members';
$uid = (int)currentUserId();

$toast = null;
$toastError = null;
if (!empty($_GET['toast'])) {
    $toast = (string)$_GET['toast'];
}
if (!empty($_GET['toast_error'])) {
    $toastError = (string)$_GET['toast_error'];
}

$q = trim((string)($_GET['q'] ?? ''));
$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 ($q !== '') {
    $sql .= " AND (
        first_name LIKE ? OR last_name LIKE ? OR phone LIKE ?
        OR COALESCE(membership_number, '') LIKE ?
        OR CONCAT(COALESCE(first_name,''), ' ', COALESCE(last_name,'')) LIKE ?
    )";
    $like = '%' . $q . '%';
    $params = [$like, $like, $like, $like, $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);
        try {
            $stmt = $pdo->prepare($sqlNoCreator);
            $stmt->execute($params);
            $rows = $stmt->fetchAll();
            foreach ($rows as &$row) {
                $row['created_by'] = null;
            }
            unset($row);
        } catch (Throwable $e2) {
            $rows = [];
        }
    } else {
        $rows = [];
    }
}

$searchFormAction = BASE_PATH . '/mobile';
$mobileAppIcon = BASE_PATH . '/mobile/assets/img/192.png';
$mobileAppIconV = @filemtime(__DIR__ . '/assets/img/192.png');
if ($mobileAppIconV) {
    $mobileAppIcon .= '?v=' . (int) $mobileAppIconV;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <?php require_once __DIR__ . '/pwa-gate-head.php'; ?>
    <title><?= htmlspecialchars($pageTitle) ?> — <?= htmlspecialchars(SITE_NAME) ?></title>
    <link rel="icon" href="<?= htmlspecialchars($mobileAppIcon, ENT_QUOTES, 'UTF-8') ?>" type="image/png" sizes="192x192">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?= nazareth_asset('css/style.css') ?>?v=<?= @filemtime(__DIR__ . '/../public/css/style.css') ?>">
    <link rel="stylesheet" href="<?= nazareth_mobile_asset('mobile.css') ?>?v=<?= @filemtime(__DIR__ . '/mobile.css') ?>">
    <?php require_once __DIR__ . '/pwa-head.php';
    nazareth_mobile_pwa_head(); ?>
</head>
<body class="mobile-collect-body">
    <div class="mobile-collect-shell">
        <header class="mobile-collect-topbar">
            <h1>Members</h1>
            <a href="<?= BASE_PATH ?>/logout?mobile=1">Log out</a>
        </header>
        <main class="mobile-collect-main">
            <?php if ($toast): ?>
                <div class="mobile-collect-toast"><?= htmlspecialchars($toast) ?></div>
            <?php endif; ?>
            <?php if ($toastError): ?>
                <div class="mobile-collect-alert" style="margin-bottom:0.75rem;"><?= htmlspecialchars($toastError) ?></div>
            <?php endif; ?>

            <?php
            $mobileSearchIcon = '<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>';
            ?>
            <form class="mobile-dir-search" method="get" action="<?= htmlspecialchars($searchFormAction) ?>" role="search">
                <label class="sr-only" for="mobile_dir_q">Search members by name, phone, or membership number</label>
                <div class="mobile-dir-search-inner">
                    <div class="mobile-dir-input-wrap">
                        <span class="mobile-dir-search-glyph"><?= $mobileSearchIcon ?></span>
                        <input type="search" id="mobile_dir_q" name="q" value="<?= htmlspecialchars($q) ?>"
                            class="mobile-dir-search-input"
                            placeholder="Name, phone, or membership no."
                            autocomplete="off" enterkeyhint="search">
                    </div>
                    <button type="submit" class="mobile-dir-search-submit" title="Search" aria-label="Search members">
                        <?= $mobileSearchIcon ?>
                    </button>
                </div>
            </form>
            <?php if ($q !== ''): ?>
                <p class="mobile-dir-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="mobile-dir-meta"><?= (int)$totalActive ?> active member<?= $totalActive === 1 ? '' : 's' ?></p>
            <?php endif; ?>

            <?php if (empty($rows)): ?>
                <div class="mobile-collect-empty">
                    <?php if ($totalActive === 0): ?>
                        No members in the system yet. Tap <strong>+ New</strong> to add the first record.
                    <?php elseif ($q !== ''): ?>
                        No members match “<?= htmlspecialchars($q) ?>”. Try another search or <a href="<?= htmlspecialchars($searchFormAction) ?>">clear</a>.
                    <?php else: ?>
                        No members to show.
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <p class="mobile-list-edit-hint">Tap a member for <strong>details</strong>, then use <strong>Edit</strong> in the header to change their record.</p>
                <div class="mobile-collect-cards">
                    <?php foreach ($rows as $r): ?>
                        <?php
                        $name = trim(($r['first_name'] ?? '') . ' ' . ($r['last_name'] ?? ''));
                        $phone = trim((string)($r['phone'] ?? ''));
                        $dob = $r['date_of_birth'] ?? '';
                        $memNo = trim((string)($r['membership_number'] ?? ''));
                        $mine = isset($r['created_by']) && (int)$r['created_by'] === $uid;
                        $href = BASE_PATH . '/mobile/view/' . (int)$r['id'];
                        ?>
                        <a class="mobile-collect-card<?= $mine ? ' mobile-collect-card--mine' : '' ?>" href="<?= htmlspecialchars($href) ?>">
                            <?php if ($mine): ?>
                                <span class="mobile-card-badge">Your entry</span>
                            <?php endif; ?>
                            <strong><?= htmlspecialchars($name ?: 'Member #' . (int)$r['id']) ?></strong>
                            <span class="meta">
                                <?php if ($memNo !== ''): ?><span class="mobile-card-memno"><?= htmlspecialchars($memNo) ?></span> · <?php endif; ?>
                                <?php if ($phone !== ''): ?>📞 <?= htmlspecialchars($phone) ?><?php else: ?>No phone<?php endif; ?>
                                <?php if ($dob): ?> · DOB <?= htmlspecialchars($dob) ?><?php endif; ?>
                            </span>
                        </a>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            <?php if (can('households.manage')): ?>
            <p class="mobile-help-footer-link"><a href="<?= BASE_PATH ?>/households">Households</a> — add or edit family groups for the directory.</p>
            <?php endif; ?>
        </main>
        <a class="mobile-collect-fab" href="<?= BASE_PATH ?>/mobile/new">+ New</a>
    </div>
    <?php nazareth_mobile_pwa_scripts(); ?>
</body>
</html>
