<?php
// pages/public_form.php
require_once '../config/database.php';

$token = $_GET['token'] ?? '';
if (!$token) die("Access Denied");

// Verify Token
$stmt = $pdo->prepare("SELECT * FROM access_tokens WHERE token = ? AND is_used = 0 AND expires_at > NOW()");
$stmt->execute([$token]);
$access = $stmt->fetch();

if (!$access) {
    die("Invalid or Expired Link.");
}

$mode = $access['type']; // 'registration' or 'update'
$member = null;

// Default Data
$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' => '']
];
$default_assignments = [
    ['role' => '', 'location' => '', 'dates' => '', 'pastor' => '']
]; // Just one row default for public

// If update, fetch member
if ($mode === 'update') {
    $m_stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
    $m_stmt->execute([$access['member_id']]);
    $member = $m_stmt->fetch();
}

// Helper to decode or return default
function decode_or_default($json, $default) {
    if (empty($json)) return $default;
    $decoded = json_decode($json, true);
    return is_array($decoded) ? $decoded : $default;
}

$current_exp = $member ? decode_or_default($member['experiences'], $default_experiences) : $default_experiences;
$current_nok = $member ? decode_or_default($member['next_of_kin'], $default_nok) : $default_nok;
$current_emp = $member ? decode_or_default($member['employment'], $default_employment) : $default_employment;
$current_ref = $member ? decode_or_default($member['referees'], $default_referees) : $default_referees;
if (empty($current_ref)) $current_ref = $default_referees;
$current_assign = $member ? decode_or_default($member['past_assignments'], []) : [];
while(count($current_assign) < 2) $current_assign[] = ['role'=>'','location'=>'','dates'=>'','pastor'=>''];

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

$success = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once '../includes/functions.php';

    // 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;
    
    $category = clean_input($_POST['category']);
    $branch = clean_input($_POST['branch']);
    // Defaults for new registration
    $unit = ''; $unit_role = ''; $department = ''; $status = 'Available';

    // 2. Complex Fields
    $experiences = $default_experiences;
    foreach ($experiences as $k => $v) $experiences[$k] = !empty($_POST['exp_'.$k]) ? $_POST['exp_'.$k] : null;

    $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 = [
        '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 = [];
    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 = [];
    if (isset($_POST['assign_role'])) {
        for ($i=0; $i<count($_POST['assign_role']); $i++) {
            if (!empty($_POST['assign_role'][$i])) {
                $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),
            $category, $branch
        ];
        
        if ($mode === 'registration') {
            // Add defaults for new registration
            $params[] = $status; // status
            // unit, role, dept, date_joined (curdate) handled in SQL for now or simplified
            // SQL: ... category, branch, status, unit, unit_role, department, experiences, is_approved, date_joined ...
            // Let's align params
            $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,
                category, branch, status, unit, unit_role, department, is_approved, date_joined
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', '', '', 0, CURDATE())";
            $params[] = 'Available'; // status
        } else {
             // Update
             $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=?,
                category=?, branch=?
                WHERE id=?";
             $params[] = $member['id'];
        }

        // Debug Param Mismatch
        $ph_count = substr_count($sql, '?');
        $p_count = count($params);
        if ($ph_count !== $p_count) {
            $error = "System Error: Parameter Mismatch. SQL has $ph_count placeholders, provided $p_count params.";
        } else {
            try {
                $stmt = $pdo->prepare($sql);
                if ($stmt->execute($params)) {
                    $success = true;
                    $pdo->prepare("UPDATE access_tokens SET is_used = 1 WHERE id = ?")->execute([$access['id']]);
                } else {
                    $error = "Failed to submit data.";
                }
            } catch (PDOException $e) {
                $error = "System Error: " . $e->getMessage();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WCS Membership Data Form</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #e9ecef; color: #333; line-height: 1.6; margin: 0; padding: 20px; }
        .container { max-width: 900px; margin: 0 auto; background: #fff; padding: 40px; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
        h1 { text-align: center; color: #2c3e50; margin-bottom: 10px; border-bottom: 2px solid #eee; padding-bottom: 20px; }
        h3 { background: #f8f9fa; padding: 10px; border-left: 4px solid #007bff; margin-top: 30px; color: #007bff; }
        h4 { margin-top: 20px; margin-bottom: 10px; color: #666; font-size: 1.1em; border-bottom: 1px dashed #ccc; padding-bottom: 5px; }
        
        .row { display: flex; gap: 20px; flex-wrap: wrap; margin-bottom: 15px; }
        .col { flex: 1; min-width: 250px; }
        
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: 600; font-size: 0.9em; color: #555; }
        input, select, textarea { width: 100%; padding: 10px; border: 1px solid #ced4da; border-radius: 4px; box-sizing: border-box; transition: border-color 0.15s ease-in-out; }
        input:focus, select:focus, textarea:focus { border-color: #80bdff; outline: 0; box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25); }
        
        button { display: block; width: 100%; padding: 15px; background: #28a745; color: #fff; border: none; border-radius: 4px; font-size: 18px; font-weight: bold; cursor: pointer; transition: background 0.2s; margin-top: 30px; }
        button:hover { background: #218838; }
        
        .alert { padding: 15px; background: #d4edda; color: #155724; border-radius: 4px; margin-bottom: 20px; text-align: center; border: 1px solid #c3e6cb; }
        .alert-danger { background: #f8d7da; color: #721c24; border-color: #f5c6cb; }
        
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { border: 1px solid #dee2e6; padding: 8px; }
        th { background: #e9ecef; text-align: left; }
    </style>
</head>
<body>

<div class="container">
    <?php if ($success): ?>
        <div class="alert">
            <h2 style="margin-top:0;">Submission Successful!</h2>
            <p><?php echo $mode === 'registration' ? "Thank you! Your registration has been submitted for approval." : "Thank you! Your details have been updated."; ?></p>
        </div>
    <?php else: ?>
        <h1><?php echo $mode === 'registration' ? 'Membership Application Form' : 'Update Membership Details'; ?></h1>
        
        <?php if($error) echo "<div class='alert alert-danger'>$error</div>"; ?>

        <form method="POST">
            <!-- A. Personal Details -->
            <h3>A. Personal Details / Biodata</h3>
            <div class="row">
                <div class="col">
                    <div class="form-group"><label>Full Name *</label><input type="text" name="full_name" value="<?php echo htmlspecialchars($member['full_name']??''); ?>" required></div>
                </div>
                <div class="col">
                     <div class="form-group"><label>Address (Residential)</label><textarea name="address" rows="1"><?php echo htmlspecialchars($member['address']??''); ?></textarea></div>
                </div>
            </div>
            <div class="row">
                <div class="col">
                     <div class="form-group"><label>Email</label><input type="email" name="email" value="<?php echo htmlspecialchars($member['email']??''); ?>"></div>
                </div>
                <div class="col">
                    <div class="form-group"><label>Phone</label><input type="text" name="phone" value="<?php echo htmlspecialchars($member['phone']??''); ?>"></div>
                </div>
                <div class="col">
                    <div class="form-group"><label>WhatsApp</label><input type="text" name="whatsapp" value="<?php echo htmlspecialchars($member['whatsapp']??''); ?>"></div>
                </div>
            </div>
             <div class="row">
                <div class="col">
                     <div class="form-group"><label>Date of Birth</label><input type="date" name="dob" value="<?php echo htmlspecialchars($member['dob']??''); ?>"></div>
                </div>
                <div class="col">
                    <div class="form-group"><label>Gender</label>
                        <select name="gender">
                            <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 class="col">
                    <div class="form-group"><label>State/Country of Origin</label><input type="text" name="state_origin" value="<?php echo htmlspecialchars($member['state_origin']??''); ?>"></div>
                </div>
            </div>
            <div class="row">
                 <div class="col">
                    <div class="form-group"><label>Marital Status</label>
                        <select name="marital_status">
                            <option value="">Select</option>
                            <?php foreach(['Single','Married','Separated','Widowed','Divorced'] as $s) echo "<option value='$s' ". (($member['marital_status']??'')==$s?'selected':'') .">$s</option>"; ?>
                        </select>
                    </div>
                </div>
                <div class="col">
                     <div class="form-group"><label>Wedding Anniversary (if married)</label><input type="date" name="wedding_anniversary" value="<?php echo htmlspecialchars($member['wedding_anniversary']??''); ?>"></div>
                </div>
            </div>
            
            <h4>Next of Kin</h4>
            <div class="row">
                 <div class="col"><div class="form-group"><label>Name</label><input type="text" name="nok_name" value="<?php echo htmlspecialchars($current_nok['name']??''); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Relationship</label><input type="text" name="nok_relationship" value="<?php echo htmlspecialchars($current_nok['relationship']??''); ?>"></div></div>
            </div>
             <div class="row">
                 <div class="col"><div class="form-group"><label>Address</label><input type="text" name="nok_address" value="<?php echo htmlspecialchars($current_nok['address']??''); ?>"></div></div>
            </div>
            <div class="row">
                 <div class="col"><div class="form-group"><label>Phone</label><input type="text" name="nok_phone" value="<?php echo htmlspecialchars($current_nok['phone']??''); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Email</label><input type="email" name="nok_email" value="<?php echo htmlspecialchars($current_nok['email']??''); ?>"></div></div>
            </div>


            <!-- B. Work -->
            <h3>B. Work / Education</h3>
            <div class="row">
                 <div class="col"><div class="form-group"><label>Business/School Name</label><input type="text" name="emp_business_name" value="<?php echo htmlspecialchars($current_emp['business_name']??''); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Job Title / Course</label><input type="text" name="emp_job_title" value="<?php echo htmlspecialchars($current_emp['job_title']??''); ?>"></div></div>
            </div>
             <div class="row">
                 <div class="col"><div class="form-group"><label>Business Address</label><input type="text" name="emp_business_address" value="<?php echo htmlspecialchars($current_emp['business_address']??''); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Date Joined</label><input type="date" name="emp_date_joined" value="<?php echo htmlspecialchars($current_emp['date_joined']??''); ?>"></div></div>
            </div>
             <div class="row">
                 <div class="col"><div class="form-group"><label>Qualifications</label><input type="text" name="emp_qualifications" value="<?php echo htmlspecialchars($current_emp['qualifications']??''); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Skills / Abilities</label><input type="text" name="emp_skills" value="<?php echo htmlspecialchars($current_emp['skills']??''); ?>"></div></div>
            </div>


            <!-- C. Spiritual Info -->
            <h3>C. Spiritual Information</h3>
            <div class="row">
                 <div class="col"><div class="form-group"><label>Salvation</label><input type="date" name="exp_salvation" value="<?php echo htmlspecialchars($current_exp['salvation']??''); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Sanctification</label><input type="date" name="exp_sanctification" value="<?php echo htmlspecialchars($current_exp['sanctification']??''); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Holy Ghost Baptism</label><input type="date" name="exp_baptism" value="<?php echo htmlspecialchars($current_exp['baptism_holy_ghost']??''); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Water Baptism</label><input type="date" name="exp_water" value="<?php echo htmlspecialchars($current_exp['water_baptism']??''); ?>"></div></div>
            </div>
            <div class="row">
                 <div class="col">
                     <div class="form-group"><label>Category</label>
                        <select name="category">
                             <?php foreach(['Member','Intern','Staff','Guest','Visitor'] as $c) echo "<option value='$c' ". (($member['category']??'')==$c?'selected':'') .">$c</option>"; ?>
                        </select>
                    </div>
                </div>
                <div class="col">
                     <div class="form-group"><label>Current Branch</label>
                        <select name="branch">
                            <option value="">Select</option>
                             <?php foreach($branch_options as $o) echo "<option value='$o' ". (($member['branch']??'')==$o?'selected':'') .">$o</option>"; ?>
                        </select>
                    </div>
                </div>
            </div>

            <h4>Current / Past Assignments</h4>
            <table>
                <thead><tr><th>Role / Assignment</th><th>Location</th><th>Dates</th><th>Pastor's Name</th></tr></thead>
                <tbody>
                    <?php foreach($current_assign as $row): ?>
                    <tr>
                        <td><input type="text" name="assign_role[]" value="<?php echo htmlspecialchars($row['role']); ?>"></td>
                        <td><input type="text" name="assign_location[]" value="<?php echo htmlspecialchars($row['location']); ?>"></td>
                        <td><input type="text" name="assign_dates[]" value="<?php echo htmlspecialchars($row['dates']); ?>"></td>
                        <td><input type="text" name="assign_pastor[]" value="<?php echo htmlspecialchars($row['pastor']); ?>"></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>


            <!-- D. Referees -->
            <h3>D. Referees</h3>
             <?php foreach($current_ref as $k => $ref): ?>
            <h4>Referee <?php echo $k+1; ?></h4>
            <div class="row">
                 <div class="col"><div class="form-group"><label>Name</label><input type="text" name="ref_name[]" value="<?php echo htmlspecialchars($ref['name']); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Relationship</label><input type="text" name="ref_relationship[]" value="<?php echo htmlspecialchars($ref['relationship']); ?>"></div></div>
            </div>
            <div class="row">
                 <div class="col"><div class="form-group"><label>Address</label><input type="text" name="ref_address[]" value="<?php echo htmlspecialchars($ref['address']); ?>"></div></div>
            </div>
             <div class="row">
                 <div class="col"><div class="form-group"><label>Phone</label><input type="text" name="ref_phone[]" value="<?php echo htmlspecialchars($ref['phone']); ?>"></div></div>
                 <div class="col"><div class="form-group"><label>Email</label><input type="text" name="ref_email[]" value="<?php echo htmlspecialchars($ref['email']); ?>"></div></div>
            </div>
            <?php endforeach; ?>

            <div class="form-group" style="margin-top:20px;">
                <label style="font-weight:normal;">
                    <input type="checkbox" required style="width:auto; margin-right:10px;">
                    I confirm that the information contained in this application is correct and complete to the best of my knowledge.
                </label>
            </div>

            <button type="submit">Submit Membership Form</button>
        </form>
    <?php endif; ?>
</div>

</body>
</html>
