<?php
/**
 * Admin: search and permanently remove mistaken or duplicate member records.
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/member-delete.php';
require_once __DIR__ . '/../../includes/fellowships.php';

requireAuth();

if (!canDeleteMembers()) {
    header('Location: ' . BASE_PATH . '/members?toast_error=' . urlencode('Only administrators can remove members.'));
    exit;
}

$pageTitle = 'Remove member';
$currentPage = 'members';

$search = trim($_GET['search'] ?? '');
$members = [];

if ($search !== '') {
    $term = '%' . $search . '%';
    $sql = "
        SELECT m.id, m.title, m.first_name, m.middle_name, m.last_name, m.phone, m.email,
               m.membership_number, m.status, m.date_of_birth, m.created_at,
               u.full_name AS created_by_name
        FROM members m
        LEFT JOIN users u ON u.id = m.created_by
        WHERE m.first_name LIKE ? OR m.last_name LIKE ? OR m.phone LIKE ?
           OR m.email LIKE ? OR COALESCE(m.membership_number, '') LIKE ?
           OR CONCAT(COALESCE(m.first_name,''), ' ', COALESCE(m.last_name,'')) LIKE ?
        ORDER BY m.last_name, m.first_name
        LIMIT 50
    ";
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$term, $term, $term, $term, $term, $term]);
        $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        if (strpos($e->getMessage(), 'created_by') !== false) {
            $sql = str_replace('LEFT JOIN users u ON u.id = m.created_by', '', $sql);
            $sql = str_replace(', u.full_name AS created_by_name', '', $sql);
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$term, $term, $term, $term, $term, $term]);
            $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            throw $e;
        }
    }
}

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

<div class="header">
    <h1>Remove member</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/members" class="link-muted">← Members</a>
    </div>
</div>

<div class="remove-member-layout">

<div class="form-card remove-member-card">
    <p class="text-muted remove-member-intro">Permanent delete for mistaken or duplicate records only. Use <a href="<?= BASE_PATH ?>/members/departed">Departed</a> if someone is no longer active.</p>
    <form method="get" action="<?= BASE_PATH ?>/members/remove" class="form-inline" style="display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: end;">
        <div class="form-group" style="flex: 1; min-width: 220px; margin: 0;">
            <label for="remove_search">Search by name, phone, email, or membership number</label>
            <input type="search" id="remove_search" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="e.g. Kwame Mensah" autofocus>
        </div>
        <button type="submit" class="btn">Search</button>
        <?php if ($search !== ''): ?>
            <a href="<?= BASE_PATH ?>/members/remove" class="btn btn-secondary">Clear</a>
        <?php endif; ?>
    </form>
</div>

<?php if ($search !== ''): ?>
    <?php if (empty($members)): ?>
    <div class="remove-member-empty" role="status" aria-live="polite">
        <h2 class="remove-member-empty-title">No member found for “<?= htmlspecialchars($search) ?>”</h2>
        <p class="remove-member-empty-lede">Try another spelling or phone number. If they were never saved in the app, there is nothing to delete — check <a href="<?= BASE_PATH ?>/members">Members</a>.</p>
        <div class="remove-member-empty-actions">
            <a href="<?= BASE_PATH ?>/members/remove" class="btn btn-secondary">Clear search</a>
        </div>
    </div>
    <?php else: ?>
        <div class="table-wrap remove-member-card remove-member-results">
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Status</th>
                        <th>Entered</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($members as $m):
                        $name = trim(($m['title'] ?? '') . ' ' . ($m['first_name'] ?? '') . ' ' . ($m['middle_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                        $created = !empty($m['created_at']) ? date('M j, Y', strtotime($m['created_at'])) : '—';
                        $by = trim((string)($m['created_by_name'] ?? ''));
                        $confirm = 'Permanently delete “' . $name . '”? This cannot be undone.';
                    ?>
                    <tr>
                        <td>
                            <a href="<?= BASE_PATH ?>/members/view/<?= (int)$m['id'] ?>"><?= htmlspecialchars($name) ?></a>
                            <?php if (!empty($m['membership_number'])): ?>
                                <br><small class="text-muted"><?= htmlspecialchars($m['membership_number']) ?></small>
                            <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($m['phone'] ?: '—') ?></td>
                        <td><?= htmlspecialchars($m['status'] ?? '—') ?></td>
                        <td>
                            <?= htmlspecialchars($created) ?>
                            <?php if ($by !== ''): ?><br><small class="text-muted">by <?= htmlspecialchars($by) ?></small><?php endif; ?>
                        </td>
                        <td class="actions">
                            <a href="<?= BASE_PATH ?>/members/view/<?= (int)$m['id'] ?>" class="btn btn-sm btn-outline">View</a>
                            <a href="<?= BASE_PATH ?>/members/delete/<?= (int)$m['id'] ?>"
                               class="btn btn-sm btn-outline"
                               style="color:#b91c1c;border-color:#fecaca;"
                               data-confirm="<?= htmlspecialchars($confirm) ?>"
                               data-confirm-btn="Delete permanently">Delete</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
<?php endif; ?>

</div><!-- .remove-member-layout -->

<style>
.remove-member-layout {
    max-width: 720px;
    margin: 0 auto;
    padding: 0 1rem 2rem;
}
.remove-member-card {
    max-width: 100%;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 1.25rem;
}
.remove-member-intro {
    margin: 0 0 1rem;
    font-size: 0.875rem;
}
.remove-member-results {
    width: 100%;
}
.remove-member-empty {
    max-width: 100%;
    margin: 0.5rem auto 2rem;
    text-align: center;
    padding: 1.5rem 1.75rem;
    background: #fffbeb;
    border: 1px solid #fde68a;
    border-left: 4px solid #d97706;
    border-radius: 0;
}
.remove-member-empty-title {
    margin: 0 0 0.5rem;
    font-size: 1.125rem;
    font-weight: 700;
    color: #92400e;
}
.remove-member-empty-lede {
    margin: 0 0 1.25rem;
    color: #78350f;
    line-height: 1.5;
    max-width: 480px;
    margin-left: auto;
    margin-right: auto;
}
.remove-member-empty-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    justify-content: center;
}
</style>

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