<?php
// pages/member_form.php
requireRole('any'); // Coordinators/Admins

$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
$member = null;
$error = null;
$success = null;

// Default Data Structures
$default_experiences = ['salvation' => null, 'sanctification' => null, 'baptism_holy_ghost' => null, 'water_baptism' => null];
$default_nok = ['name' => '', 'relationship' => '', 'address' => '', 'phone' => '', 'email' => ''];
$default_employment = ['business_name' => '', 'job_title' => '', 'business_address' => '', 'date_joined' => '', 'qualifications' => '', 'skills' => ''];
$default_referees = [
    ['name' => '', 'relationship' => '', 'address' => '', 'phone' => '', 'email' => ''],
    ['name' => '', 'relationship' => '', 'address' => '', 'phone' => '', 'email' => '']
];
// Past Assignments - Fixed 3 rows for simplicity
$default_assignments = [
    ['role' => '', 'location' => '', 'dates' => '', 'pastor' => ''],
    ['role' => '', 'location' => '', 'dates' => '', 'pastor' => ''],
    ['role' => '', 'location' => '', 'dates' => '', 'pastor' => '']
];

if ($id) {
    if ($_SESSION['user_role'] === 'member' && $id !== $_SESSION['member_id']) {
        redirect('index.php?page=dashboard&error=unauthorized_edit');
    }
    $stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
    $stmt->execute([$id]);
    $member = $stmt->fetch();
    if (!$member) redirect('index.php?page=members');
} else {
    if (!hasRole('roster_manager')) redirect('index.php?page=members&error=unauthorized_add');
}

// Fetch Options
$unit_options = $pdo->query("SELECT value FROM settings_options WHERE category='units' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);
$role_options = $pdo->query("SELECT value FROM settings_options WHERE category='unit_roles' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);
$branch_options = $pdo->query("SELECT value FROM settings_options WHERE category='branches' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);
$dept_options = $pdo->query("SELECT value FROM settings_options WHERE category='member_departments' AND is_active=1 ORDER BY display_order")->fetchAll(PDO::FETCH_COLUMN);

// Handle POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. Basic Fields
    $full_name = clean_input($_POST['full_name']);
    $phone = clean_input($_POST['phone']);
    $whatsapp = clean_input($_POST['whatsapp']);
    $email = clean_input($_POST['email']);
    $address = clean_input($_POST['address']);
    $dob = !empty($_POST['dob']) ? $_POST['dob'] : null;
    $gender = clean_input($_POST['gender']);
    $state_origin = clean_input($_POST['state_origin']);
    $marital_status = clean_input($_POST['marital_status']);
    $wedding_anniversary = !empty($_POST['wedding_anniversary']) ? $_POST['wedding_anniversary'] : null;
    
    // 2. Church Info
    $status = clean_input($_POST['status']);
    $category = clean_input($_POST['category']);
    $unit = clean_input($_POST['unit']);
    $unit_role = clean_input($_POST['unit_role']);
    $department = clean_input($_POST['department']);
    $branch = clean_input($_POST['branch']);
    $date_joined = !empty($_POST['date_joined']) ? $_POST['date_joined'] : null;

    // 3. Complex JSON Fields
    // Experiences
    $experiences = $default_experiences;
    foreach ($experiences as $k => $v) $experiences[$k] = !empty($_POST['exp_'.$k]) ? $_POST['exp_'.$k] : null;
    
    // Next of Kin
    $nok = [
        'name' => clean_input($_POST['nok_name']),
        'relationship' => clean_input($_POST['nok_relationship']),
        'address' => clean_input($_POST['nok_address']),
        'phone' => clean_input($_POST['nok_phone']),
        'email' => clean_input($_POST['nok_email'])
    ];
    
    // Employment
    $employment = [
        'business_name' => clean_input($_POST['emp_business_name']),
        'job_title' => clean_input($_POST['emp_job_title']),
        'business_address' => clean_input($_POST['emp_business_address']),
        'date_joined' => !empty($_POST['emp_date_joined']) ? $_POST['emp_date_joined'] : null,
        'qualifications' => clean_input($_POST['emp_qualifications']),
        'skills' => clean_input($_POST['emp_skills'])
    ];
    
    // Referees
    $referees = [];
    for ($i=0; $i<2; $i++) {
        $referees[] = [
            'name' => clean_input($_POST['ref_name'][$i]),
            'relationship' => clean_input($_POST['ref_relationship'][$i]),
            'address' => clean_input($_POST['ref_address'][$i]),
            'phone' => clean_input($_POST['ref_phone'][$i]),
            'email' => clean_input($_POST['ref_email'][$i]),
        ];
    }
    
    // Past Assignments
    $past_assignments = [];
    for ($i=0; $i<3; $i++) {
        if (!empty($_POST['assign_role'][$i])) { // Only save if role is set
            $past_assignments[] = [
                'role' => clean_input($_POST['assign_role'][$i]),
                'location' => clean_input($_POST['assign_location'][$i]),
                'dates' => clean_input($_POST['assign_dates'][$i]),
                'pastor' => clean_input($_POST['assign_pastor'][$i]),
            ];
        }
    }

    if (empty($full_name)) {
        $error = "Full Name is required";
    } else {
        $params = [
            $full_name, $phone, $whatsapp, $email, $address, 
            $dob, $gender, $state_origin, $marital_status, $wedding_anniversary,
            json_encode($nok), json_encode($employment), json_encode($experiences),
            json_encode($referees), json_encode($past_assignments),
            $status, $category, $unit, $unit_role, $department, $branch, $date_joined
        ];

        if ($id) {
            $sql = "UPDATE members SET 
                full_name=?, phone=?, whatsapp=?, email=?, address=?, 
                dob=?, gender=?, state_origin=?, marital_status=?, wedding_anniversary=?,
                next_of_kin=?, employment=?, experiences=?, 
                referees=?, past_assignments=?,
                status=?, category=?, unit=?, unit_role=?, department=?, branch=?, date_joined=? 
                WHERE id=?";
            $params[] = $id;
        } else {
            $sql = "INSERT INTO members (
                full_name, phone, whatsapp, email, address, 
                dob, gender, state_origin, marital_status, wedding_anniversary,
                next_of_kin, employment, experiences, 
                referees, past_assignments,
                status, category, unit, unit_role, department, branch, date_joined
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        }
        
        try {
            $stmt = $pdo->prepare($sql);
            if ($stmt->execute($params)) {
                $success = "Member saved successfully";
                if (!$id) $id = $pdo->lastInsertId();
                // Refresh
                $stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
                $stmt->execute([$id]);
                $member = $stmt->fetch();
            } else {
                $error = "Failed to save member";
            }
        } catch (PDOException $e) {
            $error = "DB Error: " . $e->getMessage();
        }
    }
}

// Decode Data for Display
$current_exp = $member ? json_decode($member['experiences'] ?? '{}', true) : $default_experiences;
$current_nok = $member ? json_decode($member['next_of_kin'] ?? '{}', true) : $default_nok;
$current_emp = $member ? json_decode($member['employment'] ?? '{}', true) : $default_employment;
$current_ref = $member ? json_decode($member['referees'] ?? '[]', true) : $default_referees;
if (empty($current_ref)) $current_ref = $default_referees;
$current_assign = $member ? json_decode($member['past_assignments'] ?? '[]', true) : [];
// Pad assignments to 3 rows
while (count($current_assign) < 3) $current_assign[] = ['role'=>'','location'=>'','dates'=>'','pastor'=>''];

?>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <h1><?php echo $id ? 'Edit Member' : 'Add New Member'; ?></h1>
    <a href="index.php?page=members" class="btn" style="background-color: #666;">&laquo; Back to List</a>
</div>

<?php if ($error): ?> <div class="alert alert-danger"><?php echo $error; ?></div> <?php endif; ?>
<?php if ($success): ?> <div class="alert alert-success"><?php echo $success; ?></div> <?php endif; ?>

<form method="POST">
    <!-- A. Personal Details -->
    <div class="card" style="margin-bottom: 20px;">
        <h3>A. Personal Details / Biodata</h3>
        <div class="dashboard-grid">
            <div style="grid-column: span 1;">
                <div class="form-group"><label>Full Name *</label><input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($member['full_name']??''); ?>" required></div>
                <div class="form-group"><label>Address</label><textarea name="address" class="form-control"><?php echo htmlspecialchars($member['address']??''); ?></textarea></div>
                <div class="form-group"><label>State / Country of Origin</label><input type="text" name="state_origin" class="form-control" value="<?php echo htmlspecialchars($member['state_origin']??''); ?>"></div>
            </div>
            
            <div style="grid-column: span 1;">
                 <div style="display: flex; gap: 10px;">
                    <div class="form-group" style="flex:1"><label>Phone</label><input type="text" name="phone" class="form-control" value="<?php echo htmlspecialchars($member['phone']??''); ?>"></div>
                    <div class="form-group" style="flex:1"><label>WhatsApp</label><input type="text" name="whatsapp" class="form-control" value="<?php echo htmlspecialchars($member['whatsapp']??''); ?>"></div>
                </div>
                <div class="form-group"><label>Email</label><input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($member['email']??''); ?>"></div>
                <div style="display: flex; gap: 10px;">
                    <div class="form-group" style="flex:1"><label>Date of Birth</label><input type="date" name="dob" class="form-control" value="<?php echo htmlspecialchars($member['dob']??''); ?>"></div>
                    <div class="form-group" style="flex:1"><label>Gender</label>
                        <select name="gender" class="form-control">
                            <option value="">Select</option>
                            <option value="Male" <?php if(($member['gender']??'')=='Male') echo 'selected'; ?>>Male</option>
                            <option value="Female" <?php if(($member['gender']??'')=='Female') echo 'selected'; ?>>Female</option>
                        </select>
                    </div>
                </div>
                 <div style="display: flex; gap: 10px;">
                    <div class="form-group" style="flex:1"><label>Marital Status</label>
                        <select name="marital_status" class="form-control">
                            <option value="">Select</option>
                            <option value="Single" <?php if(($member['marital_status']??'')=='Single') echo 'selected'; ?>>Single</option>
                            <option value="Married" <?php if(($member['marital_status']??'')=='Married') echo 'selected'; ?>>Married</option>
                            <option value="Separated" <?php if(($member['marital_status']??'')=='Separated') echo 'selected'; ?>>Separated</option>
                            <option value="Widowed" <?php if(($member['marital_status']??'')=='Widowed') echo 'selected'; ?>>Widowed</option>
                            <option value="Divorced" <?php if(($member['marital_status']??'')=='Divorced') echo 'selected'; ?>>Divorced</option>
                        </select>
                    </div>
                    <div class="form-group" style="flex:1"><label>Wedding Anniversary</label><input type="date" name="wedding_anniversary" class="form-control" value="<?php echo htmlspecialchars($member['wedding_anniversary']??''); ?>"></div>
                </div>
            </div>
        </div>
        
        <!-- Next of Kin -->
        <h4 style="border-bottom: 1px solid #444; padding-bottom: 5px; margin-top: 10px;">Next of Kin</h4>
        <div class="dashboard-grid">
             <div style="grid-column: span 1;">
                <div class="form-group"><label>Name</label><input type="text" name="nok_name" class="form-control" value="<?php echo htmlspecialchars($current_nok['name']??''); ?>"></div>
                <div class="form-group"><label>Relationship</label><input type="text" name="nok_relationship" class="form-control" value="<?php echo htmlspecialchars($current_nok['relationship']??''); ?>"></div>
                <div class="form-group"><label>Address</label><input type="text" name="nok_address" class="form-control" value="<?php echo htmlspecialchars($current_nok['address']??''); ?>"></div>
             </div>
             <div style="grid-column: span 1;">
                <div class="form-group"><label>Phone</label><input type="text" name="nok_phone" class="form-control" value="<?php echo htmlspecialchars($current_nok['phone']??''); ?>"></div>
                <div class="form-group"><label>Email</label><input type="email" name="nok_email" class="form-control" value="<?php echo htmlspecialchars($current_nok['email']??''); ?>"></div>
             </div>
        </div>
    </div>

    <!-- B. Employment / Education -->
    <div class="card" style="margin-bottom: 20px;">
        <h3>B. Work / Education</h3>
        <div class="dashboard-grid">
            <div style="grid-column: span 1;">
                <div class="form-group"><label>Business/School Name</label><input type="text" name="emp_business_name" class="form-control" value="<?php echo htmlspecialchars($current_emp['business_name']??''); ?>"></div>
                <div class="form-group"><label>Job Title/Course</label><input type="text" name="emp_job_title" class="form-control" value="<?php echo htmlspecialchars($current_emp['job_title']??''); ?>"></div>
                <div class="form-group"><label>Address</label><input type="text" name="emp_business_address" class="form-control" value="<?php echo htmlspecialchars($current_emp['business_address']??''); ?>"></div>
            </div>
            <div style="grid-column: span 1;">
                <div class="form-group"><label>Date Joined</label><input type="date" name="emp_date_joined" class="form-control" value="<?php echo htmlspecialchars($current_emp['date_joined']??''); ?>"></div>
                <div class="form-group"><label>Qualifications</label><input type="text" name="emp_qualifications" class="form-control" value="<?php echo htmlspecialchars($current_emp['qualifications']??''); ?>"></div>
                 <div class="form-group"><label>Skills / Abilities</label><textarea name="emp_skills" class="form-control"><?php echo htmlspecialchars($current_emp['skills']??''); ?></textarea></div>
            </div>
        </div>
    </div>

    <!-- C. Spiritual Information -->
    <div class="card" style="margin-bottom: 20px;">
        <h3>C. Spiritual Information</h3>
        <div class="dashboard-grid">
            <div style="grid-column: span 1;">
                <div class="form-group"><label>Salvation Date</label><input type="date" name="exp_salvation" class="form-control" value="<?php echo htmlspecialchars($current_exp['salvation']??''); ?>"></div>
                <div class="form-group"><label>Sanctification Date</label><input type="date" name="exp_sanctification" class="form-control" value="<?php echo htmlspecialchars($current_exp['sanctification']??''); ?>"></div>
                <div class="form-group"><label>Holy Ghost Baptism Date</label><input type="date" name="exp_baptism" class="form-control" value="<?php echo htmlspecialchars($current_exp['baptism_holy_ghost']??''); ?>"></div>
                <div class="form-group"><label>Water Baptism Date</label><input type="date" name="exp_water" class="form-control" value="<?php echo htmlspecialchars($current_exp['water_baptism']??''); ?>"></div>
            </div>
            <div style="grid-column: span 1;">
                 <div class="form-group"><label>Current Branch</label>
                    <select name="branch" class="form-control">
                        <option value="">Select Branch</option>
                        <?php foreach($branch_options as $o) echo "<option value='$o' ".($member && $member['branch']==$o?'selected':'').">$o</option>"; ?>
                    </select>
                </div>
                <div class="form-group"><label>Date Joined AFM</label><input type="date" name="date_joined" class="form-control" value="<?php echo htmlspecialchars($member['date_joined']??''); ?>"></div>
                
                 <div style="display:flex; gap:10px;">
                    <div class="form-group" style="flex:1"><label>Category</label>
                        <select name="category" class="form-control">
                            <?php foreach(['Member','Intern','Staff','Guest','Visitor'] as $c) echo "<option value='$c' ".($member && ($member['category']??'')==$c?'selected':'').">$c</option>"; ?>
                        </select>
                    </div>
                    <div class="form-group" style="flex:1"><label>Status</label>
                        <select name="status" class="form-control">
                            <?php foreach(['Available','Not Available','Sick','Travelled','Gospel Errand'] as $s) echo "<option value='$s' ".($member && $member['status']==$s?'selected':'').">$s</option>"; ?>
                        </select>
                    </div>
                </div>
                 <div style="display:flex; gap:10px;">
                     <div class="form-group" style="flex:1"><label>Unit</label><select name="unit" class="form-control"><option value="">Select</option><?php foreach($unit_options as $o) echo "<option value='$o' ".($member && $member['unit']==$o?'selected':'').">$o</option>"; ?></select></div>
                     <div class="form-group" style="flex:1"><label>Role</label><select name="unit_role" class="form-control"><option value="">Select</option><?php foreach($role_options as $o) echo "<option value='$o' ".($member && $member['unit_role']==$o?'selected':'').">$o</option>"; ?></select></div>
                 </div>
                 <div class="form-group"><label>Department</label><select name="department" class="form-control"><option value="">Select</option><?php foreach($dept_options as $o) echo "<option value='$o' ".($member && $member['department']==$o?'selected':'').">$o</option>"; ?></select></div>
            </div>
        </div>

        <h4 style="border-bottom: 1px solid #444; padding-bottom: 5px; margin-top: 10px;">Current / Past Assignments</h4>
        <table class="table table-bordered">
            <thead><tr><th>Role / Assignment</th><th>Location</th><th>Dates (From-To)</th><th>Pastor's Name</th></tr></thead>
            <tbody>
                <?php foreach($current_assign as $k=>$row): ?>
                <tr>
                    <td><input type="text" name="assign_role[]" class="form-control" value="<?php echo htmlspecialchars($row['role']); ?>"></td>
                    <td><input type="text" name="assign_location[]" class="form-control" value="<?php echo htmlspecialchars($row['location']); ?>"></td>
                    <td><input type="text" name="assign_dates[]" class="form-control" value="<?php echo htmlspecialchars($row['dates']); ?>"></td>
                    <td><input type="text" name="assign_pastor[]" class="form-control" value="<?php echo htmlspecialchars($row['pastor']); ?>"></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- D. Referees -->
    <div class="card" style="margin-bottom: 20px;">
        <h3>D. Referees</h3>
        <?php foreach($current_ref as $k => $ref): ?>
        <h4 style="margin-top: 10px;">Referee <?php echo $k+1; ?></h4>
        <div class="dashboard-grid">
            <div style="grid-column: span 1;">
                 <div class="form-group"><label>Name</label><input type="text" name="ref_name[]" class="form-control" value="<?php echo htmlspecialchars($ref['name']); ?>"></div>
                 <div class="form-group"><label>Relationship</label><input type="text" name="ref_relationship[]" class="form-control" value="<?php echo htmlspecialchars($ref['relationship']); ?>"></div>
                 <div class="form-group"><label>Address</label><input type="text" name="ref_address[]" class="form-control" value="<?php echo htmlspecialchars($ref['address']); ?>"></div>
            </div>
             <div style="grid-column: span 1;">
                 <div class="form-group"><label>GSM</label><input type="text" name="ref_phone[]" class="form-control" value="<?php echo htmlspecialchars($ref['phone']); ?>"></div>
                 <div class="form-group"><label>Email</label><input type="text" name="ref_email[]" class="form-control" value="<?php echo htmlspecialchars($ref['email']); ?>"></div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    
     <div style="margin-top: 20px;">
        <button type="submit" class="btn btn-block" style="background: var(--primary-color); padding: 15px; font-size: 1.2rem;"><?php echo $id ? 'Update Member Profile' : 'Add New Member'; ?></button>
    </div>

</form>
