<?php
/**
 * Departed Members - Manage deceased members
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/member-validation.php';
require_once __DIR__ . '/../../includes/audit-entities.php';
requireAuth();

// Only admin and system_admin can manage departed members
if (!isAdmin() && !isSystemAdmin()) {
    header('Location: ' . BASE_PATH . '/members');
    exit;
}

// JSON search for members (non-departed only) - used by the search input
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['search']) && isset($_GET['q'])) {
    header('Content-Type: application/json; charset=utf-8');
    $q = trim($_GET['q'] ?? '');
    $out = ['members' => []];
    if (strlen($q) >= 2) {
        $term = '%' . $q . '%';
        $stmt = $pdo->prepare("
            SELECT id, title, first_name, middle_name, last_name
            FROM members
            WHERE (status != 'deceased' OR status IS NULL) AND (date_of_death IS NULL)
            AND (first_name LIKE ? OR last_name LIKE ? OR middle_name LIKE ? OR CONCAT(COALESCE(first_name,''), ' ', COALESCE(last_name,'')) LIKE ? OR CONCAT(COALESCE(last_name,''), ' ', COALESCE(first_name,'')) LIKE ?)
            ORDER BY last_name, first_name
            LIMIT 25
        ");
        $stmt->execute([$term, $term, $term, $term, $term]);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $name = trim(($row['title'] ?? '') . ' ' . ($row['first_name'] ?? '') . ' ' . ($row['middle_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
            $out['members'][] = ['id' => (int)$row['id'], 'name' => $name];
        }
    }
    echo json_encode($out);
    exit;
}

$pageTitle = 'Departed Members';
$currentPage = 'members';

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_departed') {
        $memberId = (int)($_POST['member_id'] ?? 0);
        $dateOfDeath = trim($_POST['date_of_death'] ?? '');
        
        if ($memberId > 0 && !empty($dateOfDeath)) {
            // Check if member exists and is not already departed
            $stmt = $pdo->prepare('SELECT id, status, date_of_death, date_of_birth FROM members WHERE id = ?');
            $stmt->execute([$memberId]);
            $member = $stmt->fetch();

            if ($member) {
                $dateErrors = validateMemberDates($member['date_of_birth'] ?? null, null, $dateOfDeath);
                if (!empty($dateErrors)) {
                    header('Location: ' . BASE_PATH . '/members/departed?toast_error=' . urlencode(implode(' ', $dateErrors)));
                    exit;
                }
                $stmt = $pdo->prepare('UPDATE members SET status = ?, date_of_death = ? WHERE id = ?');
                $stmt->execute(['deceased', $dateOfDeath, $memberId]);
                try {
                    $stmt = $pdo->prepare('SELECT * FROM members WHERE id = ?');
                    $stmt->execute([$memberId]);
                    $nm = $stmt->fetch(PDO::FETCH_ASSOC);
                    $name = $nm ? nazarethMemberDisplayName($nm) : ('Member #' . $memberId);
                    logActivity(
                        'member_marked_departed',
                        "Member marked as departed: {$name} (ID {$memberId})",
                        ['member_id' => $memberId, 'date_of_death' => $dateOfDeath],
                        currentUserId() ? (int) currentUserId() : null
                    );
                } catch (Throwable $e) {
                    error_log('departed audit: ' . $e->getMessage());
                }
                header('Location: ' . BASE_PATH . '/members/departed?toast=' . urlencode('Member marked as departed.'));
                exit;
            }
        }
        header('Location: ' . BASE_PATH . '/members/departed?toast_error=' . urlencode('Invalid member or date.'));
        exit;
    }
    
    if ($action === 'remove_departed') {
        $memberId = (int)($_POST['member_id'] ?? 0);
        
        if ($memberId > 0) {
            $stmt = $pdo->prepare('SELECT * FROM members WHERE id = ?');
            $stmt->execute([$memberId]);
            $beforeRow = $stmt->fetch(PDO::FETCH_ASSOC);
            $stmt = $pdo->prepare('UPDATE members SET status = ?, date_of_death = NULL WHERE id = ?');
            // Reset to communicant as default, or you could preserve original status if stored
            $stmt->execute(['communicant', $memberId]);
            try {
                $name = $beforeRow ? nazarethMemberDisplayName($beforeRow) : ('Member #' . $memberId);
                logActivity(
                    'member_departed_removed',
                    "Departed status removed (restored to communicant): {$name} (ID {$memberId})",
                    ['member_id' => $memberId, 'previous_status' => $beforeRow['status'] ?? null, 'previous_date_of_death' => $beforeRow['date_of_death'] ?? null],
                    currentUserId() ? (int) currentUserId() : null
                );
            } catch (Throwable $e) {
                error_log('departed audit: ' . $e->getMessage());
            }
            header('Location: ' . BASE_PATH . '/members/departed?toast=' . urlencode('Departed status removed.'));
            exit;
        }
        header('Location: ' . BASE_PATH . '/members/departed?toast_error=' . urlencode('Invalid member.'));
        exit;
    }
}

// Get all departed members
$departedMembers = $pdo->query("
    SELECT m.*, h.name AS household_name
    FROM members m
    LEFT JOIN households h ON m.household_id = h.id
    WHERE m.status = 'deceased' OR m.date_of_death IS NOT NULL
    ORDER BY m.date_of_death DESC, m.last_name, m.first_name
")->fetchAll();

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

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

<div class="card" style="margin-bottom: 2rem;">
    <h2 style="margin-top: 0;">Mark Member as Departed</h2>
    <form method="post" id="departed-form" style="max-width: 600px;">
        <input type="hidden" name="action" value="add_departed">
        <input type="hidden" name="member_id" id="member_id" value="">
        <div class="form-row">
            <div class="form-group" style="position: relative;">
                <label for="member_search">Search Member</label>
                <input type="text" id="member_search" autocomplete="off" placeholder="Type name to search (min 2 characters)..." style="width: 100%;">
                <div id="member_search_results" class="member-search-results" role="listbox" aria-label="Search results" hidden></div>
                <p id="member_selected_display" class="member-selected-display" style="display: none; margin-top: 0.5rem;">
                    <span id="member_selected_name"></span>
                    <button type="button" class="btn btn-sm btn-outline" id="member_clear_btn" style="margin-left: 0.5rem;">Change member</button>
                </p>
            </div>
            <div class="form-group">
                <label for="date_of_death">Date of Death</label>
                <input type="date" id="date_of_death" name="date_of_death" required style="width: 100%;">
            </div>
        </div>
        <div class="form-group">
            <button type="submit" class="btn" id="submit_departed_btn" disabled>Mark as Departed</button>
        </div>
    </form>
</div>

<div class="card">
    <h2 style="margin-top: 0;">Departed Members (<?= count($departedMembers) ?>)</h2>
    
    <?php if (empty($departedMembers)): ?>
        <p class="text-muted">No departed members recorded.</p>
    <?php else: ?>
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Date of Death</th>
                        <th>Age at Death</th>
                        <th>Household</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($departedMembers as $m): 
                        $name = trim(($m['title'] ?? '') . ' ' . ($m['first_name'] ?? '') . ' ' . ($m['middle_name'] ?? '') . ' ' . ($m['last_name'] ?? ''));
                        $photoUrl = !empty($m['photo']) ? BASE_PATH . '/public/uploads/members/' . htmlspecialchars($m['photo']) : null;
                        
                        // Calculate age at death
                        $ageAtDeath = null;
                        if (!empty($m['date_of_birth']) && !empty($m['date_of_death'])) {
                            $dob = new DateTime($m['date_of_birth']);
                            $dod = new DateTime($m['date_of_death']);
                            $ageAtDeath = $dob->diff($dod)->y;
                        }
                    ?>
                        <tr style="opacity: 0.8;">
                            <td>
                                <?php if ($photoUrl): ?>
                                    <img src="<?= $photoUrl ?>" alt="" class="member-list-photo" style="filter: grayscale(100%); opacity: 0.6;">
                                <?php endif; ?>
                                <a href="<?= BASE_PATH ?>/members/view/<?= $m['id'] ?>"><?= htmlspecialchars($name) ?></a>
                            </td>
                            <td>
                                <?php if (!empty($m['date_of_death'])): ?>
                                    <?= date('F j, Y', strtotime($m['date_of_death'])) ?>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($ageAtDeath !== null): ?>
                                    <?= $ageAtDeath ?> years
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($m['household_name'] ?? '—') ?></td>
                            <td class="actions">
                                <a href="<?= BASE_PATH ?>/members/view/<?= $m['id'] ?>" class="btn btn-sm btn-outline">View</a>
                                <form method="post" style="display: inline-block;" onsubmit="return confirm('Remove departed status for this member?');">
                                    <input type="hidden" name="action" value="remove_departed">
                                    <input type="hidden" name="member_id" value="<?= $m['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-outline" style="color: #059669;">Restore</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<style>
.member-search-results {
    position: absolute;
    left: 0;
    right: 0;
    top: 100%;
    margin-top: 2px;
    max-height: 280px;
    overflow-y: auto;
    background: #fff;
    border: 1px solid var(--border, #e2e8f0);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    z-index: 100;
}
.member-search-results[hidden] { display: none !important; }
.member-search-results .member-search-item {
    display: block;
    width: 100%;
    padding: 0.6rem 0.75rem;
    text-align: left;
    background: none;
    border: none;
    cursor: pointer;
    font-size: 0.9375rem;
    color: #1e293b;
}
.member-search-results .member-search-item:hover,
.member-search-results .member-search-item:focus {
    background: #f1f5f9;
    outline: none;
}
.member-search-results .member-search-item strong { font-weight: 600; }
.member-selected-display { font-size: 0.9375rem; }
</style>
<script>
(function() {
    var form = document.getElementById('departed-form');
    var searchInput = document.getElementById('member_search');
    var memberIdInput = document.getElementById('member_id');
    var resultsEl = document.getElementById('member_search_results');
    var selectedDisplay = document.getElementById('member_selected_display');
    var submitBtn = document.getElementById('submit_departed_btn');
    var debounceTimer = null;
    var basePath = '<?= addslashes(BASE_PATH) ?>';

    function showResults(items) {
        resultsEl.innerHTML = '';
        resultsEl.hidden = false;
        if (!items || items.length === 0) {
            resultsEl.innerHTML = '<div style="padding: 0.75rem; color: #64748b;">No members found. Try another search.</div>';
            return;
        }
        items.forEach(function(m) {
            var btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'member-search-item';
            btn.setAttribute('role', 'option');
            btn.setAttribute('data-id', m.id);
            btn.setAttribute('data-name', m.name);
            btn.textContent = m.name;
            btn.addEventListener('click', function() {
                memberIdInput.value = m.id;
                selectedDisplay.querySelector('#member_selected_name').textContent = 'Selected: ' + m.name;
                selectedDisplay.style.display = 'block';
                searchInput.value = '';
                searchInput.placeholder = 'Change member (search again)';
                resultsEl.hidden = true;
                resultsEl.innerHTML = '';
                submitBtn.disabled = false;
            });
            resultsEl.appendChild(btn);
        });
    }

    function doSearch() {
        var q = (searchInput.value || '').trim();
        if (q.length < 2) {
            resultsEl.hidden = true;
            resultsEl.innerHTML = '';
            return;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('GET', basePath + '/members/departed?search=1&q=' + encodeURIComponent(q), true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState !== 4) return;
            if (xhr.status === 200) {
                try {
                    var data = JSON.parse(xhr.responseText);
                    showResults(data.members || []);
                } catch (e) {
                    showResults([]);
                }
            } else {
                showResults([]);
            }
        };
        xhr.send();
    }

    searchInput.addEventListener('input', function() {
        if (debounceTimer) clearTimeout(debounceTimer);
        if ((searchInput.value || '').trim().length < 2) {
            resultsEl.hidden = true;
            resultsEl.innerHTML = '';
            return;
        }
        debounceTimer = setTimeout(doSearch, 250);
    });

    searchInput.addEventListener('focus', function() {
        if ((searchInput.value || '').trim().length >= 2 && resultsEl.children.length) resultsEl.hidden = false;
    });

    searchInput.addEventListener('blur', function() {
        setTimeout(function() {
            var active = document.activeElement;
            if (active && resultsEl.contains(active)) return;
            resultsEl.hidden = true;
        }, 200);
    });

    form.addEventListener('submit', function(e) {
        if (!memberIdInput.value || memberIdInput.value === '') {
            e.preventDefault();
            alert('Please search and select a member first.');
            searchInput.focus();
            return false;
        }
    });

    var clearBtn = document.getElementById('member_clear_btn');
    if (clearBtn) {
        clearBtn.addEventListener('click', function() {
            memberIdInput.value = '';
            selectedDisplay.querySelector('#member_selected_name').textContent = '';
            selectedDisplay.style.display = 'none';
            searchInput.placeholder = 'Type name to search (min 2 characters)...';
            searchInput.value = '';
            searchInput.focus();
            submitBtn.disabled = true;
            resultsEl.hidden = true;
            resultsEl.innerHTML = '';
        });
    }
})();
</script>

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