<?php
session_start();
require_once '../config/database.php';
require_once '../includes/auth.php';

// Redirect if already logged in
if (isLoggedIn()) {
    header('Location: index.php');
    exit();
}

$error = '';
$success = '';
$step = isset($_POST['step']) ? $_POST['step'] : 1;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($step == 1) {
        // Step 1: Check if user is a member
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        
        if (empty($email) || empty($phone)) {
            $error = "Please provide both email and phone number.";
        } else {
            // Check if member exists
            $memberQuery = "SELECT m.*, u.id as user_id, u.email as user_email,
                           s.name as society_name, c.name as circuit_name, d.name as diocese_name
                           FROM members m 
                           LEFT JOIN users u ON u.member_id = m.id 
                           LEFT JOIN societies s ON m.society_id = s.id
                           LEFT JOIN circuits c ON s.circuit_id = c.id
                           LEFT JOIN dioceses d ON c.diocese_id = d.id
                           WHERE (m.email = ? OR m.contact_number = ?)";
            $member = fetchRow($memberQuery, [$email, $phone]);
            
            if ($member) {
                // Member found - now check if they already have a job portal account
                $userCheck = fetchRow("SELECT id FROM job_portal_users WHERE member_id = ? OR email = ?", [$member['id'], $member['email']]);
                
                if ($userCheck) {
                    $error = "A job portal account already exists for this member. Please use the login page.";
                } else {
                    // Member exists but no job portal account yet - proceed to account creation
                    $_SESSION['registration_member'] = $member;
                    $step = 2;
                }
            } else {
                // Not a member, proceed to non-member registration
                $_SESSION['registration_email'] = $email;
                $_SESSION['registration_phone'] = $phone;
                $step = 3;
            }
        }
    } elseif ($step == 2) {
        // Step 2: Member registration - create job portal account
        $member = $_SESSION['registration_member'];
        $password = trim($_POST['password']);
        $confirm_password = trim($_POST['confirm_password']);
        
        if (empty($password) || strlen($password) < 6) {
            $error = "Password must be at least 6 characters long.";
        } elseif ($password !== $confirm_password) {
            $error = "Passwords do not match.";
        } else {
            // Create job portal account for existing member
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            
            $insertQuery = "INSERT INTO job_portal_users (email, password, full_name, phone, member_id, user_type, created_at) 
                           VALUES (?, ?, ?, ?, ?, 'member', NOW())";
            
            $fullName = $member['first_name'] . ' ' . $member['last_name'];
            
            $result = executeQuery($insertQuery, [
                $member['email'], 
                $hashedPassword, 
                $fullName, 
                $member['contact_number'],
                $member['id']
            ]);
            
            if ($result) {
                $success = "Account created successfully! You can now login with your credentials.";
                unset($_SESSION['registration_member']);
                $step = 1;
            } else {
                $error = "Failed to create account. Please try again.";
            }
        }
    } elseif ($step == 3) {
        // Step 3: Non-member registration
        $full_name = trim($_POST['full_name']);
        $email = $_SESSION['registration_email'];
        $phone = $_SESSION['registration_phone'];
        $password = trim($_POST['password']);
        $confirm_password = trim($_POST['confirm_password']);
        $user_type = trim($_POST['user_type']);
        
        if (empty($full_name) || empty($password) || empty($user_type)) {
            $error = "Please fill all required fields.";
        } elseif (strlen($password) < 6) {
            $error = "Password must be at least 6 characters long.";
        } elseif ($password !== $confirm_password) {
            $error = "Passwords do not match.";
        } else {
            // Check if email already exists
            $existingUser = fetchRow("SELECT id FROM job_portal_users WHERE email = ?", [$email]);
            if ($existingUser) {
                $error = "An account with this email already exists.";
            } else {
                // Hash password and create account
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                
                $insertQuery = "INSERT INTO job_portal_users (email, password, full_name, phone, user_type, created_at) 
                               VALUES (?, ?, ?, ?, ?, NOW())";
                
                $result = executeQuery($insertQuery, [
                    $email, 
                    $hashedPassword, 
                    $full_name, 
                    $phone, 
                    $user_type
                ]);
                
                if ($result) {
                    $success = "Account created successfully! You can now login with your credentials.";
                    unset($_SESSION['registration_email']);
                    unset($_SESSION['registration_phone']);
                    $step = 4; // Success step
                } else {
                    $error = "Failed to create account. Please try again.";
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - GHAMECC Job Portal</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
        }
        .registration-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            max-width: 500px;
            width: 100%;
        }
        .registration-header {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        .registration-body {
            padding: 2rem;
        }
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 2rem;
        }
        .step {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 0.5rem;
            font-weight: bold;
            color: #6c757d;
        }
        .step.active {
            background: #4CAF50;
            color: white;
        }
        .step.completed {
            background: #28a745;
            color: white;
        }
        .btn-primary {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #45a049 0%, #4CAF50 100%);
        }
        .form-control:focus {
            border-color: #4CAF50;
            box-shadow: 0 0 0 0.2rem rgba(76, 175, 80, 0.25);
        }
        .member-info {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="registration-container">
                    <div class="registration-header">
                        <h3><i class="fas fa-user-plus me-2"></i>Join GHAMECC Job Portal</h3>
                        <p class="mb-0">Connect with opportunities in our community</p>
                    </div>
                    
                    <div class="registration-body">
                        <!-- Step Indicator -->
                        <div class="step-indicator">
                            <div class="step <?php echo $step >= 1 ? 'active' : ''; ?>">1</div>
                            <div class="step <?php echo $step >= 2 ? 'active' : ''; ?>">2</div>
                            <div class="step <?php echo $step >= 3 ? 'active' : ''; ?>">3</div>
                        </div>

                        <?php if (!empty($error)): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i><?php echo $error; ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($success)): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($step == 1): ?>
                            <!-- Step 1: Member Check -->
                            <div class="text-center mb-4">
                                <h5>Let's get started!</h5>
                                <p class="text-muted">First, let us check if you're already a GHAMECC member</p>
                            </div>
                            
                            <form method="POST">
                                <input type="hidden" name="step" value="1">
                                
                                <div class="mb-3">
                                    <label for="email" class="form-label">
                                        <i class="fas fa-envelope me-1"></i>Email Address
                                    </label>
                                    <input type="email" class="form-control" id="email" name="email" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="phone" class="form-label">
                                        <i class="fas fa-phone me-1"></i>Phone Number
                                    </label>
                                    <input type="tel" class="form-control" id="phone" name="phone" required>
                                </div>
                                
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-search me-2"></i>Check Membership
                                </button>
                            </form>

                        <?php elseif ($step == 2): ?>
                            <!-- Step 2: Member Registration -->
                            <?php $member = $_SESSION['registration_member']; ?>
                            <div class="text-center mb-4">
                                <h5><i class="fas fa-user-check text-success me-2"></i>Welcome back, Member!</h5>
                                <p class="text-muted">We found your membership record. Let's create your job portal account.</p>
                            </div>
                            
                            <div class="member-info">
                                <h6><i class="fas fa-id-card me-2"></i>Member Information</h6>
                                <p class="mb-1"><strong>Name:</strong> <?php echo htmlspecialchars($member['first_name'] . ' ' . $member['last_name']); ?></p>
                                <p class="mb-1"><strong>Email:</strong> <?php echo htmlspecialchars($member['email']); ?></p>
                                <p class="mb-1"><strong>Phone:</strong> <?php echo htmlspecialchars($member['contact_number']); ?></p>
                                <p class="mb-1"><strong>Society:</strong> <?php echo htmlspecialchars($member['society_name']); ?></p>
                                <p class="mb-1"><strong>Circuit:</strong> <?php echo htmlspecialchars($member['circuit_name']); ?></p>
                                <p class="mb-0"><strong>Diocese:</strong> <?php echo htmlspecialchars($member['diocese_name']); ?></p>
                            </div>
                            
                            <form method="POST">
                                <input type="hidden" name="step" value="2">
                                
                                <div class="mb-3">
                                    <label for="password" class="form-label">
                                        <i class="fas fa-lock me-1"></i>Create Password
                                    </label>
                                    <input type="password" class="form-control" id="password" name="password" required minlength="6">
                                    <div class="form-text">Password must be at least 6 characters long</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="confirm_password" class="form-label">
                                        <i class="fas fa-lock me-1"></i>Confirm Password
                                    </label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                </div>
                                
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-user-plus me-2"></i>Create Account
                                </button>
                            </form>

                        <?php elseif ($step == 3): ?>
                            <!-- Step 3: Non-member Registration -->
                            <div class="text-center mb-4">
                                <h5><i class="fas fa-user-plus text-info me-2"></i>New to GHAMECC?</h5>
                                <p class="text-muted">No worries! You can still join our job portal community.</p>
                            </div>
                            
                            <form method="POST">
                                <input type="hidden" name="step" value="3">
                                
                                <div class="mb-3">
                                    <label for="full_name" class="form-label">
                                        <i class="fas fa-user me-1"></i>Full Name
                                    </label>
                                    <input type="text" class="form-control" id="full_name" name="full_name" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-envelope me-1"></i>Email Address
                                    </label>
                                    <input type="email" class="form-control" value="<?php echo htmlspecialchars($_SESSION['registration_email']); ?>" readonly>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-phone me-1"></i>Phone Number
                                    </label>
                                    <input type="tel" class="form-control" value="<?php echo htmlspecialchars($_SESSION['registration_phone']); ?>" readonly>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="user_type" class="form-label">
                                        <i class="fas fa-briefcase me-1"></i>I am joining as
                                    </label>
                                    <select class="form-control" id="user_type" name="user_type" required>
                                        <option value="">Select your role</option>
                                        <option value="member">Job Seeker (GHAMECC Member)</option>
                                        <option value="employer">Employer</option>
                                    </select>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="password" class="form-label">
                                        <i class="fas fa-lock me-1"></i>Create Password
                                    </label>
                                    <input type="password" class="form-control" id="password" name="password" required minlength="6">
                                </div>
                                
                                <div class="mb-3">
                                    <label for="confirm_password" class="form-label">
                                        <i class="fas fa-lock me-1"></i>Confirm Password
                                    </label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                </div>
                                
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-user-plus me-2"></i>Create Account
                                </button>
                            </form>

                        <?php elseif ($step == 4): ?>
                            <!-- Step 4: Success -->
                            <div class="text-center">
                                <div class="mb-4">
                                    <i class="fas fa-check-circle text-success" style="font-size: 4rem;"></i>
                                </div>
                                <h5>Registration Successful!</h5>
                                <p class="text-muted mb-4">Your account has been created successfully. You can now login and start exploring job opportunities.</p>
                                
                                <div class="d-grid gap-2">
                                    <a href="login.php" class="btn btn-primary">
                                        <i class="fas fa-sign-in-alt me-2"></i>Login Now
                                    </a>
                                    <a href="index.php" class="btn btn-outline-secondary">
                                        <i class="fas fa-home me-2"></i>Go to Homepage
                                    </a>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($step < 4): ?>
                            <div class="text-center mt-4">
                                <p class="text-muted">
                                    Already have an account? 
                                    <a href="login.php" class="text-decoration-none">Login here</a>
                                </p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Password confirmation validation
        document.addEventListener('DOMContentLoaded', function() {
            const passwordField = document.getElementById('password');
            const confirmPasswordField = document.getElementById('confirm_password');
            
            if (passwordField && confirmPasswordField) {
                function validatePasswords() {
                    if (confirmPasswordField.value && passwordField.value !== confirmPasswordField.value) {
                        confirmPasswordField.setCustomValidity('Passwords do not match');
                    } else {
                        confirmPasswordField.setCustomValidity('');
                    }
                }
                
                passwordField.addEventListener('input', validatePasswords);
                confirmPasswordField.addEventListener('input', validatePasswords);
            }
        });
    </script>
</body>
</html>
