<?php
/**
 * Member add/edit form
 */

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/collect-routing.php';

if (isFinance() || isVoting()) {
    header('Location: ' . nazareth_members_route());
    exit;
}

$isEdit = ($action === 'edit' && $id);
$member = null;
$errors = [];
$isDeparted = false;

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

// Ensure confirmation_date column exists (migration)
try {
    $pdo->exec('ALTER TABLE members ADD COLUMN confirmation_date DATE NULL DEFAULT NULL AFTER baptism_date');
} catch (Exception $e) {
    // Column may already exist; ignore
}

require_once __DIR__ . '/../../includes/members_audit_columns.php';
require_once __DIR__ . '/../../includes/audit-entities.php';
ensureMembersAuditColumns($pdo);

// Get households for dropdown
$households = $pdo->query('SELECT id, name FROM households ORDER BY name')->fetchAll();
// Get ministries for checkboxes
$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'])) : [];

    // Only YPG and above (18+) can belong to ministries; status "child" never has service groups
    $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.';

    // Membership number: optional; must be unique if provided
    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. Choose a different one.';
        }
    }

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

    // Prevent changing status away from deceased if member is departed
    if ($isEdit && $isDeparted && $status !== 'deceased') {
        $status = 'deceased'; // Force keep as 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';
        $auditUid = currentUserId() ? (int)currentUserId() : null;
        $vals = [$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=?';
            $stmt = $pdo->prepare("UPDATE members SET {$setSql} WHERE id=?");
            $updVals = array_merge($vals, [$auditUid, $id]);
            $stmt->execute($updVals);
        } else {
            $fullCols = $cols . ', created_by, updated_by';
            $placeholders = implode(', ', array_fill(0, 25, '?'));
            $stmt = $pdo->prepare("INSERT INTO members ($fullCols) VALUES ($placeholders)");
            $stmt->execute(array_merge($vals, [$auditUid, $auditUid]));
            $id = (int)$pdo->lastInsertId();
        }
        $oldServiceGroups = nazarethMemberServiceGroupLabels($pdo, $id);
        // Update member ministries
        $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]);
            }
        }

        // Photo upload
        $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) {
                // skip invalid or > 2MB
            } else {
                $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]);
                }
            }
        }

        $auditSource = (defined('NAZARETH_MEMBERS_ROUTE') && NAZARETH_MEMBERS_ROUTE === 'collect') ? 'collect' : 'desktop';
        if ($isEdit) {
            nazarethTryLogMemberUpdated($pdo, $auditUid, $id, $member, $oldServiceGroups, $auditSource);
        } else {
            nazarethTryLogMemberCreated($pdo, $auditUid, $id, $auditSource);
        }

        header('Location: ' . nazareth_members_route() . '?toast=' . urlencode('Member 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;
}

$pageTitle = $isEdit ? 'Edit Member' : 'Add Member';
if (defined('NAZARETH_MEMBERS_ROUTE') && NAZARETH_MEMBERS_ROUTE === 'collect') {
    $pageTitle = $isEdit ? 'Edit member' : 'New member';
}
require_once __DIR__ . '/../../includes/header.php';
?>

<?php if ($isEdit && $isDeparted && !isDataCollector()): ?>
<div class="alert" style="background-color: #fef3c7; border-left: 4px solid #f59e0b; padding: 1rem; margin-bottom: 1.5rem; border-radius: 4px;">
    <strong>Note:</strong> This member is marked as departed. To manage departed status, please use the <a href="<?= nazareth_url('members/departed') ?>" style="color: #d97706; font-weight: 500;">Departed Members</a> page.
</div>
<?php endif; ?>

<div class="header">
    <h1><?= htmlspecialchars($pageTitle) ?></h1>
    <div class="header-actions">
        <?php if (!isDataCollector()): ?>
        <a href="<?= nazareth_url('members/child-form') ?>" class="btn btn-secondary">Download child form (DOCX)</a>
        <?php endif; ?>
        <a href="<?= nazareth_members_route() ?>" class="link-muted">← <?= (defined('NAZARETH_MEMBERS_ROUTE') && NAZARETH_MEMBERS_ROUTE === 'collect') ? 'Directory' : 'Members' ?></a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div data-toast="error" data-toast-msg="<?= htmlspecialchars(implode(' ', $errors)) ?>" style="display:none"></div>
<?php endif; ?>

<div class="form-card">
    <form method="post" class="member-form" enctype="multipart/form-data">
        <div class="form-group">
            <label>Photograph</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">Click to change photo</span>
                    <?php else: ?>
                        <img src="<?= BASE_PATH ?>/public/img/user.jpg" alt="" class="member-photo-default">
                        <span class="member-photo-placeholder-text">Click to add photo</span>
                        <span class="member-photo-hint">JPEG, PNG, GIF or WebP. Max 2 MB.</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">
            </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>
        <?php
            $sel_special = isset($_POST['special_group']) ? trim($_POST['special_group']) : (isset($member['is_aged']) && !empty($member['is_aged']) ? 'aged' : (isset($member['is_invalid']) && !empty($member['is_invalid']) ? 'invalid' : ''));
            ?>
        <div class="form-group">
            <label for="membership_number">Membership number</label>
            <div style="display: flex; align-items: flex-end; gap: 0.5rem; flex-wrap: wrap;">
                <input type="text" id="membership_number" name="membership_number" placeholder="YMC125" value="<?= htmlspecialchars(isset($_POST['membership_number']) ? trim($_POST['membership_number']) : ($member['membership_number'] ?? '')) ?>" maxlength="50" style="width: 10rem;">
                <div class="form-group" style="margin-bottom: 0;">
                    <label for="special_group" class="sr-only">Special group</label>
                    <select id="special_group" name="special_group" style="width: auto; min-width: 7rem;">
                        <option value="" <?= $sel_special === '' ? 'selected' : '' ?>>—</option>
                        <option value="aged" <?= $sel_special === 'aged' ? 'selected' : '' ?>>Aged</option>
                        <option value="invalid" <?= $sel_special === 'invalid' ? 'selected' : '' ?>>Invalid</option>
                    </select>
                </div>
            </div>
        </div>
        <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="<?= htmlspecialchars($t) ?>" <?= ($member['title'] ?? '') === $t ? 'selected' : '' ?>><?= htmlspecialchars($t) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="first_name">First name</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</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 class="form-row">
            <div class="form-group">
                <label for="phone" id="member_label_phone">Phone</label>
                <input type="text" id="phone" name="phone"
                    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"
                    value="<?= htmlspecialchars($member['email'] ?? '') ?>">
            </div>
        </div>
        <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>
                    <option value="Single" <?= ($member['marital_status'] ?? '') === 'Single' ? 'selected' : '' ?>>Single</option>
                    <option value="Married" <?= ($member['marital_status'] ?? '') === 'Married' ? 'selected' : '' ?>>Married</option>
                    <option value="Widowed" <?= ($member['marital_status'] ?? '') === 'Widowed' ? 'selected' : '' ?>>Widowed</option>
                    <option value="Divorced" <?= ($member['marital_status'] ?? '') === 'Divorced' ? 'selected' : '' ?>>Divorced</option>
                </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 class="form-row">
            <div class="form-group">
                <label for="status">Status</label>
                <?php if ($isEdit && $isDeparted): ?>
                    <input type="hidden" name="status" value="deceased">
                    <input type="text" value="Deceased (managed via Departed page)" disabled style="background-color: #f3f4f6; color: #6b7280;">
                    <small class="text-muted">Status cannot be changed here. Use the <a href="<?= BASE_PATH ?>/members/departed">Departed Members</a> page.</small>
                <?php else: ?>
                    <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>
                <?php endif; ?>
            </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"<?= (($member ?? [])['status'] ?? '') === 'child' ? ' 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>
        <?php
        $mForm = $member ?? [];
        $eligibleByAgeForMinistries = canBelongToMinistry($mForm['date_of_birth'] ?? null);
        $isChildStatusForm = (($mForm['status'] ?? '') === 'child');
        $canHaveMinistries = $eligibleByAgeForMinistries;
        if ($eligibleByAgeForMinistries): ?>
        <div id="member_ministry_wrap" class="form-group"<?= $isChildStatusForm ? ' style="display: none;"' : '' ?>>
            <label for="ministry_select">Service Groups</label>
            <div class="ministry-add-row" style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
                <select id="ministry_select">
                    <option value="">— Select service group —</option>
                    <?php foreach ($allMinistries as $min): ?>
                    <option value="<?= $min['id'] ?>"><?= htmlspecialchars($min['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="button" id="ministry_add_btn" class="btn btn-sm">Add service group</button>
            </div>
            <div id="ministry_selected" class="ministry-tags" style="margin-top: 0.5rem; min-height: 1.5rem;"></div>
            <div id="ministry_inputs"></div>
            <?php if (empty($allMinistries)): ?><small class="text-muted">No service groups defined. <a href="<?= BASE_PATH ?>/ministries/add">Add service groups</a>.</small><?php endif; ?>
        </div>
        <?php elseif (!$isChildStatusForm): ?>
        <div class="form-group" style="background: #f8fafc; padding: 0.75rem 1rem; border-radius: 6px; border: 1px solid #e2e8f0;">
            <strong style="font-size: 0.875rem;">Service Groups</strong>
            <p style="margin: 0.35rem 0 0 0; font-size: 0.875rem; color: #64748b;">Congregants in Children's Service and Junior Youth do not belong to service groups. Service group membership is for YPG and above (18+).</p>
        </div>
        <?php endif; ?>
        <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="<?= $h['id'] ?>" <?= ($member['household_id'] ?? '') == $h['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($h['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <p id="member_child_household_hint" class="text-muted" style="display: none; margin: 0.35rem 0 0; font-size: 0.875rem;">Link this child to their family household so they appear with parents and siblings in the directory.</p>
        </div>
        <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 digital address</label>
            <input type="text" id="ghana_post_address" name="ghana_post_address" placeholder="GA-123-4567"
                value="<?= htmlspecialchars($member['ghana_post_address'] ?? '') ?>">
            <small class="text-muted">Ghana Post GPS address for exact location</small>
        </div>
        <div class="form-group">
            <label for="map_link">Google Map link</label>
            <input type="url" id="map_link" name="map_link" placeholder="https://maps.google.com/ or https://goo.gl/maps/..."
                value="<?= htmlspecialchars($member['map_link'] ?? '') ?>">
            <small class="text-muted">Paste a link from Google Maps to the member’s location</small>
        </div>
        <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" placeholder="Phone number"
                    value="<?= htmlspecialchars($member['emergency_phone'] ?? '') ?>">
            </div>
        </div>
        <div class="form-group">
            <label for="notes">Notes</label>
            <textarea id="notes" name="notes" rows="2"><?= htmlspecialchars($member['notes'] ?? '') ?></textarea>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn"><?= $isEdit ? 'Update' : 'Save' ?> member</button>
            <a href="<?= nazareth_members_route() ?>" class="btn btn-ghost">Cancel</a>
        </div>
    </form>
</div>

<?php if ($canHaveMinistries): ?>
<script>
(function() {
    var ministries = <?= json_encode(array_column($allMinistries, 'name', 'id')) ?>;
    <?php
    $ids = $member['ministry_ids'] ?? ($isEdit ? getMemberMinistriesIds($id) : []);
    $initial = [];
    foreach ($allMinistries as $m) {
        if (in_array($m['id'], $ids)) $initial[] = ['id' => $m['id'], 'name' => $m['name']];
    }
    ?>
    var selected = <?= json_encode($initial) ?>;
    var container = document.getElementById('ministry_selected');
    var inputsContainer = document.getElementById('ministry_inputs');

    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: var(--border, #e2e8f0); padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.875rem; margin-right: 0.35rem; margin-bottom: 0.35rem;';
            tag.innerHTML = s.name + ' <button type="button" class="remove-ministry" data-id="' + s.id + '" style="background:none;border:none;cursor:pointer;padding:0;font-size:1rem;line-height:1;color:var(--text-muted,#718096)" title="Remove">&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();
            });
        });
    }

    document.getElementById('ministry_add_btn').addEventListener('click', function() {
        var sel = document.getElementById('ministry_select');
        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) {
            var url = URL.createObjectURL(file);
            preview.src = url;
            preview.style.display = 'block';
            if (placeholder) placeholder.style.visibility = 'hidden';
        } else {
            preview.style.display = 'none';
            preview.src = '';
            if (placeholder) placeholder.style.visibility = '';
        }
    });
})();
</script>
<?php if (!($isEdit && $isDeparted)): ?>
<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 rowMarital = document.getElementById('member_row_marital_occupation');
    var hintHousehold = document.getElementById('member_child_household_hint');
    var groupConfirmation = document.getElementById('member_group_confirmation_date');
    var confirmationInput = document.getElementById('confirmation_date');
    var ministryWrap = document.getElementById('member_ministry_wrap');

    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' }
    };

    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 (rowMarital) rowMarital.style.display = child ? 'none' : '';
        if (hintHousehold) hintHousehold.style.display = child ? 'block' : 'none';
        if (groupConfirmation) groupConfirmation.style.display = child ? 'none' : '';
        if (child && confirmationInput) confirmationInput.value = '';
        if (ministryWrap) ministryWrap.style.display = child ? 'none' : '';
    }

    statusEl.addEventListener('change', sync);
    sync();
})();
</script>
<?php endif; ?>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
