<?php
/**
 * Member view - read-only display of member data
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/fellowships.php';
require_once __DIR__ . '/../../includes/collect-routing.php';
require_once __DIR__ . '/../../includes/member-delete.php';
requireAuth();

$stmt = $pdo->prepare("
    SELECT m.*, h.name AS household_name,
    (SELECT GROUP_CONCAT(mn.name ORDER BY mn.name SEPARATOR ', ')
     FROM member_ministries mm
     JOIN ministries mn ON mn.id = mm.ministry_id
     WHERE mm.member_id = m.id) AS ministry_names
    FROM members m
    LEFT JOIN households h ON m.household_id = h.id
    WHERE m.id = ?
");
$stmt->execute([$id]);
$m = $stmt->fetch();

if (!$m) {
    header('Location: ' . nazareth_members_route());
    exit;
}

$pageTitle = 'Member';
$currentPage = defined('NAZARETH_MEMBERS_ROUTE') ? NAZARETH_MEMBERS_ROUTE : 'members';

$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;
$fellowship = getMemberFellowship($m['date_of_birth'] ?? null, $m['gender'] ?? null);
$age = getMemberAge($m['date_of_birth'] ?? null, $m['date_of_death'] ?? null);
$canHaveMinistries = canBelongToMinistry($m['date_of_birth'] ?? null);
$isChildMember = ($m['status'] ?? '') === 'child';

function v($val, $default = '—') {
    return $val !== null && $val !== '' ? htmlspecialchars($val) : $default;
}

$embed = isset($_GET['embed']) && $_GET['embed'] === '1';

if ($embed) {
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($name) ?> - Member</title>
    <base href="<?= htmlspecialchars(BASE_PATH . '/') ?>">
    <link rel="stylesheet" href="<?= htmlspecialchars(BASE_PATH) ?>/public/css/style.css">
    <style>
    /* YPG theme inside embed */
    :root, body { --primary: #f74652; --primary-light: #fa6b75; }
    body { margin: 0; padding: 1rem 1.25rem; background: #f8f8f7; font-size: 0.9375rem; }
    .member-view-wrapper { max-width: none; padding: 0; }
    .member-view-hero {
        margin-bottom: 1.5rem; padding-bottom: 1.5rem; border-bottom: 1px solid #e8e8e6;
        display: flex; align-items: center; gap: 1.25rem;
    }
    .member-view-photo-placeholder {
        width: 88px; height: 88px; border-radius: 50%;
        background: linear-gradient(145deg, #f74652 0%, #d93d48 100%);
        color: rgba(255,255,255,0.9); font-size: 2rem; font-weight: 600;
        display: flex; align-items: center; justify-content: center;
        flex-shrink: 0; border: none;
    }
    .member-view-name { font-size: 1.35rem; margin: 0 0 0.35rem; font-weight: 600; color: #1a1a1a; }
    .member-view-meta { font-size: 0.875rem; color: #555; margin: 0; }
    .member-view-meta span:not(:last-child)::after { content: ' · '; margin: 0 0.2rem; }
    .member-view-cards { display: flex; flex-direction: column; gap: 1rem; }
    .member-view-card {
        background: #fff; border-radius: 0; padding: 1.25rem 1.5rem;
        box-shadow: 0 1px 4px rgba(0,0,0,0.06); border-left: 4px solid #f74652;
    }
    .member-view-card-title {
        font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em;
        color: #555; margin: 0 0 0.75rem; padding-bottom: 0.5rem; border-bottom: 1px solid #eee;
    }
    .member-view-list li { padding: 0.4rem 0; border-bottom-color: #f0f0ef; }
    .member-view-label { color: #666; }
    </style>
</head>
<body class="theme-ypg">
    <div class="member-view-wrapper member-view-embed">
        <div class="member-view">
    <?php
} else {
    require_once __DIR__ . '/../../includes/header.php';
    ?>
<div class="member-view-wrapper">
    <div class="header">
        <h1>Member</h1>
        <div class="header-actions">
            <?php if (!isFinance() && !isVoting()): ?><a href="<?= nazareth_members_route('edit/' . (int) $m['id']) ?>" class="btn">Edit</a><?php endif; ?>
            <?php if (canDeleteMembers()): ?>
            <a href="<?= BASE_PATH ?>/members/delete/<?= (int) $m['id'] ?>"
               class="btn btn-secondary"
               style="color: #b91c1c; border-color: #fecaca;"
               data-confirm="Permanently delete “<?= htmlspecialchars(addslashes($name)) ?>”? This cannot be undone."
               data-confirm-btn="Delete permanently">Delete</a>
            <?php endif; ?>
            <a href="<?= nazareth_members_route() ?>" class="link-muted">← <?= $currentPage === 'collect' ? 'Directory' : 'Members' ?></a>
            <a href="<?= BASE_PATH ?>/logout">Logout</a>
        </div>
    </div>

    <div class="member-view">
    <?php
}
?>
    <div class="member-view-hero">
        <?php if ($photoUrl): ?>
            <img src="<?= $photoUrl ?>" alt="" class="member-view-photo" onclick="openImageModal('<?= htmlspecialchars($photoUrl, ENT_QUOTES) ?>', '<?= htmlspecialchars($name, ENT_QUOTES) ?>')" style="cursor: pointer;">
        <?php else: ?>
            <div class="member-view-photo-placeholder"></div>
        <?php endif; ?>
        <div class="member-view-hero-text">
            <h2 class="member-view-name">
                <?= htmlspecialchars($name) ?>
                <?php if (!empty($m['membership_number'])): ?>
                    <span style="font-size: 0.875rem; font-weight: normal; color: var(--text-muted, #6b7280); margin-left: 0.5rem;"><?= htmlspecialchars($m['membership_number']) ?></span>
                <?php endif; ?>
                <?php if (($m['status'] ?? '') === 'deceased' || !empty($m['date_of_death'])): ?>
                    <span style="color: #dc2626; font-size: 0.875rem; font-weight: normal; margin-left: 0.5rem;">(Deceased)</span>
                <?php endif; ?>
            </h2>
            <?php if (!isFinance() && !isVoting()): ?>
            <div class="member-view-meta">
                <?php if ($m['status'] ?? ''): ?>
                    <span<?= ($m['status'] ?? '') === 'deceased' ? ' style="color: #dc2626;"' : '' ?>><?= htmlspecialchars($m['status']) ?></span>
                <?php endif; ?>
                <?php if ($fellowship): ?><span><?= htmlspecialchars($fellowship) ?></span><?php endif; ?>
                <?php if (!empty($m['is_aged'])): ?><span>Aged</span><?php endif; ?>
                <?php if (!empty($m['is_invalid'])): ?><span>Invalid</span><?php endif; ?>
                <?php if ($age !== null && empty($m['date_of_death'])): ?><span><?= $age ?> years</span><?php endif; ?>
                <?php if (!empty($m['date_of_death'])): ?>
                    <?php
                    $deathAge = getMemberAge($m['date_of_birth'] ?? null, $m['date_of_death'] ?? null);
                    if ($deathAge !== null): ?>
                        <span style="color: #dc2626;">Died at <?= $deathAge ?> years</span>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="member-view-cards">
        <?php if (isFinance()): ?>
        <section class="member-view-card">
            <h3 class="member-view-card-title">Contact</h3>
            <ul class="member-view-list">
                <?php if ($m['phone'] ?? ''): ?><li><span class="member-view-label"><?= $isChildMember ? "Child's phone" : 'Phone' ?></span><?= htmlspecialchars($m['phone']) ?></li><?php endif; ?>
                <?php if ($m['email'] ?? ''): ?><li><span class="member-view-label"><?= $isChildMember ? "Child's email" : 'Email' ?></span><a href="mailto:<?= htmlspecialchars($m['email']) ?>"><?= htmlspecialchars($m['email']) ?></a></li><?php endif; ?>
            </ul>
            <?php if (empty($m['phone']) && empty($m['email'])): ?><p class="member-view-empty">No contact details</p><?php endif; ?>
        </section>
        <?php elseif (isVoting()): ?>
        <section class="member-view-card">
            <h3 class="member-view-card-title">Contact</h3>
            <ul class="member-view-list">
                <?php if ($m['phone'] ?? ''): ?><li><span class="member-view-label"><?= $isChildMember ? "Child's phone" : 'Phone' ?></span><?= htmlspecialchars($m['phone']) ?></li><?php endif; ?>
                <?php if ($m['email'] ?? ''): ?><li><span class="member-view-label"><?= $isChildMember ? "Child's email" : 'Email' ?></span><a href="mailto:<?= htmlspecialchars($m['email']) ?>"><?= htmlspecialchars($m['email']) ?></a></li><?php endif; ?>
            </ul>
            <?php if (empty($m['phone']) && empty($m['email'])): ?><p class="member-view-empty">No contact details</p><?php endif; ?>
        </section>
        <?php
        // Add "Add to Election" section for voting users
        require_once __DIR__ . '/../../includes/voting.php';
        if (isVotingEnabled()) {
            $activeElections = getAllElections('active');
            if (!empty($activeElections)):
        ?>
        <section class="member-view-card">
            <h3 class="member-view-card-title">Add to Election</h3>
            <ul class="member-view-list">
                <?php foreach ($activeElections as $election): ?>
                <li>
                    <a href="<?= BASE_PATH ?>/voting/manage/<?= $election['id'] ?>?add_member=<?= $m['id'] ?>" style="text-decoration: none; color: inherit;">
                        <?= htmlspecialchars($election['title']) ?> (<?= $election['type'] === 'fellowship' ? 'Group' : "Presbyters'" ?>)
                    </a>
                </li>
                <?php endforeach; ?>
            </ul>
        </section>
        <?php endif; } ?>
        <?php else: ?>
        <section class="member-view-card">
            <h3 class="member-view-card-title">About</h3>
            <ul class="member-view-list">
                <?php if ($m['gender'] ?? ''): ?><li><span class="member-view-label">Gender</span><?= htmlspecialchars($m['gender']) ?></li><?php endif; ?>
                <?php if ($m['date_of_birth'] ?? ''): ?><li><span class="member-view-label">Date of birth</span><?= date('F j, Y', strtotime($m['date_of_birth'])) ?></li><?php endif; ?>
                <?php if ($m['date_of_death'] ?? ''): ?><li><span class="member-view-label" style="color: #dc2626;">Date of death</span><span style="color: #dc2626; font-weight: 500;"><?= date('F j, Y', strtotime($m['date_of_death'])) ?></span></li><?php endif; ?>
                <?php if (!$isChildMember && ($m['marital_status'] ?? '')): ?><li><span class="member-view-label">Marital status</span><?= htmlspecialchars($m['marital_status']) ?></li><?php endif; ?>
                <?php if (!$isChildMember && ($m['occupation'] ?? '')): ?><li><span class="member-view-label">Occupation</span><?= htmlspecialchars($m['occupation']) ?></li><?php endif; ?>
            </ul>
        </section>

        <section class="member-view-card">
            <h3 class="member-view-card-title">Contact</h3>
            <ul class="member-view-list">
                <?php if ($m['phone'] ?? ''): ?><li><span class="member-view-label"><?= $isChildMember ? "Child's phone" : 'Phone' ?></span><?= htmlspecialchars($m['phone']) ?></li><?php endif; ?>
                <?php if ($m['email'] ?? ''): ?><li><span class="member-view-label"><?= $isChildMember ? "Child's email" : 'Email' ?></span><a href="mailto:<?= htmlspecialchars($m['email']) ?>"><?= htmlspecialchars($m['email']) ?></a></li><?php endif; ?>
                <?php if ($m['address'] ?? ''): ?><li><span class="member-view-label">Address</span><?= nl2br(htmlspecialchars($m['address'])) ?></li><?php endif; ?>
                <?php if ($m['ghana_post_address'] ?? ''): ?><li><span class="member-view-label">Ghana Post</span><?= htmlspecialchars($m['ghana_post_address']) ?></li><?php endif; ?>
                <?php if ($m['map_link'] ?? ''): ?><li><span class="member-view-label">Map</span><a href="<?= htmlspecialchars($m['map_link']) ?>" target="_blank" rel="noopener">View on Google Maps</a></li><?php endif; ?>
            </ul>
            <?php if (empty($m['phone']) && empty($m['email']) && empty($m['address']) && empty($m['ghana_post_address']) && empty($m['map_link'])): ?><p class="member-view-empty">No contact details</p><?php endif; ?>
        </section>

        <section class="member-view-card">
            <h3 class="member-view-card-title">Church</h3>
            <ul class="member-view-list">
                <?php if ($isChildMember): ?>
                    <li><span class="member-view-label">Service Groups</span><span class="text-muted">Not applicable — children do not belong to service groups.</span></li>
                <?php elseif ($canHaveMinistries): ?>
                    <?php if ($m['ministry_names'] ?? ''): ?><li><span class="member-view-label">Service Groups</span><?= htmlspecialchars($m['ministry_names']) ?></li><?php endif; ?>
                <?php else: ?>
                    <li><span class="member-view-label">Service Groups</span><span class="text-muted">Not applicable — children and junior youth do not belong to service groups (YPG and above only).</span></li>
                <?php endif; ?>
                <?php if ($m['household_name'] ?? ''): ?><li><span class="member-view-label">Household</span><?= htmlspecialchars($m['household_name']) ?></li><?php endif; ?>
                <?php if ($m['baptism_date'] ?? ''): ?><li><span class="member-view-label">Baptism date</span><?= date('F j, Y', strtotime($m['baptism_date'])) ?></li><?php endif; ?>
                <?php if (!$isChildMember && ($m['confirmation_date'] ?? '')): ?><li><span class="member-view-label">Confirmation date</span><?= date('F j, Y', strtotime($m['confirmation_date'])) ?></li><?php endif; ?>
            </ul>
        </section>

        <?php if (($m['emergency_contact'] ?? '') || ($m['emergency_phone'] ?? '')): ?>
        <section class="member-view-card">
            <h3 class="member-view-card-title"><?= $isChildMember ? 'Parent or caregiver' : 'Emergency contact' ?></h3>
            <ul class="member-view-list">
                <?php if ($m['emergency_contact'] ?? ''): ?><li><span class="member-view-label"><?= $isChildMember ? 'Parent / caregiver name' : 'Emergency contact (name)' ?></span><?= htmlspecialchars($m['emergency_contact']) ?></li><?php endif; ?>
                <?php if ($m['emergency_phone'] ?? ''): ?><li><span class="member-view-label"><?= $isChildMember ? 'Parent / caregiver phone' : 'Emergency contact (phone)' ?></span><?= htmlspecialchars($m['emergency_phone']) ?></li><?php endif; ?>
            </ul>
        </section>
        <?php endif; ?>

        <?php if (!empty($m['notes'])): ?>
        <section class="member-view-card">
            <h3 class="member-view-card-title">Notes</h3>
            <p class="member-view-notes"><?= nl2br(htmlspecialchars($m['notes'])) ?></p>
        </section>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>
</div>

<!-- Image Modal -->
<div id="image-modal" class="image-modal" role="dialog" aria-modal="true" aria-labelledby="image-modal-name" hidden>
    <div class="image-modal-backdrop" onclick="closeImageModal()"></div>
    <div class="image-modal-content">
        <div class="image-modal-header">
            <h2 id="image-modal-name" class="image-modal-title"></h2>
            <button type="button" class="image-modal-close" onclick="closeImageModal()" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="image-modal-body">
            <img id="image-modal-img" src="" alt="Member photo">
        </div>
    </div>
</div>

<script>
function openImageModal(imageUrl, memberName) {
    const modal = document.getElementById('image-modal');
    const img = document.getElementById('image-modal-img');
    const nameEl = document.getElementById('image-modal-name');
    img.src = imageUrl;
    nameEl.textContent = memberName;
    modal.hidden = false;
    document.body.style.overflow = 'hidden';
}

function closeImageModal() {
    const modal = document.getElementById('image-modal');
    modal.hidden = true;
    document.body.style.overflow = '';
}

// Close on Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const modal = document.getElementById('image-modal');
        if (!modal.hidden) {
            closeImageModal();
        }
    }
});
</script>
<?php if ($embed): ?>
</body>
</html>
<?php
    exit;
endif;
?>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
