<?php
/**
 * Member details (directory). Use header or bottom Edit to open the form.
 */
require_once __DIR__ . '/../includes/fellowships.php';

$uid = (int)currentUserId();
$mid = (int)$id;

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

$m = null;
try {
    $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([$mid]);
    $m = $stmt->fetch();
} catch (Throwable $e) {
    header('Location: ' . BASE_PATH . '/mobile?toast_error=' . urlencode('Could not load member.'));
    exit;
}

if (!$m) {
    header('Location: ' . BASE_PATH . '/mobile?toast_error=' . urlencode('Member not found.'));
    exit;
}

$isMine = isset($m['created_by']) && (int)$m['created_by'] === $uid;

$name = trim(implode(' ', array_filter([
    $m['title'] ?? '',
    $m['first_name'] ?? '',
    $m['middle_name'] ?? '',
    $m['last_name'] ?? '',
])));

$photoUrl = null;
if (!empty($m['photo'])) {
    $photoPath = __DIR__ . '/../public/uploads/members/' . $m['photo'];
    if (is_file($photoPath)) {
        $photoUrl = BASE_PATH . '/public/uploads/members/' . rawurlencode($m['photo']);
    }
}
$photoFallback = BASE_PATH . '/public/img/user.jpg';

$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);
$isDeceased = ($m['status'] ?? '') === 'deceased' || !empty($m['date_of_death']);
$isChildMember = ($m['status'] ?? '') === 'child';

function mobileFmtDate($d) {
    if (empty($d)) {
        return '';
    }
    $t = strtotime((string)$d);
    return $t ? date('M j, Y', $t) : (string)$d;
}

$pageTitle = 'Member';
$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 mobile-collect-topbar--view">
            <a href="<?= BASE_PATH ?>/mobile">← Directory</a>
            <h1>Details</h1>
            <?php if (!$isDeceased): ?>
                <a href="<?= BASE_PATH ?>/mobile/edit/<?= $mid ?>" class="mobile-collect-topbar-action">Edit</a>
            <?php else: ?>
                <span class="mobile-collect-topbar-spacer" aria-hidden="true"></span>
            <?php endif; ?>
        </header>
        <main class="mobile-collect-main">
            <div class="mobile-view-card">
                <div class="mobile-view-hero">
                    <div class="mobile-view-photo-wrap">
                        <img src="<?= htmlspecialchars($photoUrl ?: $photoFallback, ENT_QUOTES, 'UTF-8') ?>" alt="" class="mobile-view-photo-img" width="120" height="120" loading="lazy">
                    </div>
                    <div class="mobile-view-hero-text">
                        <h2 class="mobile-view-name"><?= htmlspecialchars($name ?: 'Member #' . $mid) ?></h2>
                        <?php if (!empty($m['membership_number'])): ?>
                            <p class="mobile-view-memno"><?= htmlspecialchars((string)$m['membership_number']) ?></p>
                        <?php endif; ?>
                        <div class="mobile-view-meta-row">
                            <?php if ($isMine): ?>
                                <span class="mobile-view-badge mobile-view-badge--mine">You added this</span>
                            <?php else: ?>
                                <span class="mobile-view-badge">Directory</span>
                            <?php endif; ?>
                            <?php if ($isDeceased): ?>
                                <span class="mobile-view-badge mobile-view-badge--deceased">Deceased</span>
                            <?php endif; ?>
                        </div>
                        <p class="mobile-view-tags">
                            <?php if (!empty($m['status']) && !$isDeceased): ?>
                                <span><?= htmlspecialchars((string)$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 && !$isDeceased): ?>
                                <span><?= (int)$age ?> yrs</span>
                            <?php endif; ?>
                        </p>
                    </div>
                </div>

                <div class="mobile-view-sections">
                    <section class="mobile-view-block">
                        <h3 class="mobile-view-block-title">Personal</h3>
                        <dl class="mobile-view-dl">
                            <dt>Gender</dt>
                            <dd><?= htmlspecialchars(mobileViewVal($m['gender'] ?? null)) ?></dd>
                            <dt>Date of birth</dt>
                            <dd><?= $m['date_of_birth'] ? htmlspecialchars(mobileFmtDate($m['date_of_birth'])) : '—' ?></dd>
                            <?php if ($isDeceased && !empty($m['date_of_death'])): ?>
                                <dt>Date of death</dt>
                                <dd class="mobile-view-dd-warn"><?= htmlspecialchars(mobileFmtDate($m['date_of_death'])) ?></dd>
                            <?php endif; ?>
                            <?php if (!$isChildMember): ?>
                            <dt>Marital status</dt>
                            <dd><?= htmlspecialchars(mobileViewVal($m['marital_status'] ?? null)) ?></dd>
                            <dt>Occupation</dt>
                            <dd><?= htmlspecialchars(mobileViewVal($m['occupation'] ?? null)) ?></dd>
                            <?php endif; ?>
                            <?php if (!empty($m['join_date'])): ?>
                                <dt>Join date</dt>
                                <dd><?= htmlspecialchars(mobileFmtDate($m['join_date'])) ?></dd>
                            <?php endif; ?>
                        </dl>
                    </section>

                    <section class="mobile-view-block">
                        <h3 class="mobile-view-block-title">Contact &amp; location</h3>
                        <dl class="mobile-view-dl">
                            <dt><?= $isChildMember ? "Child's phone" : 'Phone' ?></dt>
                            <dd>
                                <?php if (!empty(trim((string)($m['phone'] ?? '')))): ?>
                                    <a href="tel:<?= htmlspecialchars(preg_replace('/\s+/', '', (string)$m['phone'])) ?>"><?= htmlspecialchars((string)$m['phone']) ?></a>
                                <?php else: ?>—<?php endif; ?>
                            </dd>
                            <dt><?= $isChildMember ? "Child's email" : 'Email' ?></dt>
                            <dd>
                                <?php if (!empty(trim((string)($m['email'] ?? '')))): ?>
                                    <a href="mailto:<?= htmlspecialchars((string)$m['email']) ?>"><?= htmlspecialchars((string)$m['email']) ?></a>
                                <?php else: ?>—<?php endif; ?>
                            </dd>
                            <dt>Address</dt>
                            <dd><?= !empty(trim((string)($m['address'] ?? ''))) ? nl2br(htmlspecialchars((string)$m['address'])) : '—' ?></dd>
                            <dt>Ghana Post</dt>
                            <dd><?= htmlspecialchars(mobileViewVal($m['ghana_post_address'] ?? null)) ?></dd>
                            <dt>Map</dt>
                            <dd>
                                <?php if (!empty(trim((string)($m['map_link'] ?? '')))): ?>
                                    <a href="<?= htmlspecialchars((string)$m['map_link']) ?>" target="_blank" rel="noopener noreferrer">Open in maps</a>
                                <?php else: ?>—<?php endif; ?>
                            </dd>
                        </dl>
                    </section>

                    <section class="mobile-view-block">
                        <h3 class="mobile-view-block-title">Church</h3>
                        <dl class="mobile-view-dl">
                            <dt>Service groups</dt>
                            <dd>
                                <?php if ($isChildMember): ?>
                                    <span class="mobile-view-muted">Not applicable (children)</span>
                                <?php elseif ($canHaveMinistries): ?>
                                    <?= !empty($m['ministry_names']) ? htmlspecialchars((string)$m['ministry_names']) : '—' ?>
                                <?php else: ?>
                                    <span class="mobile-view-muted">Not applicable (junior youth)</span>
                                <?php endif; ?>
                            </dd>
                            <dt>Household</dt>
                            <dd><?= htmlspecialchars(mobileViewVal($m['household_name'] ?? null)) ?></dd>
                            <dt>Baptism</dt>
                            <dd><?= !empty($m['baptism_date']) ? htmlspecialchars(mobileFmtDate($m['baptism_date'])) : '—' ?></dd>
                            <?php if (!$isChildMember): ?>
                            <dt>Confirmation</dt>
                            <dd><?= !empty($m['confirmation_date']) ? htmlspecialchars(mobileFmtDate($m['confirmation_date'])) : '—' ?></dd>
                            <?php endif; ?>
                        </dl>
                    </section>

                    <?php if (!empty($m['emergency_contact']) || !empty($m['emergency_phone'])): ?>
                    <section class="mobile-view-block">
                        <h3 class="mobile-view-block-title"><?= $isChildMember ? 'Parent / caregiver' : 'Emergency' ?></h3>
                        <dl class="mobile-view-dl">
                            <dt><?= $isChildMember ? 'Parent / caregiver name' : 'Emergency contact (name)' ?></dt>
                            <dd><?= htmlspecialchars(mobileViewVal($m['emergency_contact'] ?? null)) ?></dd>
                            <dt><?= $isChildMember ? 'Parent / caregiver phone' : 'Emergency contact (phone)' ?></dt>
                            <dd>
                                <?php if (!empty(trim((string)($m['emergency_phone'] ?? '')))): ?>
                                    <a href="tel:<?= htmlspecialchars(preg_replace('/\s+/', '', (string)$m['emergency_phone'])) ?>"><?= htmlspecialchars((string)$m['emergency_phone']) ?></a>
                                <?php else: ?>—<?php endif; ?>
                            </dd>
                        </dl>
                    </section>
                    <?php endif; ?>

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

                <?php if (!$isDeceased): ?>
                    <a class="btn mobile-collect-btn mobile-view-edit-btn" href="<?= BASE_PATH ?>/mobile/edit/<?= $mid ?>">Edit member record</a>
                <?php else: ?>
                    <p class="mobile-view-note">Deceased records cannot be edited in the field app.</p>
                <?php endif; ?>
            </div>
        </main>
    </div>
    <?php nazareth_mobile_pwa_scripts(); ?>
</body>
</html>
