<?php
/**
 * Member Edit Page
 * GHAMECC Choir Management Platform
 */

// Include necessary files
require_once '../includes/auth.php';
require_once '../config/database.php';
require_once '../config/logger.php';

// Ensure user is logged in
requireLogin();

// Log page access
logMemberInfo("Member edit page accessed", [
    'user_role' => $_SESSION['role'] ?? 'unknown',
    'society_id' => $_SESSION['society_id'] ?? null
]);

// Check if user has permission to edit members
if (!hasRole('admin') && !hasRole('manager') && !hasRole('secretary') && 
    !hasRole('choirmaster') && !hasRole('society_secretary') && !hasRole('society_treasurer')) {
    header("Location: list.php?error=permission_denied");
    exit;
}

// Check if member ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: list.php?error=invalid_id");
    exit;
}

$memberId = (int)$_GET['id'];

// Check if user has access to this member
if (!hasRole(['admin', 'manager']) && !hasMemberAccess($memberId)) {
    header("Location: list.php?error=permission_denied");
    exit;
}

$errors = [];
$success = false;

// Get member details
$query = "SELECT m.*, s.name as society_name, s.circuit_id
          FROM members m
          LEFT JOIN societies s ON m.society_id = s.id
          WHERE m.id = ?";

$member = fetchRows($query, [$memberId]);

// Check if member exists
if (empty($member)) {
    header("Location: list.php?error=member_not_found");
    exit;
}

$member = $member[0];

// Leadership position options by governance level
$leadershipPositions = [
    'connexion' => [
        'Connexion Chairman',
        'Connexion Assistant Chairman',
        'Connexion Secretary',
        'Connexion Assistant Secretary',
        'Connexion Organizer',
        'Connexion Assistant Organizer',
        'Connexion Financial Secretary',
        'Connexion Treasurer',
        'Connexion Ex-Officio Member'
    ],
    'diocese' => [
        'Diocesan Chairman',
        'Diocesan Assistant Chairman',
        'Diocesan Secretary',
        'Diocesan Assistant Secretary',
        'Diocesan Organizer',
        'Diocesan Assistant Organizer',
        'Diocesan Financial Secretary',
        'Diocesan Treasurer',
        'Diocesan Ex-Officio Member'
    ],
    'circuit' => [
        'Circuit Chairman',
        'Circuit Assistant Chairman',
        'Circuit Secretary',
        'Circuit Assistant Secretary',
        'Circuit Organizer',
        'Circuit Assistant Organizer',
        'Circuit Financial Secretary',
        'Circuit Treasurer',
        'Circuit Ex-Officio Member'
    ],
    'society' => [
        'Society Choirmaster/Organist',
        'Society Assistant Choirmaster/Organist',
        'Society Secretary',
        'Society Assistant Secretary',
        'Society Treasurer',
        'Society Curator',
        'Society Assistant Curator',
        'Society Ex-Officio Member'
    ]
];

// Determine position groups available to the current user
$positionGroups = [];
$sessionRole = strtolower($_SESSION['role'] ?? '');
$addPositionGroup = function (string $key, string $label) use (&$positionGroups, $leadershipPositions) {
    if (!empty($leadershipPositions[$key])) {
        $positionGroups[$label] = $leadershipPositions[$key];
    }
};

if (hasRole(['admin', 'manager', 'secretary'])) {
    $addPositionGroup('connexion', 'Connexion Leadership Positions');
    $addPositionGroup('diocese', 'Diocesan Leadership Positions');
    $addPositionGroup('circuit', 'Circuit Leadership Positions');
    $addPositionGroup('society', 'Society Leadership Positions');
} elseif (strpos($sessionRole, 'connexion_') === 0) {
    $addPositionGroup('connexion', 'Connexion Leadership Positions');
} elseif (strpos($sessionRole, 'diocesan_') === 0 || strpos($sessionRole, 'diocese_') === 0) {
    $addPositionGroup('diocese', 'Diocesan Leadership Positions');
} elseif (strpos($sessionRole, 'circuit_') === 0) {
    $addPositionGroup('circuit', 'Circuit Leadership Positions');
} else {
    $addPositionGroup('society', 'Society Leadership Positions');
}

// Ensure the member's current executive position stays selectable
$currentExecutivePosition = trim($member['executive_position'] ?? '');
if ($currentExecutivePosition !== '') {
    $present = false;
    foreach ($positionGroups as $positions) {
        if (in_array($currentExecutivePosition, $positions, true)) {
            $present = true;
            break;
        }
    }
    if (!$present) {
        $positionGroups = ['Current Position' => [$currentExecutivePosition]] + $positionGroups;
    }
}

// Get all societies for dropdown
$societies = fetchRows("SELECT s.*, c.name as circuit_name, d.name as diocese_name 
                       FROM societies s 
                       JOIN circuits c ON s.circuit_id = c.id 
                       JOIN dioceses d ON c.diocese_id = d.id 
                       ORDER BY d.name, c.name, s.name");

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate inputs
    $firstName = trim($_POST['first_name']);
    $middleName = trim($_POST['middle_name'] ?? '');
    $lastName = trim($_POST['last_name']);
    $sex = $_POST['sex'];
    $dob = $_POST['dob'];
    $contactNumber = trim($_POST['contact_number']);
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $profession = trim($_POST['profession'] ?? '');
    $part = $_POST['part'];
    $partOther = trim($_POST['part_other'] ?? '');
    $societyId = $_POST['society_id'];
    $membershipStatus = $_POST['membership_status'];
    $maritalStatus = $_POST['marital_status'] ?? '';
    $spouseName = trim($_POST['spouse_name'] ?? '');
    $emergencyContactName = trim($_POST['emergency_contact_name'] ?? '');
    $emergencyContactNumber = trim($_POST['emergency_contact_number'] ?? '');
    $musicalBackground = trim($_POST['musical_background'] ?? '');
    $instrumentsPlayed = trim($_POST['instruments_played'] ?? '');
    $educationLevel = $_POST['education_level'] ?? '';
    $churchRole = $_POST['church_role'] ?? '';
    $otherChurchRole = trim($_POST['other_church_role'] ?? '');
    $baptized = $_POST['baptized'];
    $confirmed = $_POST['confirmed'];
    $communicant = $_POST['communicant'];
    $membershipType = $_POST['membership_type'] ?? '';
    $role = $_POST['role'] ?? '';
    $roleOther = trim($_POST['role_other'] ?? '');
    $executivePosition = trim($_POST['executive_position'] ?? '');
    $executivePositionOther = trim($_POST['executive_position_other'] ?? '');
    $circuitModelChoirMember = isset($_POST['circuit_model_choir_member']) ? 1 : 0;
    $diocesanModelChoirMember = isset($_POST['diocesan_model_choir_member']) ? 1 : 0;
    $musicalSkillAssessment = trim($_POST['musical_skill_assessment'] ?? '');
    
    // Validate required fields
    if (empty($firstName)) {
        $errors[] = "First name is required";
    }
    
    if (empty($lastName)) {
        $errors[] = "Last name is required";
    }
    
    if (empty($sex)) {
        $errors[] = "Gender is required";
    }
    
    if (empty($contactNumber)) {
        $errors[] = "Contact number is required";
    }
    
    if (empty($part)) {
        $errors[] = "Voice part is required";
    }
    
    if (empty($societyId)) {
        $errors[] = "Society is required";
    }
    
    // Check if email is unique (if provided)
    if (!empty($email)) {
        $existingMember = fetchRows("SELECT id FROM members WHERE email = ? AND id != ?", [$email, $memberId]);
        if (!empty($existingMember)) {
            $errors[] = "A member with this email already exists";
        }
    }
    
    // Check if contact number is unique
    $existingMember = fetchRows("SELECT id FROM members WHERE contact_number = ? AND id != ?", [$contactNumber, $memberId]);
    if (!empty($existingMember)) {
        $errors[] = "A member with this contact number already exists";
    }
    
    if (empty($errors)) {
        // Handle profile image upload if provided
        $profileImage = $member['profile_image']; // Default to current image
        
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['size'] > 0) {
            $uploadDir = '../uploads/members/';
            
            // Create directory if it doesn't exist
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileExtension = pathinfo($_FILES['profile_image']['name'], PATHINFO_EXTENSION);
            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (!in_array(strtolower($fileExtension), $allowedExtensions)) {
                $errors[] = "Invalid file format. Only JPG, JPEG, PNG, and GIF are allowed.";
            } else {
                $newFileName = 'member_' . $memberId . '_' . time() . '.' . $fileExtension;
                $targetFilePath = $uploadDir . $newFileName;
                
                if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $targetFilePath)) {
                    // Delete old profile image if exists
                    if (!empty($member['profile_image']) && file_exists($uploadDir . $member['profile_image'])) {
                        unlink($uploadDir . $member['profile_image']);
                    }
                    
                    $profileImage = $newFileName;
                } else {
                    $errors[] = "Failed to upload profile image. Please try again.";
                }
            }
        }
        
        if (empty($errors)) {
            // Update member in database
            $query = "UPDATE members SET 
                        first_name = ?, 
                        middle_name = ?, 
                        last_name = ?, 
                        sex = ?, 
                        dob = ?, 
                        contact_number = ?, 
                        email = ?, 
                        address = ?, 
                        profession = ?, 
                        part = ?, 
                        part_other = ?, 
                        society_id = ?, 
                        membership_status = ?, 
                        marital_status = ?, 
                        spouse_name = ?, 
                        emergency_contact_name = ?, 
                        emergency_contact_number = ?, 
                        musical_background = ?, 
                        instruments_played = ?, 
                        education_level = ?, 
                        church_role = ?, 
                        other_church_role = ?, 
                        baptized = ?, 
                        confirmed = ?, 
                        communicant = ?, 
                        membership_type = ?, 
                        role = ?, 
                        role_other = ?, 
                        executive_position = ?, 
                        executive_position_other = ?, 
                        circuit_model_choir_member = ?, 
                        diocesan_model_choir_member = ?, 
                        musical_skill_assessment = ?, 
                        profile_image = ?, 
                        updated_at = NOW() 
                      WHERE id = ?";
            
            $params = [
                $firstName,
                $middleName,
                $lastName,
                $sex,
                $dob ?: null,
                $contactNumber,
                $email ?: null,
                $address ?: null,
                $profession ?: null,
                $part,
                $partOther ?: null,
                $societyId,
                $membershipStatus,
                $maritalStatus ?: null,
                $spouseName ?: null,
                $emergencyContactName ?: null,
                $emergencyContactNumber ?: null,
                $musicalBackground ?: null,
                $instrumentsPlayed ?: null,
                $educationLevel ?: null,
                $churchRole ?: null,
                $otherChurchRole ?: null,
                $baptized,
                $confirmed,
                $communicant,
                $membershipType ?: null,
                $role ?: null,
                $roleOther ?: null,
                $executivePosition ?: null,
                $executivePositionOther ?: null,
                $circuitModelChoirMember,
                $diocesanModelChoirMember,
                $musicalSkillAssessment ?: null,
                $profileImage,
                $memberId
            ];
            
            $updateResult = executeQuery($query, $params);
            if ($updateResult !== false) {
                $success = true;
                
                // Refresh member data
                $member = fetchRows("SELECT m.*, s.name as society_name, s.circuit_id 
                                    FROM members m 
                                    LEFT JOIN societies s ON m.society_id = s.id 
                                    WHERE m.id = ?", [$memberId])[0];
                
                // Log member edit
                logInfo("Member edited", [
                    'member_id' => $memberId,
                    'updated_by' => $_SESSION['user_id']
                ]);
            } else {
                $errors[] = "Failed to update member. Please try again.";
                if (function_exists('logMemberError')) {
                    logMemberError("Member update failed", [
                        'member_id' => $memberId,
                        'db_error' => $conn->error ?? null,
                        'executive_position' => $executivePosition,
                        'executive_position_other' => $executivePositionOther
                    ]);
                }
            }
        }
    }
}

// Set base path for includes
$basePath = '..';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Member - GHAMECC Choir Management Platform</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .profile-preview {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 3px solid #ccc;
        }
        .required-field::after {
            content: " *";
            color: red;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Edit Member</h1>
                    <div>
                        <a href="view.php?id=<?php echo $memberId; ?>" class="btn btn-secondary me-2">
                            <i class="bi bi-eye"></i> View Profile
                        </a>
                        <a href="list.php" class="btn btn-secondary">
                            <i class="bi bi-arrow-left"></i> Back to Members List
                        </a>
                    </div>
                </div>
                
                <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <i class="bi bi-check-circle-fill me-2"></i> Member information updated successfully!
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                    <strong>Error!</strong> Please correct the following issues:
                    <ul class="mb-0 mt-2">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo $error; ?></li>
                        <?php endforeach; ?>
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Edit Member Information</h6>
                    </div>
                    <div class="card-body">
                        <form action="edit.php?id=<?php echo $memberId; ?>" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <!-- Profile Image Section -->
                                <div class="col-md-3 text-center mb-4">
                                    <?php if (!empty($member['profile_image'])): ?>
                                        <img src="../uploads/members/<?php echo htmlspecialchars($member['profile_image']); ?>" alt="Profile" class="profile-preview" id="profilePreview">
                                    <?php else: ?>
                                        <img src="../assets/img/profile-placeholder.jpg" alt="Profile" class="profile-preview" id="profilePreview">
                                    <?php endif; ?>
                                    <div class="mt-3">
                                        <label for="profileImageInput" class="btn btn-outline-primary btn-sm">
                                            <i class="bi bi-camera"></i> Change Photo
                                        </label>
                                        <input type="file" id="profileImageInput" name="profile_image" accept="image/*" style="display: none;">
                                    </div>
                                </div>
                                
                                <div class="col-md-9">
                                    <div class="row">
                                        <!-- Personal Information -->
                                        <div class="col-12 mb-3">
                                            <h5>Personal Information</h5>
                                            <hr>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="first_name" class="form-label required-field">First Name</label>
                                            <input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo htmlspecialchars($member['first_name']); ?>" required>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="middle_name" class="form-label">Middle Name</label>
                                            <input type="text" class="form-control" id="middle_name" name="middle_name" value="<?php echo htmlspecialchars($member['middle_name'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="last_name" class="form-label required-field">Last Name</label>
                                            <input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo htmlspecialchars($member['last_name']); ?>" required>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="sex" class="form-label required-field">Sex</label>
                                            <select class="form-select" id="sex" name="sex" required>
                                                <option value="">Select Sex</option>
                                                <option value="Male" <?php echo $member['sex'] === 'Male' ? 'selected' : ''; ?>>Male</option>
                                                <option value="Female" <?php echo $member['sex'] === 'Female' ? 'selected' : ''; ?>>Female</option>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="dob" class="form-label">Date of Birth</label>
                                            <input type="date" class="form-control" id="dob" name="dob" value="<?php echo htmlspecialchars($member['dob'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="profession" class="form-label">Profession</label>
                                            <input type="text" class="form-control" id="profession" name="profession" value="<?php echo htmlspecialchars($member['profession'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label for="address" class="form-label">Residential Address</label>
                                            <textarea class="form-control" id="address" name="address" rows="2"><?php echo htmlspecialchars($member['address'] ?? ''); ?></textarea>
                                        </div>
                                        
                                        <!-- Contact Information -->
                                        <div class="col-12 mb-3 mt-3">
                                            <h5>Contact Information</h5>
                                            <hr>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="contact_number" class="form-label required-field">Contact Number</label>
                                            <input type="tel" class="form-control" id="contact_number" name="contact_number" value="<?php echo htmlspecialchars($member['contact_number']); ?>" required>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="email" class="form-label">Email Address</label>
                                            <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($member['email'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="emergency_contact_name" class="form-label">Emergency Contact Name</label>
                                            <input type="text" class="form-control" id="emergency_contact_name" name="emergency_contact_name" value="<?php echo htmlspecialchars($member['emergency_contact_name'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="emergency_contact_number" class="form-label">Emergency Contact Number</label>
                                            <input type="tel" class="form-control" id="emergency_contact_number" name="emergency_contact_number" value="<?php echo htmlspecialchars($member['emergency_contact_number'] ?? ''); ?>">
                                        </div>
                                        
                                        <!-- Choir Information -->
                                        <div class="col-12 mb-3 mt-3">
                                            <h5>Choir Information</h5>
                                            <hr>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="society_id" class="form-label required-field">Society</label>
                                            <select class="form-select" id="society_id" name="society_id" required>
                                                <option value="">Select Society</option>
                                                <?php foreach ($societies as $society): ?>
                                                    <option value="<?php echo $society['id']; ?>" <?php echo $member['society_id'] == $society['id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($society['name']); ?> 
                                                        (<?php echo htmlspecialchars($society['circuit_name']); ?>, 
                                                        <?php echo htmlspecialchars($society['diocese_name']); ?>)
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="part" class="form-label required-field">Voice Part</label>
                                            <select class="form-select" id="part" name="part" required>
                                                <option value="">Select Voice Part</option>
                                                <option value="Soprano" <?php echo $member['part'] === 'Soprano' ? 'selected' : ''; ?>>Soprano</option>
                                                <option value="Alto" <?php echo $member['part'] === 'Alto' ? 'selected' : ''; ?>>Alto</option>
                                                <option value="Tenor" <?php echo $member['part'] === 'Tenor' ? 'selected' : ''; ?>>Tenor</option>
                                                <option value="Bass" <?php echo $member['part'] === 'Bass' ? 'selected' : ''; ?>>Bass</option>
                                                <option value="Other" <?php echo $member['part'] === 'Other' ? 'selected' : ''; ?>>Other</option>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="part_other" class="form-label">Other Voice Part</label>
                                            <input type="text" class="form-control" id="part_other" name="part_other" value="<?php echo htmlspecialchars($member['part_other'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="role" class="form-label">Role</label>
                                            <select class="form-select" id="role" name="role">
                                                <option value="">Select Role</option>
                                                <option value="Singer" <?php echo $member['role'] === 'Singer' ? 'selected' : ''; ?>>Singer</option>
                                                <option value="Conductor" <?php echo $member['role'] === 'Conductor' ? 'selected' : ''; ?>>Conductor</option>
                                                <option value="Instrumentalist" <?php echo $member['role'] === 'Instrumentalist' ? 'selected' : ''; ?>>Instrumentalist</option>
                                                <option value="Other" <?php echo $member['role'] === 'Other' ? 'selected' : ''; ?>>Other</option>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="role_other" class="form-label">Other Role</label>
                                            <input type="text" class="form-control" id="role_other" name="role_other" value="<?php echo htmlspecialchars($member['role_other'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="executive_position" class="form-label">Leadership Position</label>
                                            <select class="form-select" id="executive_position" name="executive_position">
                                                <option value="">Select Leadership Position</option>
                                                <?php foreach ($positionGroups as $groupLabel => $positions): ?>
                                                    <?php if (count($positionGroups) > 1): ?>
                                                        <optgroup label="<?php echo htmlspecialchars($groupLabel); ?>">
                                                    <?php endif; ?>
                                                    <?php foreach ($positions as $position): ?>
                                                        <option value="<?php echo htmlspecialchars($position); ?>" <?php echo $member['executive_position'] === $position ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($position); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                    <?php if (count($positionGroups) > 1): ?>
                                                        </optgroup>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="executive_position_other" class="form-label">Other Executive Position</label>
                                            <input type="text" class="form-control" id="executive_position_other" name="executive_position_other" value="<?php echo htmlspecialchars($member['executive_position_other'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="membership_status" class="form-label">Membership Status</label>
                                            <select class="form-select" id="membership_status" name="membership_status">
                                                <option value="Active" <?php echo $member['membership_status'] === 'Active' ? 'selected' : ''; ?>>Active</option>
                                                <option value="Inactive" <?php echo $member['membership_status'] === 'Inactive' ? 'selected' : ''; ?>>Inactive</option>
                                                <option value="Distance Member" <?php echo $member['membership_status'] === 'Distance Member' ? 'selected' : ''; ?>>Distance Member</option>
                                            </select>
                                        </div>
                                        
                                        <!-- Personal Details -->
                                        <div class="col-12 mb-3 mt-3">
                                            <h5>Personal & Church Details</h5>
                                            <hr>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="marital_status" class="form-label">Marital Status</label>
                                            <select class="form-select" id="marital_status" name="marital_status">
                                                <option value="">Select Marital Status</option>
                                                <option value="Single" <?php echo $member['marital_status'] === 'Single' ? 'selected' : ''; ?>>Single</option>
                                                <option value="Married" <?php echo $member['marital_status'] === 'Married' ? 'selected' : ''; ?>>Married</option>
                                                <option value="Divorced" <?php echo $member['marital_status'] === 'Divorced' ? 'selected' : ''; ?>>Divorced</option>
                                                <option value="Widowed" <?php echo $member['marital_status'] === 'Widowed' ? 'selected' : ''; ?>>Widowed</option>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="spouse_name" class="form-label">Spouse Name</label>
                                            <input type="text" class="form-control" id="spouse_name" name="spouse_name" value="<?php echo htmlspecialchars($member['spouse_name'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="education_level" class="form-label">Education Level</label>
                                            <select class="form-select" id="education_level" name="education_level">
                                                <option value="">Select Education Level</option>
                                                <option value="Primary" <?php echo $member['education_level'] === 'Primary' ? 'selected' : ''; ?>>Primary</option>
                                                <option value="Secondary" <?php echo $member['education_level'] === 'Secondary' ? 'selected' : ''; ?>>Secondary</option>
                                                <option value="Tertiary" <?php echo $member['education_level'] === 'Tertiary' ? 'selected' : ''; ?>>Tertiary</option>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="church_role" class="form-label">Church Role</label>
                                            <select class="form-select" id="church_role" name="church_role">
                                                <option value="">Select Church Role</option>
                                                <option value="Member" <?php echo $member['church_role'] === 'Member' ? 'selected' : ''; ?>>Member</option>
                                                <option value="Deacon" <?php echo $member['church_role'] === 'Deacon' ? 'selected' : ''; ?>>Deacon</option>
                                                <option value="Elder" <?php echo $member['church_role'] === 'Elder' ? 'selected' : ''; ?>>Elder</option>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="other_church_role" class="form-label">Other Church Role</label>
                                            <input type="text" class="form-control" id="other_church_role" name="other_church_role" value="<?php echo htmlspecialchars($member['other_church_role'] ?? ''); ?>">
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="membership_type" class="form-label">Membership Type</label>
                                            <input type="text" class="form-control" id="membership_type" name="membership_type" value="<?php echo htmlspecialchars($member['membership_type'] ?? 'Regular'); ?>">
                                        </div>
                                        
                                        <!-- Church Status -->
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Baptized</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" id="baptized_yes" name="baptized" value="yes" <?php echo $member['baptized'] === 'yes' ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="baptized_yes">Yes</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" id="baptized_no" name="baptized" value="no" <?php echo $member['baptized'] === 'no' ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="baptized_no">No</label>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Confirmed</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" id="confirmed_yes" name="confirmed" value="yes" <?php echo $member['confirmed'] === 'yes' ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="confirmed_yes">Yes</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" id="confirmed_no" name="confirmed" value="no" <?php echo $member['confirmed'] === 'no' ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="confirmed_no">No</label>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Communicant</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" id="communicant_yes" name="communicant" value="yes" <?php echo $member['communicant'] === 'yes' ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="communicant_yes">Yes</label>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" id="communicant_no" name="communicant" value="no" <?php echo $member['communicant'] === 'no' ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="communicant_no">No</label>
                                            </div>
                                        </div>
                                        
                                        <!-- Musical Information -->
                                        <div class="col-12 mb-3 mt-3">
                                            <h5>Musical Information</h5>
                                            <hr>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="musical_background" class="form-label">Musical Background</label>
                                            <textarea class="form-control" id="musical_background" name="musical_background" rows="2"><?php echo htmlspecialchars($member['musical_background'] ?? ''); ?></textarea>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="instruments_played" class="form-label">Instruments Played</label>
                                            <textarea class="form-control" id="instruments_played" name="instruments_played" rows="2"><?php echo htmlspecialchars($member['instruments_played'] ?? ''); ?></textarea>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label for="musical_skill_assessment" class="form-label">Musical Skill Assessment</label>
                                            <textarea class="form-control" id="musical_skill_assessment" name="musical_skill_assessment" rows="2"><?php echo htmlspecialchars($member['musical_skill_assessment'] ?? ''); ?></textarea>
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Circuit Model Choir Member</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="circuit_model_choir_member" name="circuit_model_choir_member" <?php echo $member['circuit_model_choir_member'] == 1 ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="circuit_model_choir_member">Yes</label>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Diocesan Model Choir Member</label>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="diocesan_model_choir_member" name="diocesan_model_choir_member" <?php echo $member['diocesan_model_choir_member'] == 1 ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="diocesan_model_choir_member">Yes</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-12 mt-4">
                                    <hr>
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <button type="submit" class="btn btn-primary">
                                                <i class="bi bi-save"></i> Save Changes
                                            </button>
                                            <a href="list.php" class="btn btn-secondary">
                                                <i class="bi bi-x-circle"></i> Cancel
                                            </a>
                                        </div>
                                        <div>
                                            <a href="view.php?id=<?php echo $memberId; ?>" class="btn btn-info">
                                                <i class="bi bi-eye"></i> View Profile
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Preview profile image before upload
            $("#profileImageInput").change(function() {
                if (this.files && this.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#profilePreview').attr('src', e.target.result);
                    }
                    reader.readAsDataURL(this.files[0]);
                }
            });
        });
    </script>
</body>
</html>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Preview profile image before upload
            $("#profileImageInput").change(function() {
                if (this.files && this.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#profilePreview').attr('src', e.target.result);
                    }
                    reader.readAsDataURL(this.files[0]);
                }
            });
        });
    </script>
</body>
</html>
