<link rel="icon" href="logo.jpg" type="image/jpg">
<?php
// File: manage_members.php
// Handles adding, editing, and managing members of a specific household.
require_once "db.php";
check_login();

$error_message = '';
$success_message = '';
$household_id = $_GET['household_id'] ?? null;
$household_info = null;
$resident_to_edit = null;

if (!$household_id) {
    header("Location: households.php");
    exit;
}

// Fetch household info
$stmt_h = $conn->prepare("SELECT household_no, purok FROM households WHERE id = ?");
if (!$stmt_h) {
    die("Household prepare failed: " . $conn->error);
}
$stmt_h->bind_param("i", $household_id);
$stmt_h->execute();
$result_h = $stmt_h->get_result();
if ($result_h->num_rows > 0) {
    $household_info = $result_h->fetch_assoc();
} else {
    header("Location: households.php");
    exit;
}
$stmt_h->close();

$page_title = "Manage Members - " . htmlspecialchars($household_info['household_no']);

// --- FORM SUBMISSION LOGIC ---

// List of all fields expected from the form (must match columns in `residents`)
$resident_fields = [
    'first_name', 'middle_name', 'last_name', 'suffix', 'relation_to_head',
    'birthday', 'gender', 'civil_status', 'occupation', 'monthly_income',
    'educational_attainment', 'is_voter', 'type_of_dwelling', 'water_source',
    'toilet_type', 'has_electricity', 'is_pwd', 'has_cvd', 'has_hpn',
    'has_dm', 'has_ca', 'has_eye_prob', 'has_leprosy', 'has_tb', 'has_goiter',
    'has_mental', 'is_smoker', 'has_ckd', 'is_sc', 'has_veg_garden', 'has_livestock', 
    'has_poultry', 'has_fishpond', 'is_pregnant', 'is_breastfeeding', 'fp_method', 'youth_status'
];

// Boolean fields (checkbox/radio) that should always be 0 or 1
$boolean_fields = [
    'is_voter', 'has_electricity', 'is_pwd', 'has_cvd', 'has_hpn',
    'has_dm', 'has_ca', 'has_eye_prob', 'has_leprosy', 'has_tb',
    'has_goiter', 'has_mental', 'is_smoker', 'has_ckd', 'is_sc',
    'has_veg_garden', 'has_livestock', 'has_poultry', 'has_fishpond',
    'is_pregnant', 'is_breastfeeding'
];

// Handle ADDING a new member
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_member'])) {

    $params       = [$household_id];
    $types        = 'i';
    $placeholders = '?';
    $columns      = 'household_id';

    foreach ($resident_fields as $field) {
        $columns      .= ", `$field`";
        $placeholders .= ', ?';

        if (in_array($field, $boolean_fields, true)) {
            $raw   = $_POST[$field] ?? '0';
            $value = ($raw === '1' || $raw === 1) ? 1 : 0;
        } else {
            $value = $_POST[$field] ?? null;
        }

        $params[] = $value;
        $types   .= 's';
    }

    $sql = "INSERT INTO residents ($columns) VALUES ($placeholders)";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die("Insert prepare failed: " . $conn->error . " | SQL: " . $sql);
    }

    $stmt->bind_param($types, ...$params);
    if ($stmt->execute()) {
        $success_message = "New member added successfully!";
    } else {
        $error_message = "Error adding member: " . $stmt->error;
    }
    $stmt->close();
}

// Handle UPDATING a member
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_member'])) {
    $resident_id = (int)$_POST['resident_id'];

    $params      = [];
    $types       = '';
    $set_clauses = [];

    foreach ($resident_fields as $field) {
        $set_clauses[] = "`$field` = ?";

        if (in_array($field, $boolean_fields, true)) {
            $raw   = $_POST[$field] ?? '0';
            $value = ($raw === '1' || $raw === 1) ? 1 : 0;
        } else {
            $value = $_POST[$field] ?? null;
        }

        $params[] = $value;
        $types   .= 's';
    }

    $sql = "UPDATE residents SET " . implode(', ', $set_clauses) . " WHERE id = ? AND household_id = ?";
    $params[] = $resident_id;
    $params[] = $household_id;
    $types   .= 'ii';

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die("Update prepare failed: " . $conn->error . " | SQL: " . $sql);
    }

    $stmt->bind_param($types, ...$params);
    if ($stmt->execute()) {
        $success_message = "Member details updated successfully!";
    } else {
        $error_message = "Error updating member: " . $stmt->error;
    }
    $stmt->close();
}

// Handle ARCHIVING a member (with password verification)
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['confirm_archive'])) {
    $archive_id       = (int)$_POST['archive_id'];
    $password         = $_POST['admin_password'];
    $current_user_id  = $_SESSION['user_id'];

    $stmt_pass = $conn->prepare("SELECT password FROM users WHERE id = ?");
    if (!$stmt_pass) {
        die("Password prepare failed: " . $conn->error);
    }
    $stmt_pass->bind_param("i", $current_user_id);
    $stmt_pass->execute();
    $result_pass = $stmt_pass->get_result();
    $user = $result_pass->fetch_assoc();
    $stmt_pass->close();

    if ($user && password_verify($password, $user['password'])) {
        $stmt_archive = $conn->prepare("UPDATE residents SET is_archived = 1, date_archived = NOW() WHERE id = ? AND household_id = ?");
        if (!$stmt_archive) {
            die("Archive prepare failed: " . $conn->error);
        }
        $stmt_archive->bind_param("ii", $archive_id, $household_id);
        if ($stmt_archive->execute()) {
            $success_message = "Member has been archived successfully.";
        } else {
            $error_message = "Error archiving member: " . $stmt_archive->error;
        }
        $stmt_archive->close();
    } else {
        $error_message = "Incorrect password. Archiving failed.";
    }
}

// Check if we are editing a resident to pre-fill the form
if (isset($_GET['edit_id'])) {
    $edit_id = (int)$_GET['edit_id'];
    $stmt_edit = $conn->prepare("SELECT * FROM residents WHERE id = ? AND household_id = ?");
    if (!$stmt_edit) {
        die("Edit prepare failed: " . $conn->error);
    }
    $stmt_edit->bind_param("ii", $edit_id, $household_id);
    $stmt_edit->execute();
    $result_edit = $stmt_edit->get_result();
    if ($result_edit->num_rows > 0) {
        $resident_to_edit = $result_edit->fetch_assoc();
    }
    $stmt_edit->close();
}

include 'header.php';
?>

<div class="main-content">
    <div class="page-header">
        <h1>Manage Household Members</h1>
        <p>
            For Household: <strong><?php echo htmlspecialchars($household_info['household_no']); ?></strong>
            (Purok: <?php echo htmlspecialchars($household_info['purok']); ?>)
        </p>
        <a href="households.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> Back to Households</a>
    </div>

    <!-- Add/Edit Member Form -->
    <div class="card form-container">
        <h2 class="card-title"><?php echo $resident_to_edit ? 'Edit Member Details' : 'Add New Member'; ?></h2>
        <?php if($error_message): ?><div class="alert alert-danger"><?php echo $error_message; ?></div><?php endif; ?>
        <?php if($success_message): ?><div class="alert alert-success"><?php echo $success_message; ?></div><?php endif; ?>

        <form action="manage_members.php?household_id=<?php echo $household_id; ?>" method="post">
            <?php if ($resident_to_edit): ?>
                <input type="hidden" name="resident_id" value="<?php echo (int)$resident_to_edit['id']; ?>">
            <?php endif; ?>
            
            <fieldset>
                <legend>Personal Information</legend>
                <div class="form-grid">
                    <div class="form-group">
                        <label>First Name</label>
                        <input type="text" name="first_name" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['first_name'] ?? ''); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Middle Name</label>
                        <input type="text" name="middle_name" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['middle_name'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Last Name</label>
                        <input type="text" name="last_name" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['last_name'] ?? ''); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Suffix</label>
                        <input type="text" name="suffix" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['suffix'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Relation to Head</label>
                        <select name="relation_to_head" class="form-control" required>
                            <?php $rel = $resident_to_edit['relation_to_head'] ?? 'Head'; ?>
                            <option value="Head"     <?php if($rel==='Head')     echo 'selected'; ?>>Head</option>
                            <option value="Spouse"   <?php if($rel==='Spouse')   echo 'selected'; ?>>Spouse</option>
                            <option value="Son"      <?php if($rel==='Son')      echo 'selected'; ?>>Son</option>
                            <option value="Daughter" <?php if($rel==='Daughter') echo 'selected'; ?>>Daughter</option>
                            <option value="Other"    <?php if($rel==='Other')    echo 'selected'; ?>>Other Relative</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Birthday</label>
                        <input type="date" name="birthday" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['birthday'] ?? ''); ?>" required>
                    </div>
                    <div class="form-group">
                        <label>Gender</label>
                        <select name="gender" id="gender" class="form-control" required onchange="toggleFemaleFields()">
                            <?php $g = $resident_to_edit['gender'] ?? ''; ?>
                            <option value="">-- Select --</option>
                            <option value="Male"   <?php if($g==='Male')   echo 'selected'; ?>>Male</option>
                            <option value="Female" <?php if($g==='Female') echo 'selected'; ?>>Female</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Civil Status</label>
                        <select name="civil_status" class="form-control" required>
                            <?php $cs = $resident_to_edit['civil_status'] ?? 'Single'; ?>
                            <option value="Single"    <?php if($cs==='Single')    echo 'selected'; ?>>Single</option>
                            <option value="Married"   <?php if($cs==='Married')   echo 'selected'; ?>>Married</option>
                            <option value="Widowed"   <?php if($cs==='Widowed')   echo 'selected'; ?>>Widowed</option>
                            <option value="Separated" <?php if($cs==='Separated') echo 'selected'; ?>>Separated</option>
                        </select>
                    </div>
                </div>
            </fieldset>

            <fieldset>
                <legend>PWD Status</legend>
                <div class="form-group">
                    <label><strong>Is this resident a PWD?</strong></label>
                    <?php $pwd_val = $resident_to_edit['is_pwd'] ?? '0'; ?>
                    <div style="display:flex; gap:20px; margin-top:5px;">
                        <label>
                            <input type="radio" name="is_pwd" value="1" <?php if($pwd_val=='1') echo 'checked'; ?>>
                            Yes (PWD)
                        </label>
                        <label>
                            <input type="radio" name="is_pwd" value="0" <?php if($pwd_val=='0') echo 'checked'; ?>>
                            No (Not PWD)
                        </label>
                    </div>
                </div>
            </fieldset>

            <!-- Female-specific fields -->
            <fieldset id="femaleSpecificFields" style="display: none;">
                <legend>Female Reproductive Status</legend>
                <div class="form-grid">
                    <div class="checkbox-group">
                        <input type="hidden" name="is_pregnant" value="0">
                        <input type="checkbox" name="is_pregnant" value="1"
                            <?php echo (($resident_to_edit['is_pregnant'] ?? '0') == '1') ? 'checked' : ''; ?>>
                        Pregnant
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="is_breastfeeding" value="0">
                        <input type="checkbox" name="is_breastfeeding" value="1"
                            <?php echo (($resident_to_edit['is_breastfeeding'] ?? '0') == '1') ? 'checked' : ''; ?>>
                        Breastfeeding
                    </div>
                    <div class="form-group full-width">
                        <label>Family Planning Method</label>
                        <select name="fp_method" class="form-control">
                            <?php $fp = $resident_to_edit['fp_method'] ?? ''; ?>
                            <option value="">None</option>
                            <option value="Pills"     <?php if($fp==='Pills')     echo 'selected'; ?>>Pills</option>
                            <option value="Implant"   <?php if($fp==='Implant')   echo 'selected'; ?>>Implant</option>
                            <option value="DMPA"      <?php if($fp==='DMPA')      echo 'selected'; ?>>DMPA</option>
                            <option value="DPO"       <?php if($fp==='DPO')       echo 'selected'; ?>>DPO</option>
                            <option value="NAT'L FP"  <?php if($fp==="NAT'L FP")  echo 'selected'; ?>>NAT'L FP</option>
                            <option value="Condom"    <?php if($fp==='Condom')    echo 'selected'; ?>>Condom</option>
                            <option value="IUD"       <?php if($fp==='IUD')       echo 'selected'; ?>>IUD</option>
                        </select>
                    </div>
                </div>
            </fieldset>

            <fieldset>
                <legend>Socio-Economic Profile</legend>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Occupation</label>
                        <input type="text" name="occupation" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['occupation'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Monthly Income (Php)</label>
                        <input type="number" step="0.01" name="monthly_income" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['monthly_income'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Educational Attainment</label>
                        <?php $ea = $resident_to_edit['educational_attainment'] ?? ''; ?>
                        <select name="educational_attainment" class="form-control">
                            <option value="">-- Select --</option>
                            <option value="No Formal Education" <?php if($ea==='No Formal Education') echo 'selected'; ?>>No Formal Education</option>
                            <option value="Pre-school" <?php if($ea==='Pre-school') echo 'selected'; ?>>Pre-school</option>
                            <option value="Elementary Level" <?php if($ea==='Elementary Level') echo 'selected'; ?>>Elementary Level</option>
                            <option value="Elementary Graduate" <?php if($ea==='Elementary Graduate') echo 'selected'; ?>>Elementary Graduate</option>
                            <option value="High School Level" <?php if($ea==='High School Level') echo 'selected'; ?>>High School Level</option>
                            <option value="High School Graduate" <?php if($ea==='High School Graduate') echo 'selected'; ?>>High School Graduate</option>
                            <option value="Vocational/Trade Course" <?php if($ea==='Vocational/Trade Course') echo 'selected'; ?>>Vocational/Trade Course</option>
                            <option value="College Level" <?php if($ea==='College Level') echo 'selected'; ?>>College Level</option>
                            <option value="College Graduate" <?php if($ea==='College Graduate') echo 'selected'; ?>>College Graduate</option>
                            <option value="Post Graduate" <?php if($ea==='Post Graduate') echo 'selected'; ?>>Post Graduate</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Youth Status</label>
                        <?php $ys = $resident_to_edit['youth_status'] ?? ''; ?>
                        <select name="youth_status" class="form-control">
                            <option value="">N/A</option>
                            <option value="ISY" <?php if($ys==='ISY') echo 'selected'; ?>>In-School Youth (ISY)</option>
                            <option value="OSY" <?php if($ys==='OSY') echo 'selected'; ?>>Out-of-School Youth (OSY)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Registered Voter?</label>
                        <?php $v = $resident_to_edit['is_voter'] ?? '0'; ?>
                        <select name="is_voter" class="form-control" required>
                            <option value="1" <?php if($v==='1') echo 'selected'; ?>>Yes</option>
                            <option value="0" <?php if($v==='0') echo 'selected'; ?>>No</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Type of Dwelling</label>
                        <input type="text" name="type_of_dwelling" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['type_of_dwelling'] ?? ''); ?>">
                    </div>
                </div>
            </fieldset>
            
            <fieldset>
                <legend>Health &amp; Sanitation Profile</legend>
                <div class="form-grid">
                    <div class="form-group">
                        <label>Source of Water</label>
                        <input type="text" name="water_source" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['water_source'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Toilet Type</label>
                        <input type="text" name="toilet_type" class="form-control"
                               value="<?php echo htmlspecialchars($resident_to_edit['toilet_type'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label>Has Electricity?</label>
                        <?php $he = $resident_to_edit['has_electricity'] ?? '0'; ?>
                        <select name="has_electricity" class="form-control">
                            <option value="1" <?php if($he==='1') echo 'selected'; ?>>Yes</option>
                            <option value="0" <?php if($he==='0') echo 'selected'; ?>>No</option>
                        </select>
                    </div>
                </div>
                <p><strong>Health Conditions (Check if applicable):</strong></p>
                <div class="checkbox-grid">
                    <div class="checkbox-group">
                        <input type="hidden" name="has_cvd" value="0">
                        <input type="checkbox" name="has_cvd" value="1" <?php echo (($resident_to_edit['has_cvd'] ?? '0') == '1') ? 'checked' : ''; ?>> CVD
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_hpn" value="0">
                        <input type="checkbox" name="has_hpn" value="1" <?php echo (($resident_to_edit['has_hpn'] ?? '0') == '1') ? 'checked' : ''; ?>> HPN
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_dm" value="0">
                        <input type="checkbox" name="has_dm" value="1" <?php echo (($resident_to_edit['has_dm'] ?? '0') == '1') ? 'checked' : ''; ?>> DM
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_ca" value="0">
                        <input type="checkbox" name="has_ca" value="1" <?php echo (($resident_to_edit['has_ca'] ?? '0') == '1') ? 'checked' : ''; ?>> CA
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_eye_prob" value="0">
                        <input type="checkbox" name="has_eye_prob" value="1" <?php echo (($resident_to_edit['has_eye_prob'] ?? '0') == '1') ? 'checked' : ''; ?>> Eye Problem
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_leprosy" value="0">
                        <input type="checkbox" name="has_leprosy" value="1" <?php echo (($resident_to_edit['has_leprosy'] ?? '0') == '1') ? 'checked' : ''; ?>> Leprosy
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_tb" value="0">
                        <input type="checkbox" name="has_tb" value="1" <?php echo (($resident_to_edit['has_tb'] ?? '0') == '1') ? 'checked' : ''; ?>> TB
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_goiter" value="0">
                        <input type="checkbox" name="has_goiter" value="1" <?php echo (($resident_to_edit['has_goiter'] ?? '0') == '1') ? 'checked' : ''; ?>> Goiter
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_mental" value="0">
                        <input type="checkbox" name="has_mental" value="1" <?php echo (($resident_to_edit['has_mental'] ?? '0') == '1') ? 'checked' : ''; ?>> Mental
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="is_smoker" value="0">
                        <input type="checkbox" name="is_smoker" value="1" <?php echo (($resident_to_edit['is_smoker'] ?? '0') == '1') ? 'checked' : ''; ?>> Smoker
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_ckd" value="0">
                        <input type="checkbox" name="has_ckd" value="1" <?php echo (($resident_to_edit['has_ckd'] ?? '0') == '1') ? 'checked' : ''; ?>> CKD
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="is_sc" value="0">
                        <input type="checkbox" name="is_sc" value="1" <?php echo (($resident_to_edit['is_sc'] ?? '0') == '1') ? 'checked' : ''; ?>> Senior Citizen
                    </div>
                </div>
            </fieldset>
            
            <fieldset>
                <legend>Food Production Activities (Check if applicable)</legend>
                <div class="checkbox-grid">
                    <div class="checkbox-group">
                        <input type="hidden" name="has_veg_garden" value="0">
                        <input type="checkbox" name="has_veg_garden" value="1" <?php echo (($resident_to_edit['has_veg_garden'] ?? '0') == '1') ? 'checked' : ''; ?>> Vegetable Garden
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_livestock" value="0">
                        <input type="checkbox" name="has_livestock" value="1" <?php echo (($resident_to_edit['has_livestock'] ?? '0') == '1') ? 'checked' : ''; ?>> Livestock
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_poultry" value="0">
                        <input type="checkbox" name="has_poultry" value="1" <?php echo (($resident_to_edit['has_poultry'] ?? '0') == '1') ? 'checked' : ''; ?>> Poultry
                    </div>
                    <div class="checkbox-group">
                        <input type="hidden" name="has_fishpond" value="0">
                        <input type="checkbox" name="has_fishpond" value="1" <?php echo (($resident_to_edit['has_fishpond'] ?? '0') == '1') ? 'checked' : ''; ?>> Fishpond
                    </div>
                </div>
            </fieldset>

            <div class="form-actions">
                <?php if ($resident_to_edit): ?>
                    <button type="submit" name="update_member" class="btn btn-primary">Update Member</button>
                    <a href="manage_members.php?household_id=<?php echo $household_id; ?>" class="btn btn-secondary">Cancel Edit</a>
                <?php else: ?>
                    <button type="submit" name="add_member" class="btn btn-primary">Add Member</button>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- Member List -->
    <div class="card">
        <h2 class="card-title">Family Members</h2>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>Name</th><th>Age</th><th>Relation to Head</th><th>Voter Status</th><th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                        $stmt_members = $conn->prepare("SELECT * FROM residents WHERE household_id = ? AND is_archived = 0 ORDER BY relation_to_head");
                        if (!$stmt_members) {
                            die("Members prepare failed: " . $conn->error);
                        }
                        $stmt_members->bind_param("i", $household_id);
                        $stmt_members->execute();
                        $result_members = $stmt_members->get_result();
                        if ($result_members->num_rows > 0):
                            while($row = $result_members->fetch_assoc()):
                                $age = date_diff(date_create($row['birthday']), date_create('now'))->y;
                    ?>
                            <tr>
                                <td>
                                    <?php echo htmlspecialchars($row['first_name'] . " " . $row['last_name']); ?>
                                    <?php if (!empty($row['is_pwd'])): ?>
                                        <span class="badge badge-info" title="Person with Disability" style="margin-left:6px;">PWD</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo $age; ?></td>
                                <td><?php echo htmlspecialchars($row['relation_to_head']); ?></td>
                                <td><?php echo $row['is_voter'] ? 'Registered' : 'Not Registered'; ?></td>
                                <td>
                                    <a href="manage_members.php?household_id=<?php echo $household_id; ?>&edit_id=<?php echo $row['id']; ?>" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-edit"></i> Edit
                                    </a>
                                    <button type="button" class="btn btn-warning btn-sm archive-btn"
                                            data-id="<?php echo $row['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>">
                                        <i class="fas fa-archive"></i> Archive
                                    </button>
                                </td>
                            </tr>
                    <?php 
                            endwhile;
                        else: 
                    ?>
                        <tr><td colspan="5">No members found for this household. Add one using the form above.</td></tr>
                    <?php 
                        endif;
                        $stmt_members->close();
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Archive Confirmation Modal -->
<div id="archiveModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>Confirm Archive</h2>
        </div>
        <form action="manage_members.php?household_id=<?php echo $household_id; ?>" method="post">
            <div class="modal-body">
                <p>Are you sure you want to archive <strong id="archiveMemberName"></strong>? This action requires you to enter your password.</p>
                <input type="hidden" name="archive_id" id="archiveMemberId">
                <div class="form-group">
                    <label for="admin_password">Your Password</label>
                    <input type="password" name="admin_password" id="admin_password" class="form-control" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                <button type="submit" name="confirm_archive" class="btn btn-warning">Confirm Archive</button>
            </div>
        </form>
    </div>
</div>

<script>
    function toggleFemaleFields() {
        const genderSelect = document.getElementById('gender');
        const femaleFields = document.getElementById('femaleSpecificFields');
        if (genderSelect.value === 'Female') {
            femaleFields.style.display = 'block';
        } else {
            femaleFields.style.display = 'none';
        }
    }

    // Run on page load in case we are editing a female resident
    document.addEventListener('DOMContentLoaded', function() {
        toggleFemaleFields();
    });

    // Modal JavaScript
    const modal = document.getElementById('archiveModal');
    const archiveMemberName = document.getElementById('archiveMemberName');
    const archiveMemberId = document.getElementById('archiveMemberId');

    document.querySelectorAll('.archive-btn').forEach(button => {
        button.addEventListener('click', function() {
            const residentId = this.getAttribute('data-id');
            const residentName = this.getAttribute('data-name');
            archiveMemberName.textContent = residentName;
            archiveMemberId.value = residentId;
            modal.style.display = 'block';
        });
    });

    function closeModal() {
        modal.style.display = 'none';
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            closeModal();
        }
    }
</script>

<?php include 'footer.php'; ?>