<?php
/**
 * Add / edit member — mobile data collection (any active member).
 * Expects $isEdit (bool) and $id (int|null) set by app.php.
 */
require_once __DIR__ . '/init.php';
require_once __DIR__ . '/../includes/ministries.php';
require_once __DIR__ . '/../includes/fellowships.php';
require_once __DIR__ . '/../includes/member-validation.php';
require_once __DIR__ . '/../includes/member-titles.php';
require_once __DIR__ . '/../includes/audit-entities.php';

$uid = (int)currentUserId();
$member = null;
$errors = [];
$isDeparted = false;

try {
    $pdo->exec('ALTER TABLE members ADD COLUMN confirmation_date DATE NULL DEFAULT NULL AFTER baptism_date');
} catch (Throwable $e) {
    // ignore
}

if ($isEdit) {
    $stmt = $pdo->prepare('SELECT * FROM members WHERE id = ?');
    $stmt->execute([(int)$id]);
    $member = $stmt->fetch();
    if (!$member) {
        header('Location: ' . BASE_PATH . '/mobile?toast_error=' . urlencode('Member not found.'));
        exit;
    }
    $isDeparted = ($member['status'] ?? '') === 'deceased' || !empty($member['date_of_death']);
    if ($isDeparted) {
        header('Location: ' . BASE_PATH . '/mobile?toast_error=' . urlencode('This record cannot be edited here.'));
        exit;
    }
}

$households = $pdo->query('SELECT id, name FROM households ORDER BY name')->fetchAll();
$allMinistries = $pdo->query('SELECT id, name FROM ministries ORDER BY name')->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '') ?: null;
    $first_name = trim($_POST['first_name'] ?? '');
    $middle_name = trim($_POST['middle_name'] ?? '') ?: null;
    $last_name = trim($_POST['last_name'] ?? '');
    $gender = trim($_POST['gender'] ?? '') ?: null;
    $date_of_birth = trim($_POST['date_of_birth'] ?? '') ?: null;
    $phone = trim($_POST['phone'] ?? '') ?: null;
    $email = trim($_POST['email'] ?? '') ?: null;
    $marital_status = trim($_POST['marital_status'] ?? '') ?: null;
    $occupation = trim($_POST['occupation'] ?? '') ?: null;
    $status = trim($_POST['status'] ?? 'communicant');
    $baptism_date = trim($_POST['baptism_date'] ?? '') ?: null;
    $confirmation_date = trim($_POST['confirmation_date'] ?? '') ?: null;
    $address = trim($_POST['address'] ?? '') ?: null;
    $ghana_post_address = trim($_POST['ghana_post_address'] ?? '') ?: null;
    $map_link = trim($_POST['map_link'] ?? '') ?: null;
    $emergency_contact = trim($_POST['emergency_contact'] ?? '') ?: null;
    $emergency_phone = trim($_POST['emergency_phone'] ?? '') ?: null;
    $notes = trim($_POST['notes'] ?? '') ?: null;
    $household_id = !empty($_POST['household_id']) ? (int)$_POST['household_id'] : null;
    $special_group = trim($_POST['special_group'] ?? '');
    $is_aged = ($special_group === 'aged');
    $is_invalid = ($special_group === 'invalid');
    $membership_number = trim($_POST['membership_number'] ?? '');
    $membership_number = $membership_number === '' ? null : $membership_number;
    $ministry_ids = isset($_POST['ministry_ids']) && is_array($_POST['ministry_ids'])
        ? array_map('intval', array_filter($_POST['ministry_ids'])) : [];

    $dobForMinistry = $date_of_birth ?: ($member['date_of_birth'] ?? null);
    if (!canBelongToMinistry($dobForMinistry) || $status === 'child') {
        $ministry_ids = [];
    }
    if ($status === 'child') {
        $confirmation_date = null;
    }

    if (empty($first_name)) {
        $errors[] = 'First name is required.';
    }
    if (empty($last_name)) {
        $errors[] = 'Last name is required.';
    }

    if ($membership_number !== null) {
        $exists = $pdo->prepare('SELECT id FROM members WHERE membership_number = ? AND id != ?');
        $exists->execute([$membership_number, $isEdit ? (int)$id : 0]);
        if ($exists->fetch()) {
            $errors[] = 'This membership number is already assigned to another member.';
        }
    }

    $errors = array_merge($errors, validateMemberDates($date_of_birth, $baptism_date, null, $confirmation_date));

    if ($isEdit && $isDeparted && $status !== 'deceased') {
        $status = 'deceased';
    }

    if (empty($errors)) {
        $cols = 'membership_number, title, first_name, middle_name, last_name, gender, date_of_birth, phone, email, marital_status, occupation, status, baptism_date, confirmation_date, address, ghana_post_address, map_link, emergency_contact, emergency_phone, notes, is_aged, is_invalid, household_id';
        $baseVals = [$membership_number, $title, $first_name, $middle_name, $last_name, $gender, $date_of_birth, $phone, $email, $marital_status, $occupation, $status, $baptism_date, $confirmation_date, $address, $ghana_post_address, $map_link, $emergency_contact, $emergency_phone, $notes, $is_aged ? 1 : 0, $is_invalid ? 1 : 0, $household_id];

        if ($isEdit) {
            $parts = array_map('trim', explode(',', $cols));
            $setSql = implode('=?, ', $parts) . '=?, updated_by=?';
            $sql = "UPDATE members SET {$setSql} WHERE id=?";
            $vals = array_merge($baseVals, [$uid, (int)$id]);
            $stmt = $pdo->prepare($sql);
            $stmt->execute($vals);
            $verify = $pdo->prepare('SELECT id FROM members WHERE id = ?');
            $verify->execute([(int)$id]);
            if (!$verify->fetch()) {
                header('Location: ' . BASE_PATH . '/mobile?toast_error=' . urlencode('Could not update — member not found.'));
                exit;
            }
        } else {
            $fullCols = $cols . ', created_by, updated_by';
            $placeholders = implode(', ', array_fill(0, 25, '?'));
            $vals = array_merge($baseVals, [$uid, $uid]);
            $stmt = $pdo->prepare("INSERT INTO members ($fullCols) VALUES ($placeholders)");
            $stmt->execute($vals);
            $id = (int)$pdo->lastInsertId();
        }

        $oldServiceGroups = nazarethMemberServiceGroupLabels($pdo, $id);
        $pdo->prepare('DELETE FROM member_ministries WHERE member_id = ?')->execute([$id]);
        if (!empty($ministry_ids)) {
            $ins = $pdo->prepare('INSERT INTO member_ministries (member_id, ministry_id) VALUES (?, ?)');
            foreach ($ministry_ids as $mid) {
                if ($mid > 0) {
                    $ins->execute([$id, $mid]);
                }
            }
        }

        $uploadDir = __DIR__ . '/../public/uploads/members';
        if (!is_dir($uploadDir)) {
            @mkdir($uploadDir, 0755, true);
        }
        $removePhoto = !empty($_POST['remove_photo']);
        if ($isEdit && $removePhoto && !empty($member['photo'])) {
            $oldPath = $uploadDir . '/' . $member['photo'];
            if (file_exists($oldPath)) {
                @unlink($oldPath);
            }
            $pdo->prepare('UPDATE members SET photo = NULL WHERE id = ?')->execute([$id]);
        }
        $finfo = $_FILES['photo'] ?? null;
        if ($finfo && isset($finfo['error']) && $finfo['error'] === UPLOAD_ERR_OK && is_uploaded_file($finfo['tmp_name'])) {
            $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp'];
            $type = $finfo['type'] ?? '';
            if (isset($allowed[$type]) && $finfo['size'] <= 2 * 1024 * 1024) {
                $ext = $allowed[$type];
                $filename = $id . '.' . $ext;
                $path = $uploadDir . '/' . $filename;
                if ($isEdit && !empty($member['photo']) && $member['photo'] !== $filename) {
                    $oldPath = $uploadDir . '/' . $member['photo'];
                    if (file_exists($oldPath)) {
                        @unlink($oldPath);
                    }
                }
                if (move_uploaded_file($finfo['tmp_name'], $path)) {
                    $pdo->prepare('UPDATE members SET photo = ? WHERE id = ?')->execute([$filename, $id]);
                }
            }
        }

        if ($isEdit) {
            nazarethTryLogMemberUpdated($pdo, $uid, $id, $member, $oldServiceGroups, 'mobile');
        } else {
            nazarethTryLogMemberCreated($pdo, $uid, $id, 'mobile');
        }

        header('Location: ' . BASE_PATH . '/mobile?toast=' . urlencode('Saved successfully.'));
        exit;
    }

    $member = array_merge(
        compact('title', 'first_name', 'middle_name', 'last_name', 'gender', 'date_of_birth', 'phone', 'email', 'marital_status', 'occupation', 'status', 'baptism_date', 'confirmation_date', 'address', 'ghana_post_address', 'map_link', 'emergency_contact', 'emergency_phone', 'notes', 'household_id'),
        ['membership_number' => $membership_number, 'is_aged' => $is_aged ? 1 : 0, 'is_invalid' => $is_invalid ? 1 : 0]
    );
    $member['ministry_ids'] = $ministry_ids;
} elseif ($isEdit && $member) {
    $member['ministry_ids'] = getMemberMinistriesIds((int)$id);
}

$pageTitle = $isEdit ? 'Edit member' : 'New member';
$mRow = $member ?? [];
$sel_special = isset($_POST['special_group'])
    ? trim((string)$_POST['special_group'])
    : (isset($mRow['is_aged']) && !empty($mRow['is_aged']) ? 'aged' : (isset($mRow['is_invalid']) && !empty($mRow['is_invalid']) ? 'invalid' : ''));
$eligibleByAgeForMinistries = canBelongToMinistry($mRow['date_of_birth'] ?? null);
$isChildStatusForm = (($mRow['status'] ?? '') === 'child');
$canHaveMinistries = $eligibleByAgeForMinistries;
$ids = $mRow['ministry_ids'] ?? ($isEdit ? getMemberMinistriesIds((int)$id) : []);
$initialMinistries = [];
foreach ($allMinistries as $m) {
    if (in_array((int)$m['id'], $ids, true)) {
        $initialMinistries[] = ['id' => (int)$m['id'], 'name' => $m['name']];
    }
}

$member = $mRow;

$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 mobile-collect-form-page">
    <div class="mobile-collect-shell">
        <header class="mobile-collect-topbar">
            <a href="<?= BASE_PATH ?>/mobile">← Back</a>
            <h1><?= $isEdit ? 'Edit member' : 'New member' ?></h1>
            <span style="width:3rem"></span>
        </header>
        <main class="mobile-collect-main">
            <?php if (!empty($errors)): ?>
                <div class="mobile-collect-alert" style="margin-bottom:1rem;"><?= htmlspecialchars(implode(' ', $errors)) ?></div>
            <?php endif; ?>

            <div class="form-card mobile-form-card">
                <form method="post" class="member-form mobile-member-form" enctype="multipart/form-data">
                    <p class="mobile-form-required-hint"><span class="mobile-req-star">*</span> Required fields</p>

                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title">Photo</h2>
                    <div class="form-group">
                        <label class="sr-only" for="member_photo_input">Member photo</label>
                        <?php
                        $photoUrl = null;
                        if ($isEdit && !empty($member['photo'])) {
                            $photoPath = __DIR__ . '/../public/uploads/members/' . $member['photo'];
                            if (file_exists($photoPath)) {
                                $photoUrl = BASE_PATH . '/public/uploads/members/' . htmlspecialchars($member['photo']);
                            }
                        }
                        ?>
                        <div class="member-photo-upload">
                            <label for="member_photo_input" class="member-photo-placeholder" id="member_photo_placeholder">
                                <?php if ($photoUrl): ?>
                                    <img src="<?= $photoUrl ?>" alt="" class="member-photo-existing">
                                    <span class="member-photo-placeholder-text">Tap to change</span>
                                <?php else: ?>
                                    <img src="<?= BASE_PATH ?>/public/img/user.jpg" alt="" class="member-photo-default">
                                    <span class="member-photo-placeholder-text">Tap to add photo</span>
                                <?php endif; ?>
                            </label>
                            <input type="file" id="member_photo_input" name="photo" accept="image/jpeg,image/png,image/gif,image/webp" class="member-photo-input">
                            <img src="" alt="" class="member-photo-preview" id="member_photo_preview" style="display:none;">
                        </div>
                        <?php if ($photoUrl): ?>
                            <label class="checkbox-row" style="display:inline-flex;align-items:center;gap:0.35rem;margin-top:0.5rem;">
                                <input type="checkbox" name="remove_photo" value="1"> Remove photo
                            </label>
                        <?php endif; ?>
                    </div>
                    </div>

                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title">Membership</h2>
                    <div class="form-group">
                        <label for="membership_number">Membership number <span class="mobile-label-opt">(optional)</span></label>
                        <input type="text" id="membership_number" name="membership_number" maxlength="50" inputmode="text" autocomplete="off"
                            value="<?= htmlspecialchars(isset($_POST['membership_number']) ? trim((string)$_POST['membership_number']) : (string)($member['membership_number'] ?? '')) ?>"
                            placeholder="e.g. YMC125">
                    </div>
                    <div class="form-group">
                        <label for="special_group">Aged / Invalids <span class="mobile-label-opt">(optional)</span></label>
                        <select id="special_group" name="special_group" aria-describedby="special_group_hint">
                            <option value="" <?= $sel_special === '' ? 'selected' : '' ?>>Not applicable</option>
                            <option value="aged" <?= $sel_special === 'aged' ? 'selected' : '' ?>>Aged</option>
                            <option value="invalid" <?= $sel_special === 'invalid' ? 'selected' : '' ?>>Invalid</option>
                        </select>
                        <p class="mobile-field-hint" id="special_group_hint">Only if this person is tracked under Aged &amp; Invalids care.</p>
                    </div>
                    </div>

                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title">Name &amp; details</h2>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="title">Title</label>
                            <select id="title" name="title">
                                <option value="">—</option>
                                <?php foreach (nazareth_member_title_options() as $t): ?>
                                    <option value="<?= $t ?>" <?= ($member['title'] ?? '') === $t ? 'selected' : '' ?>><?= $t ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="first_name">First name <span class="mobile-req-star">*</span></label>
                            <input type="text" id="first_name" name="first_name" required value="<?= htmlspecialchars($member['first_name'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="middle_name">Middle name</label>
                            <input type="text" id="middle_name" name="middle_name" value="<?= htmlspecialchars($member['middle_name'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label for="last_name">Last name <span class="mobile-req-star">*</span></label>
                            <input type="text" id="last_name" name="last_name" required value="<?= htmlspecialchars($member['last_name'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="gender">Gender</label>
                            <select id="gender" name="gender">
                                <option value="">—</option>
                                <option value="Male" <?= ($member['gender'] ?? '') === 'Male' ? 'selected' : '' ?>>Male</option>
                                <option value="Female" <?= ($member['gender'] ?? '') === 'Female' ? 'selected' : '' ?>>Female</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="date_of_birth">Date of birth</label>
                            <input type="date" id="date_of_birth" name="date_of_birth" value="<?= htmlspecialchars($member['date_of_birth'] ?? '') ?>">
                        </div>
                    </div>
                    </div>

                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title">Contact</h2>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="phone" id="member_label_phone">Phone</label>
                            <input type="tel" id="phone" name="phone" inputmode="tel" autocomplete="tel" placeholder="e.g. 0244 000 000"
                                value="<?= htmlspecialchars($member['phone'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label for="email" id="member_label_email">Email</label>
                            <input type="email" id="email" name="email" inputmode="email" autocomplete="email" placeholder="name@example.com"
                                value="<?= htmlspecialchars($member['email'] ?? '') ?>">
                        </div>
                    </div>
                    </div>

                    <div class="mobile-form-section" id="member_row_marital_section">
                        <h2 class="mobile-form-section-title">More about them</h2>
                    <div class="form-row" id="member_row_marital_occupation">
                        <div class="form-group">
                            <label for="marital_status">Marital status</label>
                            <select id="marital_status" name="marital_status">
                                <option value="">—</option>
                                <?php foreach (['Single', 'Married', 'Widowed', 'Divorced'] as $ms): ?>
                                    <option value="<?= $ms ?>" <?= ($member['marital_status'] ?? '') === $ms ? 'selected' : '' ?>><?= $ms ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="occupation">Occupation</label>
                            <input type="text" id="occupation" name="occupation" value="<?= htmlspecialchars($member['occupation'] ?? '') ?>">
                        </div>
                    </div>
                    </div>

                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title">Church</h2>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="status">Status</label>
                            <select id="status" name="status">
                                <option value="communicant" <?= ($member['status'] ?? '') === 'communicant' ? 'selected' : '' ?>>Communicant</option>
                                <option value="adherent" <?= ($member['status'] ?? '') === 'adherent' ? 'selected' : '' ?>>Adherent</option>
                                <option value="youth" <?= ($member['status'] ?? '') === 'youth' ? 'selected' : '' ?>>Youth</option>
                                <option value="child" <?= ($member['status'] ?? '') === 'child' ? 'selected' : '' ?>>Child</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="baptism_date">Baptism date</label>
                            <input type="date" id="baptism_date" name="baptism_date" value="<?= htmlspecialchars($member['baptism_date'] ?? '') ?>">
                        </div>
                        <div class="form-group" id="member_group_confirmation_date"<?= $isChildStatusForm ? ' style="display: none;"' : '' ?>>
                            <label for="confirmation_date">Confirmation date</label>
                            <input type="date" id="confirmation_date" name="confirmation_date" value="<?= htmlspecialchars($member['confirmation_date'] ?? '') ?>">
                        </div>
                    </div>
                    </div>

                    <?php if ($eligibleByAgeForMinistries): ?>
                    <div class="mobile-form-section" id="member_mobile_ministry_section"<?= $isChildStatusForm ? ' style="display: none;"' : '' ?>>
                        <h2 class="mobile-form-section-title">Service groups</h2>
                    <div class="form-group">
                        <label for="ministry_select">Add a service group</label>
                        <div class="ministry-add-row mobile-ministry-row">
                            <select id="ministry_select">
                                <option value="">Choose a group…</option>
                                <?php foreach ($allMinistries as $min): ?>
                                    <option value="<?= (int)$min['id'] ?>"><?= htmlspecialchars($min['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <button type="button" id="ministry_add_btn" class="btn btn-sm">Add</button>
                        </div>
                        <div id="ministry_selected" class="ministry-tags" style="margin-top:0.5rem;min-height:1.5rem;"></div>
                        <div id="ministry_inputs"></div>
                    </div>
                    </div>
                    <?php elseif (!$isChildStatusForm): ?>
                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title">Service groups</h2>
                        <p class="mobile-view-muted" style="margin:0;font-size:0.875rem;">Children's Service and Junior Youth do not use service groups (YPG and above only).</p>
                    </div>
                    <?php endif; ?>

                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title">Household</h2>
                    <div class="form-group">
                        <label for="household_id">Household</label>
                        <select id="household_id" name="household_id">
                            <option value="">None</option>
                            <?php foreach ($households as $h): ?>
                                <option value="<?= (int)$h['id'] ?>" <?= (string)($member['household_id'] ?? '') === (string)$h['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($h['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p id="member_child_household_hint" class="mobile-view-muted" style="display: none; margin: 0.35rem 0 0; font-size: 0.8125rem;">Link this child to their family household so they appear with parents and siblings.</p>
                    </div>
                    </div>

                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title">Address &amp; location</h2>
                    <div class="form-group">
                        <label for="address">Address</label>
                        <textarea id="address" name="address" rows="2"><?= htmlspecialchars($member['address'] ?? '') ?></textarea>
                    </div>
                    <div class="form-group">
                        <label for="ghana_post_address">Ghana Post address</label>
                        <input type="text" id="ghana_post_address" name="ghana_post_address" value="<?= htmlspecialchars($member['ghana_post_address'] ?? '') ?>">
                    </div>
                    <div class="form-group">
                        <label for="map_link">Map link</label>
                        <input type="url" id="map_link" name="map_link" value="<?= htmlspecialchars($member['map_link'] ?? '') ?>">
                    </div>
                    </div>

                    <div class="mobile-form-section">
                        <h2 class="mobile-form-section-title" id="member_mobile_emergency_section_title">Emergency</h2>
                    <div class="form-row">
                        <div class="form-group">
                            <label for="emergency_contact" id="member_label_emergency_contact">Emergency contact (name)</label>
                            <input type="text" id="emergency_contact" name="emergency_contact" placeholder="Full name" value="<?= htmlspecialchars($member['emergency_contact'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label for="emergency_phone" id="member_label_emergency_phone">Emergency contact (phone)</label>
                            <input type="text" id="emergency_phone" name="emergency_phone" value="<?= htmlspecialchars($member['emergency_phone'] ?? '') ?>">
                        </div>
                    </div>
                    </div>

                    <div class="mobile-form-section mobile-form-section--flush">
                        <h2 class="mobile-form-section-title">Notes</h2>
                    <div class="form-group">
                        <label for="notes">Notes</label>
                        <textarea id="notes" name="notes" rows="3"><?= htmlspecialchars($member['notes'] ?? '') ?></textarea>
                    </div>
                    </div>

                    <div class="mobile-collect-form-actions">
                        <button type="submit" class="btn mobile-collect-btn" style="margin:0;"><?= $isEdit ? 'Save changes' : 'Save member' ?></button>
                        <a href="<?= BASE_PATH ?>/mobile" class="btn btn-ghost">Cancel</a>
                    </div>
                </form>
            </div>
        </main>
    </div>

<?php if ($canHaveMinistries): ?>
<script>
(function() {
    var ministries = <?= json_encode(array_column($allMinistries, 'name', 'id')) ?>;
    var selected = <?= json_encode($initialMinistries) ?>;
    var container = document.getElementById('ministry_selected');
    var inputsContainer = document.getElementById('ministry_inputs');
    if (!container || !inputsContainer) return;

    function render() {
        container.innerHTML = '';
        inputsContainer.innerHTML = '';
        selected.forEach(function(s) {
            var tag = document.createElement('span');
            tag.className = 'ministry-tag';
            tag.style.cssText = 'display:inline-flex;align-items:center;gap:0.25rem;background:#e2e8f0;padding:0.2rem 0.5rem;border-radius:4px;font-size:0.875rem;margin:0 0.35rem 0.35rem 0;';
            tag.innerHTML = s.name + ' <button type="button" class="remove-ministry" data-id="' + s.id + '" style="background:none;border:none;cursor:pointer">&times;</button>';
            container.appendChild(tag);
            var inp = document.createElement('input');
            inp.type = 'hidden';
            inp.name = 'ministry_ids[]';
            inp.value = s.id;
            inputsContainer.appendChild(inp);
        });
        container.querySelectorAll('.remove-ministry').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var rid = parseInt(this.getAttribute('data-id'), 10);
                selected = selected.filter(function(s) { return s.id !== rid; });
                render();
            });
        });
    }
    var addBtn = document.getElementById('ministry_add_btn');
    var sel = document.getElementById('ministry_select');
    if (addBtn && sel) {
        addBtn.addEventListener('click', function() {
            var id = sel.value ? parseInt(sel.value, 10) : 0;
            if (!id) return;
            if (selected.some(function(s) { return s.id === id; })) return;
            selected.push({ id: id, name: ministries[id] || sel.options[sel.selectedIndex].text });
            render();
            sel.selectedIndex = 0;
        });
    }
    render();
})();
</script>
<?php endif; ?>
<script>
(function() {
    var input = document.getElementById('member_photo_input');
    var preview = document.getElementById('member_photo_preview');
    var placeholder = document.getElementById('member_photo_placeholder');
    if (!input || !preview) return;
    input.addEventListener('change', function() {
        var file = this.files && this.files[0];
        if (file && file.type.indexOf('image/') === 0) {
            preview.src = URL.createObjectURL(file);
            preview.style.display = 'block';
            if (placeholder) placeholder.style.visibility = 'hidden';
        } else {
            preview.style.display = 'none';
            preview.src = '';
            if (placeholder) placeholder.style.visibility = '';
        }
    });
})();
</script>
<script>
(function() {
    var form = document.querySelector('form.member-form');
    var statusEl = document.getElementById('status');
    if (!form || !statusEl) return;

    var labelPhone = document.getElementById('member_label_phone');
    var labelEmail = document.getElementById('member_label_email');
    var labelEmergName = document.getElementById('member_label_emergency_contact');
    var labelEmergPhone = document.getElementById('member_label_emergency_phone');
    var sectionMarital = document.getElementById('member_row_marital_section');
    var hintHousehold = document.getElementById('member_child_household_hint');
    var emergTitle = document.getElementById('member_mobile_emergency_section_title');
    var groupConfirmation = document.getElementById('member_group_confirmation_date');
    var confirmationInput = document.getElementById('confirmation_date');
    var ministrySection = document.getElementById('member_mobile_ministry_section');

    var text = {
        phone: { adult: 'Phone', child: "Child's phone (if any)" },
        email: { adult: 'Email', child: "Child's email (if any)" },
        emergName: { adult: 'Emergency contact (name)', child: 'Parent or caregiver name' },
        emergPhone: { adult: 'Emergency contact (phone)', child: 'Parent or caregiver phone' },
        emergSection: { adult: 'Emergency', child: 'Parent / caregiver' }
    };

    function sync() {
        var child = statusEl.value === 'child';
        form.classList.toggle('member-form--child', child);
        if (labelPhone) labelPhone.textContent = child ? text.phone.child : text.phone.adult;
        if (labelEmail) labelEmail.textContent = child ? text.email.child : text.email.adult;
        if (labelEmergName) labelEmergName.textContent = child ? text.emergName.child : text.emergName.adult;
        if (labelEmergPhone) labelEmergPhone.textContent = child ? text.emergPhone.child : text.emergPhone.adult;
        if (sectionMarital) sectionMarital.style.display = child ? 'none' : '';
        if (hintHousehold) hintHousehold.style.display = child ? 'block' : 'none';
        if (emergTitle) emergTitle.textContent = child ? text.emergSection.child : text.emergSection.adult;
        if (groupConfirmation) groupConfirmation.style.display = child ? 'none' : '';
        if (child && confirmationInput) confirmationInput.value = '';
        if (ministrySection) ministrySection.style.display = child ? 'none' : '';
    }

    statusEl.addEventListener('change', sync);
    sync();
})();
</script>
<?php nazareth_mobile_pwa_scripts(); ?>
</body>
</html>
