<?php
/**
 * Member Registration 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();

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

// For society roles, ensure they have a society_id in their session
$societyRoles = ['society_secretary', 'society_treasurer', 'choirmaster'];
$userRole = $_SESSION['role'] ?? '';
$userSocietyId = $_SESSION['society_id'] ?? null;

if (in_array($userRole, $societyRoles) && empty($userSocietyId)) {
    header("Location: ../index.php?error=no_society_assigned");
    exit;
}

// Initialize variables
$success = false;
$error = '';
$formData = [
    'first_name' => '',
    'middle_name' => '',
    'surname' => '',
    'gender' => '',
    'date_of_birth' => '',
    'contact_number_1' => '',
    'contact_number_2' => '',
    'email' => '',
    'address' => '',
    'occupation' => '',
    'voice_part' => '',
    'join_date' => '',
    'society_id' => '',
    'status' => 'active',
    'executive_position' => '',
    'executive_position_other' => '',
    // Additional fields
    'marital_status' => '',
    'spouse_name' => '',
    'emergency_contact_name' => '',
    'emergency_contact_number' => '',
    'musical_background' => '',
    'instruments_played' => '',
    'education_level' => '',
    'church_role' => '',
    'baptized' => 'yes',
    'confirmed' => 'yes',
    'communicant' => 'yes',
    'membership_type' => 'Regular'
];

// Get list of societies for dropdown - filtered by user's access level
if (hasRole(['admin', 'manager'])) {
    // Admin and manager can see all societies
    $societies = fetchRows("SELECT id, name FROM societies ORDER BY name");
} else {
    $userRole = $_SESSION['role'] ?? '';
    $userSocietyId = $_SESSION['society_id'] ?? null;
    $userCircuitId = $_SESSION['circuit_id'] ?? null;
    $userDioceseId = $_SESSION['diocese_id'] ?? null;
    
    $societyRoles = ['choirmaster', 'society_secretary', 'society_treasurer'];
    $circuitRoles = ['circuit_secretary', 'circuit_treasurer'];
    $dioceseRoles = ['diocesan_secretary', 'diocesan_treasurer'];
    
    if (in_array($userRole, $societyRoles) && !empty($userSocietyId)) {
        // Society-level roles can only see their society
        $societies = fetchRows("SELECT id, name FROM societies WHERE id = ? ORDER BY name", [$userSocietyId]);
        
        // Pre-select the society in the form
        $formData['society_id'] = $userSocietyId;
    } elseif (in_array($userRole, $circuitRoles) && !empty($userCircuitId)) {
        // Circuit-level roles can see societies in their circuit
        $societies = fetchRows("SELECT id, name FROM societies WHERE circuit_id = ? ORDER BY name", [$userCircuitId]);
    } elseif (in_array($userRole, $dioceseRoles) && !empty($userDioceseId)) {
        // Diocese-level roles can see societies in their diocese
        $societies = fetchRows("SELECT s.id, s.name 
                              FROM societies s 
                              JOIN circuits c ON s.circuit_id = c.id 
                              WHERE c.diocese_id = ? 
                              ORDER BY s.name", [$userDioceseId]);
    } else {
        // Default - no societies
        $societies = [];
    }
}

// Get list of voice parts for dropdown
$voiceParts = ['Soprano', 'Alto', 'Tenor', 'Bass'];

// 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 available leadership position groups for 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 {
    // Default to society level for society officers (choirmaster, society_secretary, etc.)
    $addPositionGroup('society', 'Society Leadership Positions');
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    logMemberInfo("Member registration form submitted");
    
    // Capture form data
    foreach ($formData as $key => $value) {
        if (isset($_POST[$key])) {
            $formData[$key] = trim($_POST[$key]);
        }
    }
    
    // Validate required fields
    $requiredFields = ['first_name', 'surname', 'gender', 'contact_number_1', 'voice_part', 'society_id'];
    $missingFields = [];
    foreach ($requiredFields as $field) {
        if (empty($formData[$field])) {
            $missingFields[] = str_replace('_', ' ', ucfirst($field));
        }
    }
    
    if (!empty($missingFields)) {
        $error = "Please fill in the following required fields: " . implode(', ', $missingFields);
        logMemberWarning("Member registration validation failed - missing required fields", ['missing_fields' => $missingFields]);
    }
    
    // Validate contact number format
    if (!empty($formData['contact_number_1']) && !preg_match('/^[0-9+\-\s()]{7,15}$/', $formData['contact_number_1'])) {
        $error = "Please enter a valid contact number.";
        logMemberWarning("Member registration validation failed - invalid contact number", ['contact_number' => $formData['contact_number_1']]);
    }
    
    // Validate email if provided
    if (!empty($formData['email']) && !filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address.";
        logMemberWarning("Member registration validation failed - invalid email", ['email' => $formData['email']]);
    }
    
    // Validate society access if not admin/manager
    if (!hasRole(['admin', 'manager']) && !empty($formData['society_id'])) {
        $societyId = (int)$formData['society_id'];
        if (!hasEntityAccess('society', $societyId)) {
            $error = "You don't have permission to register members for this society.";
        }
    }
    
    // If no errors, proceed with registration
    if (empty($error)) {
        // Generate member ID for internal use
        $memberIdPrefix = 'MEM';
        $memberIdSuffix = date('Ymd') . rand(1000, 9999);
        $memberId = $memberIdPrefix . $memberIdSuffix;
        
        // Set default date for dob if empty (use 1900-01-01 as a placeholder)
        $dob = $formData['date_of_birth'] ? $formData['date_of_birth'] : '1900-01-01';
        
        logMemberDebug("Processing member registration with data", [
            'first_name' => $formData['first_name'],
            'last_name' => $formData['surname'],
            'gender' => $formData['gender'],
            'dob' => $dob,
            'society_id' => $formData['society_id']
        ]);
        
        // Prepare query - updated to match actual database schema with additional fields
        $query = "INSERT INTO members (
                    first_name, middle_name, last_name, sex,
                    dob, contact_number, email,
                    address, profession, part, role, executive_position, executive_position_other, society_id,
                    membership_status, created_by, created_at,
                    marital_status, spouse_name, emergency_contact_name,
                    emergency_contact_number, musical_background, instruments_played,
                    education_level, church_role, baptized, confirmed,
                    communicant, membership_type
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
                    NOW(),
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
                );";
        
        $params = [
            $formData['first_name'],
            $formData['middle_name'],
            $formData['surname'],  // surname maps to last_name
            $formData['gender'],   // gender maps to sex
            $dob,                  // Use the default date or the provided one
            $formData['contact_number_1'],
            $formData['email'] ?: null,
            $formData['address'] ?: null,
            $formData['occupation'] ?: '',  // Use empty string instead of null for profession
            $formData['voice_part'],  // voice_part maps to part
            'Singer', // Default role
            !empty($formData['executive_position']) ? $formData['executive_position'] : null,
            !empty($formData['executive_position_other']) ? $formData['executive_position_other'] : null,
            $formData['society_id'],
            $formData['status'] === 'active' ? 'Active' : 'Inactive', // Convert status to match enum
            $_SESSION['user_id'],
            // Additional fields
            $formData['marital_status'] ?: null,
            $formData['spouse_name'] ?: null,
            $formData['emergency_contact_name'] ?: null,
            $formData['emergency_contact_number'] ?: null,
            $formData['musical_background'] ?: null,
            $formData['instruments_played'] ?: null,
            $formData['education_level'] ?: null,
            $formData['church_role'] ?: null,
            $formData['baptized'],
            $formData['confirmed'],
            $formData['communicant'],
            $formData['membership_type']
        ];
        
        try {
            // Log the query and parameters for debugging
            logMemberDebug("Executing member insert query", [
                'query' => $query,
                'params' => $params
            ]);
            
            // Execute the query
            $result = executeQuery($query, $params);
            
            if ($result) {
                // Registration successful
                $success = true;
                $newMemberId = $conn->insert_id;
                
                // Log successful registration
                logMemberInfo("Member registration successful", [
                    'db_id' => $newMemberId,
                    'member_id' => $memberId,
                    'name' => $formData['first_name'] . ' ' . $formData['surname'],
                    'society_id' => $formData['society_id']
                ]);
                
                // Handle optional profile image upload
                if (isset($_FILES['profile_image']) && isset($_FILES['profile_image']['tmp_name']) && $_FILES['profile_image']['size'] > 0) {
                    $uploadDir = __DIR__ . '/../uploads/members/';
                    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)) {
                        $newFileName = 'member_' . $newMemberId . '_' . time() . '.' . $fileExtension;
                        $targetFilePath = $uploadDir . $newFileName;
                        if (move_uploaded_file($_FILES['profile_image']['tmp_name'], $targetFilePath)) {
                            // Save file name (not full path) in DB
                            $updateOk = executeQuery("UPDATE members SET profile_image = ? WHERE id = ?", [$newFileName, $newMemberId]);
                            if ($updateOk) {
                                logMemberInfo("Profile image uploaded for new member", [
                                    'member_db_id' => $newMemberId,
                                    'file' => $newFileName
                                ]);
                            } else {
                                logMemberError("Failed to update profile image after upload", [
                                    'member_db_id' => $newMemberId,
                                    'db_error' => $conn->error
                                ]);
                            }
                        } else {
                            logMemberError("Failed to move uploaded profile image for new member", [
                                'member_db_id' => $newMemberId,
                                'error' => error_get_last()
                            ]);
                        }
                    } else {
                        logMemberWarning("Invalid profile image extension on registration", [
                            'ext' => $fileExtension,
                            'member_db_id' => $newMemberId
                        ]);
                    }
                }
                
                // Reset form data
                foreach ($formData as $key => $value) {
                    $formData[$key] = '';
                }
                $formData['status'] = 'active';
                $formData['executive_position'] = '';
                $formData['executive_position_other'] = '';
                
                // If society-level user, pre-select their society again
                if (!hasRole(['admin', 'manager'])) {
                    $userRole = $_SESSION['role'] ?? '';
                    $userSocietyId = $_SESSION['society_id'] ?? null;
                    $societyRoles = ['choirmaster', 'society_secretary', 'society_treasurer'];
                    
                    if (in_array($userRole, $societyRoles) && !empty($userSocietyId)) {
                        $formData['society_id'] = $userSocietyId;
                    }
                }
            } else {
                // Get the specific database error
                $dbError = $conn->error;
                
                // Log failed registration with detailed error
                logMemberError("Member registration failed", [
                    'member_id' => $memberId,
                    'name' => $formData['first_name'] . ' ' . $formData['surname'],
                    'society_id' => $formData['society_id'],
                    'db_error' => $dbError
                ]);
                
                // Provide more specific error message based on common issues
                if (strpos($dbError, 'Duplicate entry') !== false) {
                    $error = "This member already exists in the database.";
                } else if (strpos($dbError, 'cannot be null') !== false) {
                    $error = "A required field is missing. Please check your form and try again.";
                } else {
                    $error = "Failed to register member. Database error: " . $dbError;
                }
            }
        } catch (Exception $e) {
            $error = "System error: " . $e->getMessage();
            logError("Unhandled exception in member registration", [
                'exception' => $e->getMessage(),
                'code' => $e->getCode(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }
}

// 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>Member Registration - 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>
        .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">Member Registration</h1>
                    <a href="list.php" class="btn btn-secondary">
                        <i class="bi bi-arrow-left"></i> Back to Members List
                    </a>
                </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 registered successfully!
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle-fill me-2"></i> <?php echo $error; ?>
                    <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">Member Registration Form</h6>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="" enctype="multipart/form-data">
                            <div class="row">
                                <!-- Personal Information -->
                                <div class="col-md-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($formData['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($formData['middle_name']); ?>">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="surname" class="form-label required-field">Surname</label>
                                    <input type="text" class="form-control" id="surname" name="surname" value="<?php echo htmlspecialchars($formData['surname']); ?>" required>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="gender" class="form-label required-field">Gender</label>
                                    <select class="form-select" id="gender" name="gender" required>
                                        <option value="" <?php echo empty($formData['gender']) ? 'selected' : ''; ?>>Select Gender</option>
                                        <option value="Male" <?php echo $formData['gender'] === 'Male' ? 'selected' : ''; ?>>Male</option>
                                        <option value="Female" <?php echo $formData['gender'] === 'Female' ? 'selected' : ''; ?>>Female</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="date_of_birth" class="form-label">Date of Birth</label>
                                    <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" value="<?php echo htmlspecialchars($formData['date_of_birth']); ?>">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="occupation" class="form-label">Occupation</label>
                                    <input type="text" class="form-control" id="occupation" name="occupation" value="<?php echo htmlspecialchars($formData['occupation']); ?>">
                                </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($formData['address']); ?></textarea>
                                </div>

                                <!-- Profile Photo -->
                                <div class="col-md-6 mb-3">
                                    <label for="profile_image" class="form-label">Profile Photo</label>
                                    <input type="file" class="form-control" id="profile_image" name="profile_image" accept="image/*">
                                    <div class="form-text">Optional. JPG, JPEG, PNG, or GIF.</div>
                                </div>
                                
                                <!-- Contact Information -->
                                <div class="col-md-12 mb-3 mt-3">
                                    <h5>Contact Information</h5>
                                    <hr>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="contact_number_1" class="form-label required-field">Primary Contact Number</label>
                                    <input type="tel" class="form-control" id="contact_number_1" name="contact_number_1" value="<?php echo htmlspecialchars($formData['contact_number_1']); ?>" required>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="contact_number_2" class="form-label">Alternative Contact Number</label>
                                    <input type="tel" class="form-control" id="contact_number_2" name="contact_number_2" value="<?php echo htmlspecialchars($formData['contact_number_2']); ?>">
                                </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($formData['email']); ?>">
                                </div>
                                
                                <!-- Choir Information -->
                                <div class="col-md-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="" <?php echo empty($formData['society_id']) ? 'selected' : ''; ?>>Select Society</option>
                                        <?php foreach ($societies as $society): ?>
                                            <option value="<?php echo $society['id']; ?>" <?php echo $formData['society_id'] == $society['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($society['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="voice_part" class="form-label required-field">Voice Part</label>
                                    <select class="form-select" id="voice_part" name="voice_part" required>
                                        <option value="" <?php echo empty($formData['voice_part']) ? 'selected' : ''; ?>>Select Voice Part</option>
                                        <?php foreach ($voiceParts as $voicePart): ?>
                                            <option value="<?php echo $voicePart; ?>" <?php echo $formData['voice_part'] === $voicePart ? 'selected' : ''; ?>>
                                                <?php echo $voicePart; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <?php if (!empty($positionGroups)): ?>
                                <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="" <?php echo empty($formData['executive_position']) ? 'selected' : ''; ?>>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 $formData['executive_position'] === $position ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($position); ?>
                                                </option>
                                            <?php endforeach; ?>
                                            <?php if (count($positionGroups) > 1): ?>
                                                </optgroup>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <?php endif; ?>
                                <div class="col-md-4 mb-3">
                                    <label for="executive_position_other" class="form-label">Other Leadership Position</label>
                                    <input type="text" class="form-control" id="executive_position_other" name="executive_position_other" value="<?php echo htmlspecialchars($formData['executive_position_other']); ?>" placeholder="Specify if not listed">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="join_date" class="form-label">Join Date</label>
                                    <input type="date" class="form-control" id="join_date" name="join_date" value="<?php echo htmlspecialchars($formData['join_date']); ?>">
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="active" <?php echo $formData['status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                                        <option value="inactive" <?php echo $formData['status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                    </select>
                                </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="" <?php echo empty($formData['marital_status']) ? 'selected' : ''; ?>>Select Marital Status</option>
                                        <option value="Single" <?php echo $formData['marital_status'] === 'Single' ? 'selected' : ''; ?>>Single</option>
                                        <option value="Married" <?php echo $formData['marital_status'] === 'Married' ? 'selected' : ''; ?>>Married</option>
                                        <option value="Divorced" <?php echo $formData['marital_status'] === 'Divorced' ? 'selected' : ''; ?>>Divorced</option>
                                        <option value="Widowed" <?php echo $formData['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($formData['spouse_name']); ?>">
                                </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($formData['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($formData['emergency_contact_number']); ?>">
                                </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($formData['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($formData['instruments_played']); ?></textarea>
                                </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="" <?php echo empty($formData['education_level']) ? 'selected' : ''; ?>>Select Education Level</option>
                                        <option value="Primary" <?php echo $formData['education_level'] === 'Primary' ? 'selected' : ''; ?>>Primary</option>
                                        <option value="Secondary" <?php echo $formData['education_level'] === 'Secondary' ? 'selected' : ''; ?>>Secondary</option>
                                        <option value="Tertiary" <?php echo $formData['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="" <?php echo empty($formData['church_role']) ? 'selected' : ''; ?>>Select Church Role</option>
                                        <option value="Member" <?php echo $formData['church_role'] === 'Member' ? 'selected' : ''; ?>>Member</option>
                                        <option value="Elder" <?php echo $formData['church_role'] === 'Elder' ? 'selected' : ''; ?>>Elder</option>
                                        <option value="Deacon" <?php echo $formData['church_role'] === 'Deacon' ? 'selected' : ''; ?>>Deacon</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="baptized" class="form-label">Baptized</label>
                                    <select class="form-select" id="baptized" name="baptized">
                                        <option value="yes" <?php echo $formData['baptized'] === 'yes' ? 'selected' : ''; ?>>Yes</option>
                                        <option value="no" <?php echo $formData['baptized'] === 'no' ? 'selected' : ''; ?>>No</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="confirmed" class="form-label">Confirmed</label>
                                    <select class="form-select" id="confirmed" name="confirmed">
                                        <option value="yes" <?php echo $formData['confirmed'] === 'yes' ? 'selected' : ''; ?>>Yes</option>
                                        <option value="no" <?php echo $formData['confirmed'] === 'no' ? 'selected' : ''; ?>>No</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="communicant" class="form-label">Communicant</label>
                                    <select class="form-select" id="communicant" name="communicant">
                                        <option value="yes" <?php echo $formData['communicant'] === 'yes' ? 'selected' : ''; ?>>Yes</option>
                                        <option value="no" <?php echo $formData['communicant'] === 'no' ? 'selected' : ''; ?>>No</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="membership_type" class="form-label">Membership Type</label>
                                    <select class="form-select" id="membership_type" name="membership_type">
                                        <option value="Regular" <?php echo $formData['membership_type'] === 'Regular' ? 'selected' : ''; ?>>Regular</option>
                                        <option value="Associate" <?php echo $formData['membership_type'] === 'Associate' ? 'selected' : ''; ?>>Associate</option>
                                    </select>
                                </div>
                                
                                <div class="col-12 mt-4">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-save"></i> Register Member
                                    </button>
                                    <a href="list.php" class="btn btn-secondary">
                                        <i class="bi bi-x-circle"></i> Cancel
                                    </a>
                                </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() {
            // Add any custom JavaScript for the form here
        });
    </script>
</body>
</html>
