<?php
session_start();
include 'layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Initialize variables
$success_message = '';
$error_message = '';
$form_data = [];

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate input data
    $form_data = [
        'first_name' => trim($_POST['first_name'] ?? ''),
        'last_name' => trim($_POST['last_name'] ?? ''),
        'middle_name' => trim($_POST['middle_name'] ?? ''),
        'email' => trim($_POST['email'] ?? ''),
        'phone_primary' => trim($_POST['phone_primary'] ?? ''),
        'phone_secondary' => trim($_POST['phone_secondary'] ?? ''),
        'date_of_birth' => $_POST['date_of_birth'] ?? '',
        'gender' => $_POST['gender'] ?? '',
        'national_id' => trim($_POST['national_id'] ?? ''),
        'address' => trim($_POST['address'] ?? ''),
        'city' => trim($_POST['city'] ?? ''),
        'county' => trim($_POST['county'] ?? ''),
        'postal_code' => trim($_POST['postal_code'] ?? ''),
        'license_number' => trim($_POST['license_number'] ?? ''),
        'license_expiry' => $_POST['license_expiry'] ?? '',
        'branch_id' => $_POST['branch_id'] ?? '',
        'education_level' => $_POST['education_level'] ?? '',
        'experience_years' => $_POST['experience_years'] ?? '',
        'previous_company' => trim($_POST['previous_company'] ?? ''),
        'emergency_contact' => trim($_POST['emergency_contact'] ?? ''),
        'emergency_phone' => trim($_POST['emergency_phone'] ?? ''),
        'emergency_relationship' => trim($_POST['emergency_relationship'] ?? ''),
        'password' => $_POST['password'] ?? '',
        'confirm_password' => $_POST['confirm_password'] ?? ''
    ];

    // Validation
    $errors = [];

    // Required fields validation
    if (empty($form_data['first_name'])) $errors[] = "First name is required";
    if (empty($form_data['last_name'])) $errors[] = "Last name is required";
    if (empty($form_data['email'])) $errors[] = "Email is required";
    if (empty($form_data['phone_primary'])) $errors[] = "Primary phone number is required";
    if (empty($form_data['date_of_birth'])) $errors[] = "Date of birth is required";
    if (empty($form_data['gender'])) $errors[] = "Gender is required";
    if (empty($form_data['national_id'])) $errors[] = "National ID is required";
    if (empty($form_data['address'])) $errors[] = "Address is required";
    if (empty($form_data['city'])) $errors[] = "City is required";
    if (empty($form_data['county'])) $errors[] = "County is required";
    if (empty($form_data['branch_id'])) $errors[] = "Preferred branch is required";
    if (empty($form_data['password'])) $errors[] = "Password is required";
    if (empty($form_data['confirm_password'])) $errors[] = "Password confirmation is required";

    // Email validation
    if (!empty($form_data['email']) && !filter_var($form_data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }

    // Phone validation (Kenya format)
    if (!empty($form_data['phone_primary']) && !preg_match('/^(\+254|254|0)[17]\d{8}$/', $form_data['phone_primary'])) {
        $errors[] = "Invalid primary phone number format";
    }

    // National ID validation (Kenya format)
    if (!empty($form_data['national_id']) && !preg_match('/^\d{7,8}$/', $form_data['national_id'])) {
        $errors[] = "Invalid National ID format";
    }

    // Password validation
    if (!empty($form_data['password'])) {
        if (strlen($form_data['password']) < 8) {
            $errors[] = "Password must be at least 8 characters long";
        }
        if (!preg_match('/[A-Z]/', $form_data['password'])) {
            $errors[] = "Password must contain at least one uppercase letter";
        }
        if (!preg_match('/[a-z]/', $form_data['password'])) {
            $errors[] = "Password must contain at least one lowercase letter";
        }
        if (!preg_match('/[0-9]/', $form_data['password'])) {
            $errors[] = "Password must contain at least one number";
        }
    }

    // Password confirmation
    if ($form_data['password'] !== $form_data['confirm_password']) {
        $errors[] = "Passwords do not match";
    }

    // Age validation (must be 18+)
    if (!empty($form_data['date_of_birth'])) {
        $birth_date = new DateTime($form_data['date_of_birth']);
        $today = new DateTime();
        $age = $today->diff($birth_date)->y;
        if ($age < 18) {
            $errors[] = "You must be at least 18 years old to register as an agent";
        }
    }

    // Check if email already exists
    if (!empty($form_data['email'])) {
        $check_email_sql = "SELECT user_id FROM users WHERE email = ?";
        $check_email_stmt = $conn->prepare($check_email_sql);
        $check_email_stmt->bind_param("s", $form_data['email']);
        $check_email_stmt->execute();
        if ($check_email_stmt->get_result()->num_rows > 0) {
            $errors[] = "Email address is already registered";
        }
        $check_email_stmt->close();
    }

    // Check if national ID already exists
    if (!empty($form_data['national_id'])) {
        $check_id_sql = "SELECT user_id FROM users WHERE national_id = ?";
        $check_id_stmt = $conn->prepare($check_id_sql);
        $check_id_stmt->bind_param("s", $form_data['national_id']);
        $check_id_stmt->execute();
        if ($check_id_stmt->get_result()->num_rows > 0) {
            $errors[] = "National ID is already registered";
        }
        $check_id_stmt->close();
    }

    // If no errors, proceed with registration
    if (empty($errors)) {
        try {
            $conn->begin_transaction();

            // Generate unique agent code
            $agent_code = 'ULT' . date('y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            
            // Check if agent code exists and generate new one if needed
            do {
                $check_code_sql = "SELECT user_id FROM users WHERE agent_code = ?";
                $check_code_stmt = $conn->prepare($check_code_sql);
                $check_code_stmt->bind_param("s", $agent_code);
                $check_code_stmt->execute();
                $code_exists = $check_code_stmt->get_result()->num_rows > 0;
                $check_code_stmt->close();
                
                if ($code_exists) {
                    $agent_code = 'ULT' . date('y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
                }
            } while ($code_exists);

            // Generate username from email
            $username = strtolower(explode('@', $form_data['email'])[0]);
            $original_username = $username;
            $counter = 1;
            
            // Ensure username is unique
            do {
                $check_username_sql = "SELECT user_id FROM users WHERE username = ?";
                $check_username_stmt = $conn->prepare($check_username_sql);
                $check_username_stmt->bind_param("s", $username);
                $check_username_stmt->execute();
                $username_exists = $check_username_stmt->get_result()->num_rows > 0;
                $check_username_stmt->close();
                
                if ($username_exists) {
                    $username = $original_username . $counter;
                    $counter++;
                }
            } while ($username_exists);

            // Hash password
            $password_hash = password_hash($form_data['password'], PASSWORD_DEFAULT);

            // Get Insurance Agent role ID
            $role_sql = "SELECT role_id FROM user_roles WHERE role_name = 'Insurance Agent' AND is_active = 1";
            $role_result = $conn->query($role_sql);
            $agent_role_id = $role_result->fetch_assoc()['role_id'];

            // Prepare full name
            $full_name = trim($form_data['first_name'] . ' ' . $form_data['middle_name'] . ' ' . $form_data['last_name']);

            // Insert user record
            $insert_sql = "INSERT INTO users (
                username, email, password_hash, full_name, phone_number, role_id, 
                agent_code, license_number, license_expiry, branch_id, status, 
                date_of_birth, gender, national_id, address, emergency_contact, 
                emergency_phone, hire_date, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, ?, CURDATE(), NOW())";

            $insert_stmt = $conn->prepare($insert_sql);
            $insert_stmt->bind_param("sssssisssssssss", 
                $username, $form_data['email'], $password_hash, $full_name, 
                $form_data['phone_primary'], $agent_role_id, $agent_code, 
                $form_data['license_number'], $form_data['license_expiry'], 
                $form_data['branch_id'], $form_data['date_of_birth'], 
                $form_data['gender'], $form_data['national_id'], $form_data['address'], 
                $form_data['emergency_contact'], $form_data['emergency_phone']
            );

            if ($insert_stmt->execute()) {
                $user_id = $conn->insert_id;

                // Log registration activity
                $ip_address = $_SERVER['REMOTE_ADDR'];
                if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
                }
                $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';

                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent) 
                           VALUES (?, 'REGISTER', 'AUTH', ?, 'USER', ?, ?, ?)";
                $log_stmt = $conn->prepare($log_sql);
                $registration_data = json_encode([
                    'agent_code' => $agent_code,
                    'registration_time' => date('Y-m-d H:i:s'),
                    'status' => 'PENDING'
                ]);
                $log_stmt->bind_param("iisss", $user_id, $user_id, $registration_data, $ip_address, $user_agent);
                $log_stmt->execute();
                $log_stmt->close();

                $conn->commit();
                $success_message = "Registration successful! Your agent code is <strong>$agent_code</strong>. Your account is pending approval.";
                $form_data = []; // Clear form data on success

            } else {
                throw new Exception("Failed to insert user record");
            }

            $insert_stmt->close();

        } catch (Exception $e) {
            $conn->rollback();
            error_log("Registration error: " . $e->getMessage());
            $error_message = "Registration failed. Please try again later.";
        }
    } else {
        $error_message = implode('<br>', $errors);
    }
}

// Get branches for dropdown
$branches_sql = "SELECT branch_id, branch_name, city FROM branches WHERE is_active = 1 ORDER BY branch_name";
$branches_result = $conn->query($branches_sql);
$branches = [];
while ($row = $branches_result->fetch_assoc()) {
    $branches[] = $row;
}

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Agent Registration - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Phosphor Icons -->
    <link href="https://unpkg.com/phosphor-icons@1.4.2/src/css/icons.css" rel="stylesheet">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    
    <style>
        /* Custom styling matching login page design */
        .auth-page-wrapper {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
        }
        
        .registration-card {
            border: none;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .registration-left-panel {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            position: relative;
        }
        
        .registration-left-panel::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
            opacity: 0.3;
        }
        
        .registration-content {
            position: relative;
            z-index: 2;
        }
        
        .feature-item {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
            text-align: center;
        }
        
        .feature-item:hover {
            transform: translateY(-5px);
            background: rgba(255, 255, 255, 0.15);
        }
        
        .form-section {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 30px;
            border: 1px solid #e9ecef;
        }
        
        .section-title {
            color: #667eea;
            font-weight: 600;
            font-size: 1.1rem;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
            display: flex;
            align-items: center;
        }
        
        .section-title i {
            margin-right: 10px;
            font-size: 1.3rem;
        }
        
        .form-control, .form-select {
            border-radius: 10px;
            border: 1px solid #dee2e6;
            padding: 12px 15px;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-primary-custom {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
            background: linear-gradient(135deg, #5a67d8 0%, #667eea 100%);
        }
        
        .password-strength {
            height: 5px;
            border-radius: 3px;
            transition: all 0.3s ease;
        }
        
        .password-requirements {
            font-size: 0.85rem;
            margin-top: 10px;
        }
        
        .requirement {
            padding: 2px 0;
            transition: color 0.3s ease;
        }
        
        .requirement.met {
            color: #28a745;
        }
        
        .requirement.unmet {
            color: #dc3545;
        }
        
        .select2-container--default .select2-selection--single {
            border-radius: 10px;
            border: 1px solid #dee2e6;
            height: 48px;
            padding: 0 15px;
        }
        
        .progress-indicator {
            background: rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .step {
            display: flex;
            align-items: center;
            color: white;
            margin-bottom: 10px;
        }
        
        .step-number {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            font-weight: bold;
        }
        
        .step.completed .step-number {
            background: #28a745;
        }
        
        .step.active .step-number {
            background: #ffc107;
            color: #000;
        }
    </style>
</head>

<body>
    <!-- auth-page wrapper -->
    <div class="auth-page-wrapper py-5 d-flex justify-content-center align-items-center min-vh-100">
        
        <!-- auth-page content -->
        <div class="auth-page-content overflow-hidden pt-lg-5">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card registration-card">
                            <div class="row g-0">
                                <div class="col-lg-4">
                                    <div class="registration-left-panel p-lg-4 p-3 h-100 d-flex flex-column justify-content-center">
                                        <div class="registration-content text-center text-white">
                                            <div class="mb-4">
                                                <a href="index.php" class="d-block">
                                                    <img src="assets/images/logo/ultrasure_logo_white.png" alt="Ultrasure Insurance Platform" height="60" class="mb-3">
                                                </a>
                                                <h4 class="text-white mb-3">Join Our Team</h4>
                                                <p class="text-white-50 mb-4">Become a certified insurance agent with Ultrasure and start your journey in digital insurance.</p>
                                            </div>
                                            
                                            <!-- Registration Progress -->
                                            <div class="progress-indicator">
                                                <h6 class="text-white mb-3">Registration Process</h6>
                                                <div class="step completed">
                                                    <div class="step-number">1</div>
                                                    <span>Fill Application</span>
                                                </div>
                                                <div class="step">
                                                    <div class="step-number">2</div>
                                                    <span>Document Verification</span>
                                                </div>
                                                <div class="step">
                                                    <div class="step-number">3</div>
                                                    <span>Training & Onboarding</span>
                                                </div>
                                                <div class="step">
                                                    <div class="step-number">4</div>
                                                    <span>Account Activation</span>
                                                </div>
                                            </div>
                                            
                                            <!-- Benefits -->
                                            <div class="row text-center">
                                                <div class="col-12 mb-3">
                                                    <div class="feature-item">
                                                        <i class="ri-trophy-line text-white h4 mb-2 d-block"></i>
                                                        <small class="text-white-50">Competitive Commission</small>
                                                        <div class="text-white-75 small mt-1">Earn up to 25% commission</div>
                                                    </div>
                                                </div>
                                                <div class="col-12 mb-3">
                                                    <div class="feature-item">
                                                        <i class="ri-graduation-cap-line text-white h4 mb-2 d-block"></i>
                                                        <small class="text-white-50">Free Training</small>
                                                        <div class="text-white-75 small mt-1">Comprehensive certification</div>
                                                    </div>
                                                </div>
                                                <div class="col-12">
                                                    <div class="feature-item">
                                                        <i class="ri-smartphone-line text-white h4 mb-2 d-block"></i>
                                                        <small class="text-white-50">Digital Tools</small>
                                                        <div class="text-white-75 small mt-1">Advanced platform access</div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- end col -->

                                <div class="col-lg-8">
                                    <div class="p-lg-5 p-4">
                                        <div class="text-center mb-4">
                                            <h4 class="text-primary mb-2">Agent Registration</h4>
                                            <p class="text-muted">Complete the form below to start your application</p>
                                        </div>

                                        <!-- Display messages -->
                                        <?php if(!empty($success_message)): ?>
                                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                                <i class="ri-check-circle-line me-2"></i>
                                                <?php echo $success_message; ?>
                                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                            </div>
                                        <?php endif; ?>

                                        <?php if(!empty($error_message)): ?>
                                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                                <i class="ri-error-warning-line me-2"></i>
                                                <?php echo $error_message; ?>
                                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                            </div>
                                        <?php endif; ?>

                                        <form id="registration-form" method="POST" novalidate>
                                            <!-- Personal Information Section -->
                                            <div class="form-section">
                                                <h5 class="section-title">
                                                    <i class="ri-user-line"></i> Personal Information
                                                </h5>
                                                <div class="row">
                                                    <div class="col-md-4 mb-3">
                                                        <label for="first_name" class="form-label">First Name <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" id="first_name" name="first_name" 
                                                               value="<?php echo htmlspecialchars($form_data['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($form_data['middle_name'] ?? ''); ?>">
                                                    </div>
                                                    <div class="col-md-4 mb-3">
                                                        <label for="last_name" class="form-label">Last Name <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" id="last_name" name="last_name" 
                                                               value="<?php echo htmlspecialchars($form_data['last_name'] ?? ''); ?>" required>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="date_of_birth" class="form-label">Date of Birth <span class="text-danger">*</span></label>
                                                        <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" 
                                                               value="<?php echo htmlspecialchars($form_data['date_of_birth'] ?? ''); ?>" 
                                                               max="<?php echo date('Y-m-d', strtotime('-18 years')); ?>" required>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label for="gender" class="form-label">Gender <span class="text-danger">*</span></label>
                                                        <select class="form-select" id="gender" name="gender" required>
                                                            <option value="">Select Gender</option>
                                                            <option value="MALE" <?php echo ($form_data['gender'] ?? '') === 'MALE' ? 'selected' : ''; ?>>Male</option>
                                                            <option value="FEMALE" <?php echo ($form_data['gender'] ?? '') === 'FEMALE' ? 'selected' : ''; ?>>Female</option>
                                                            <option value="OTHER" <?php echo ($form_data['gender'] ?? '') === 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="national_id" class="form-label">National ID Number <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" id="national_id" name="national_id" 
                                                               value="<?php echo htmlspecialchars($form_data['national_id'] ?? ''); ?>" 
                                                               placeholder="e.g., 12345678" pattern="\d{7,8}" required>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Contact Information Section -->
                                            <div class="form-section">
                                                <h5 class="section-title">
                                                    <i class="ri-phone-line"></i> Contact Information
                                                </h5>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="email" class="form-label">Email Address <span class="text-danger">*</span></label>
                                                        <input type="email" class="form-control" id="email" name="email" 
                                                               value="<?php echo htmlspecialchars($form_data['email'] ?? ''); ?>" required>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label for="phone_primary" class="form-label">Primary Phone <span class="text-danger">*</span></label>
                                                        <input type="tel" class="form-control" id="phone_primary" name="phone_primary" 
                                                               value="<?php echo htmlspecialchars($form_data['phone_primary'] ?? ''); ?>" 
                                                               placeholder="e.g., 0712345678" required>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="phone_secondary" class="form-label">Secondary Phone</label>
                                                        <input type="tel" class="form-control" id="phone_secondary" name="phone_secondary" 
                                                               value="<?php echo htmlspecialchars($form_data['phone_secondary'] ?? ''); ?>" 
                                                               placeholder="e.g., 0712345678">
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Address Information Section -->
                                            <div class="form-section">
                                                <h5 class="section-title">
                                                    <i class="ri-map-pin-line"></i> Address Information
                                                </h5>
                                                <div class="row">
                                                    <div class="col-md-12 mb-3">
                                                        <label for="address" class="form-label">Physical Address <span class="text-danger">*</span></label>
                                                        <textarea class="form-control" id="address" name="address" rows="3" 
                                                                  placeholder="Enter your full physical address" required><?php echo htmlspecialchars($form_data['address'] ?? ''); ?></textarea>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-4 mb-3">
                                                        <label for="city" class="form-label">City/Town <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" id="city" name="city" 
                                                               value="<?php echo htmlspecialchars($form_data['city'] ?? ''); ?>" required>
                                                    </div>
                                                    <div class="col-md-4 mb-3">
                                                        <label for="county" class="form-label">County <span class="text-danger">*</span></label>
                                                        <select class="form-select" id="county" name="county" required>
                                                            <option value="">Select County</option>
                                                            <option value="Nairobi" <?php echo ($form_data['county'] ?? '') === 'Nairobi' ? 'selected' : ''; ?>>Nairobi</option>
                                                            <option value="Mombasa" <?php echo ($form_data['county'] ?? '') === 'Mombasa' ? 'selected' : ''; ?>>Mombasa</option>
                                                            <option value="Kisumu" <?php echo ($form_data['county'] ?? '') === 'Kisumu' ? 'selected' : ''; ?>>Kisumu</option>
                                                            <option value="Nakuru" <?php echo ($form_data['county'] ?? '') === 'Nakuru' ? 'selected' : ''; ?>>Nakuru</option>
                                                            <option value="Uasin Gishu" <?php echo ($form_data['county'] ?? '') === 'Uasin Gishu' ? 'selected' : ''; ?>>Uasin Gishu</option>
                                                            <option value="Kiambu" <?php echo ($form_data['county'] ?? '') === 'Kiambu' ? 'selected' : ''; ?>>Kiambu</option>
                                                            <option value="Machakos" <?php echo ($form_data['county'] ?? '') === 'Machakos' ? 'selected' : ''; ?>>Machakos</option>
                                                            <option value="Kajiado" <?php echo ($form_data['county'] ?? '') === 'Kajiado' ? 'selected' : ''; ?>>Kajiado</option>
                                                            <option value="Murang'a" <?php echo ($form_data['county'] ?? '') === 'Murang\'a' ? 'selected' : ''; ?>>Murang'a</option>
                                                            <option value="Nyeri" <?php echo ($form_data['county'] ?? '') === 'Nyeri' ? 'selected' : ''; ?>>Nyeri</option>
                                                            <option value="Meru" <?php echo ($form_data['county'] ?? '') === 'Meru' ? 'selected' : ''; ?>>Meru</option>
                                                            <option value="Kakamega" <?php echo ($form_data['county'] ?? '') === 'Kakamega' ? 'selected' : ''; ?>>Kakamega</option>
                                                            <option value="Bungoma" <?php echo ($form_data['county'] ?? '') === 'Bungoma' ? 'selected' : ''; ?>>Bungoma</option>
                                                            <option value="Kericho" <?php echo ($form_data['county'] ?? '') === 'Kericho' ? 'selected' : ''; ?>>Kericho</option>
                                                            <option value="Nandi" <?php echo ($form_data['county'] ?? '') === 'Nandi' ? 'selected' : ''; ?>>Nandi</option>
                                                            <option value="Bomet" <?php echo ($form_data['county'] ?? '') === 'Bomet' ? 'selected' : ''; ?>>Bomet</option>
                                                            <option value="Trans Nzoia" <?php echo ($form_data['county'] ?? '') === 'Trans Nzoia' ? 'selected' : ''; ?>>Trans Nzoia</option>
                                                            <option value="Kilifi" <?php echo ($form_data['county'] ?? '') === 'Kilifi' ? 'selected' : ''; ?>>Kilifi</option>
                                                            <option value="Kwale" <?php echo ($form_data['county'] ?? '') === 'Kwale' ? 'selected' : ''; ?>>Kwale</option>
                                                            <option value="Other" <?php echo ($form_data['county'] ?? '') === 'Other' ? 'selected' : ''; ?>>Other</option>
                                                        </select>
                                                    </div>
                                                    <div class="col-md-4 mb-3">
                                                        <label for="postal_code" class="form-label">Postal Code</label>
                                                        <input type="text" class="form-control" id="postal_code" name="postal_code" 
                                                               value="<?php echo htmlspecialchars($form_data['postal_code'] ?? ''); ?>" 
                                                               placeholder="e.g., 00100">
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Professional Information Section -->
                                            <div class="form-section">
                                                <h5 class="section-title">
                                                    <i class="ri-briefcase-line"></i> Professional Information
                                                </h5>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="license_number" class="form-label">Insurance License Number</label>
                                                        <input type="text" class="form-control" id="license_number" name="license_number" 
                                                               value="<?php echo htmlspecialchars($form_data['license_number'] ?? ''); ?>" 
                                                               placeholder="Enter your license number (if any)">
                                                        <small class="text-muted">Leave blank if you don't have a license yet</small>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label for="license_expiry" class="form-label">License Expiry Date</label>
                                                        <input type="date" class="form-control" id="license_expiry" name="license_expiry" 
                                                               value="<?php echo htmlspecialchars($form_data['license_expiry'] ?? ''); ?>">
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="education_level" class="form-label">Education Level</label>
                                                        <select class="form-select" id="education_level" name="education_level">
                                                            <option value="">Select Education Level</option>
                                                            <option value="Secondary" <?php echo ($form_data['education_level'] ?? '') === 'Secondary' ? 'selected' : ''; ?>>Secondary School</option>
                                                            <option value="Certificate" <?php echo ($form_data['education_level'] ?? '') === 'Certificate' ? 'selected' : ''; ?>>Certificate</option>
                                                            <option value="Diploma" <?php echo ($form_data['education_level'] ?? '') === 'Diploma' ? 'selected' : ''; ?>>Diploma</option>
                                                            <option value="Degree" <?php echo ($form_data['education_level'] ?? '') === 'Degree' ? 'selected' : ''; ?>>Bachelor's Degree</option>
                                                            <option value="Masters" <?php echo ($form_data['education_level'] ?? '') === 'Masters' ? 'selected' : ''; ?>>Master's Degree</option>
                                                            <option value="PhD" <?php echo ($form_data['education_level'] ?? '') === 'PhD' ? 'selected' : ''; ?>>PhD</option>
                                                        </select>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label for="experience_years" class="form-label">Years of Insurance Experience</label>
                                                        <select class="form-select" id="experience_years" name="experience_years">
                                                            <option value="">Select Experience</option>
                                                            <option value="0" <?php echo ($form_data['experience_years'] ?? '') === '0' ? 'selected' : ''; ?>>No Experience</option>
                                                            <option value="1" <?php echo ($form_data['experience_years'] ?? '') === '1' ? 'selected' : ''; ?>>Less than 1 year</option>
                                                            <option value="2" <?php echo ($form_data['experience_years'] ?? '') === '2' ? 'selected' : ''; ?>>1-2 years</option>
                                                            <option value="5" <?php echo ($form_data['experience_years'] ?? '') === '5' ? 'selected' : ''; ?>>3-5 years</option>
                                                            <option value="10" <?php echo ($form_data['experience_years'] ?? '') === '10' ? 'selected' : ''; ?>>6-10 years</option>
                                                            <option value="15" <?php echo ($form_data['experience_years'] ?? '') === '15' ? 'selected' : ''; ?>>More than 10 years</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="previous_company" class="form-label">Previous Insurance Company</label>
                                                        <input type="text" class="form-control" id="previous_company" name="previous_company" 
                                                               value="<?php echo htmlspecialchars($form_data['previous_company'] ?? ''); ?>" 
                                                               placeholder="Enter previous employer (if any)">
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label for="branch_id" class="form-label">Preferred Branch <span class="text-danger">*</span></label>
                                                        <select class="form-select" id="branch_id" name="branch_id" required>
                                                            <option value="">Select Preferred Branch</option>
                                                            <?php foreach($branches as $branch): ?>
                                                                <option value="<?php echo $branch['branch_id']; ?>" 
                                                                        <?php echo ($form_data['branch_id'] ?? '') == $branch['branch_id'] ? 'selected' : ''; ?>>
                                                                    <?php echo htmlspecialchars($branch['branch_name'] . ' - ' . $branch['city']); ?>
                                                                </option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Emergency Contact Section -->
                                            <div class="form-section">
                                                <h5 class="section-title">
                                                    <i class="ri-contacts-line"></i> Emergency Contact
                                                </h5>
                                                <div class="row">
                                                    <div class="col-md-4 mb-3">
                                                        <label for="emergency_contact" class="form-label">Contact Name</label>
                                                        <input type="text" class="form-control" id="emergency_contact" name="emergency_contact" 
                                                               value="<?php echo htmlspecialchars($form_data['emergency_contact'] ?? ''); ?>" 
                                                               placeholder="Full name">
                                                    </div>
                                                    <div class="col-md-4 mb-3">
                                                        <label for="emergency_phone" class="form-label">Contact Phone</label>
                                                        <input type="tel" class="form-control" id="emergency_phone" name="emergency_phone" 
                                                               value="<?php echo htmlspecialchars($form_data['emergency_phone'] ?? ''); ?>" 
                                                               placeholder="Phone number">
                                                    </div>
                                                    <div class="col-md-4 mb-3">
                                                        <label for="emergency_relationship" class="form-label">Relationship</label>
                                                        <select class="form-select" id="emergency_relationship" name="emergency_relationship">
                                                            <option value="">Select Relationship</option>
                                                            <option value="Spouse" <?php echo ($form_data['emergency_relationship'] ?? '') === 'Spouse' ? 'selected' : ''; ?>>Spouse</option>
                                                            <option value="Parent" <?php echo ($form_data['emergency_relationship'] ?? '') === 'Parent' ? 'selected' : ''; ?>>Parent</option>
                                                            <option value="Sibling" <?php echo ($form_data['emergency_relationship'] ?? '') === 'Sibling' ? 'selected' : ''; ?>>Sibling</option>
                                                            <option value="Child" <?php echo ($form_data['emergency_relationship'] ?? '') === 'Child' ? 'selected' : ''; ?>>Child</option>
                                                            <option value="Friend" <?php echo ($form_data['emergency_relationship'] ?? '') === 'Friend' ? 'selected' : ''; ?>>Friend</option>
                                                            <option value="Other" <?php echo ($form_data['emergency_relationship'] ?? '') === 'Other' ? 'selected' : ''; ?>>Other</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Account Security Section -->
                                            <div class="form-section">
                                                <h5 class="section-title">
                                                    <i class="ri-lock-line"></i> Account Security
                                                </h5>
                                                <div class="row">
                                                    <div class="col-md-6 mb-3">
                                                        <label for="password" class="form-label">Password <span class="text-danger">*</span></label>
                                                        <div class="input-group">
                                                            <input type="password" class="form-control" id="password" name="password" required>
                                                            <button class="btn btn-outline-secondary" type="button" id="password-toggle">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                        </div>
                                                        <div class="password-strength mt-2" id="password-strength"></div>
                                                        <div class="password-requirements">
                                                            <div class="requirement unmet" id="req-length">
                                                                <i class="ri-close-circle-line"></i> At least 8 characters
                                                            </div>
                                                            <div class="requirement unmet" id="req-uppercase">
                                                                <i class="ri-close-circle-line"></i> One uppercase letter
                                                            </div>
                                                            <div class="requirement unmet" id="req-lowercase">
                                                                <i class="ri-close-circle-line"></i> One lowercase letter
                                                            </div>
                                                            <div class="requirement unmet" id="req-number">
                                                                <i class="ri-close-circle-line"></i> One number
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6 mb-3">
                                                        <label for="confirm_password" class="form-label">Confirm Password <span class="text-danger">*</span></label>
                                                        <div class="input-group">
                                                            <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                                            <button class="btn btn-outline-secondary" type="button" id="confirm-password-toggle">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                        </div>
                                                        <div class="mt-2" id="password-match"></div>
                                                    </div>
                                                </div>
                                            </div>

                                            <!-- Terms and Conditions -->
                                            <div class="form-section">
                                                <div class="form-check mb-3">
                                                    <input class="form-check-input" type="checkbox" id="terms_agreement" name="terms_agreement" required>
                                                    <label class="form-check-label" for="terms_agreement">
                                                        I agree to the <a href="#" class="text-primary">Terms and Conditions</a> and 
                                                        <a href="#" class="text-primary">Privacy Policy</a> <span class="text-danger">*</span>
                                                    </label>
                                                </div>
                                                <div class="form-check mb-3">
                                                    <input class="form-check-input" type="checkbox" id="data_consent" name="data_consent" required>
                                                    <label class="form-check-label" for="data_consent">
                                                        I consent to the processing of my personal data for registration and employment purposes <span class="text-danger">*</span>
                                                    </label>
                                                </div>
                                                <div class="form-check mb-4">
                                                    <input class="form-check-input" type="checkbox" id="marketing_consent" name="marketing_consent">
                                                    <label class="form-check-label" for="marketing_consent">
                                                        I would like to receive updates about training opportunities and company news
                                                    </label>
                                                </div>
                                            </div>

                                            <!-- Submit Button -->
                                            <div class="text-center">
                                                <button type="submit" class="btn btn-primary-custom btn-lg" id="submit-btn">
                                                    <i class="ri-user-add-line me-2"></i>Submit Application
                                                </button>
                                            </div>
                                        </form>

                                        <!-- Already have account -->
                                        <div class="mt-4 text-center">
                                            <p class="mb-0 text-muted">
                                                Already have an account? 
                                                <a href="login.php" class="fw-semibold text-primary text-decoration-none">Sign in here</a>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                                <!-- end col -->
                            </div>
                            <!-- end row -->
                        </div>
                        <!-- end card -->
                    </div>
                    <!-- end col -->
                </div>
                <!-- end row -->
            </div>
            <!-- end container -->
        </div>
        <!-- end auth page content -->

        <!-- footer -->
        <footer class="footer">
            <div class="container">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="text-center">
                            <p class="mb-0 text-muted">
                                &copy; <script>document.write(new Date().getFullYear())</script> 
                                <span class="text-primary fw-semibold">Ultrasure Insurance Platform</span> - 
                                Leading Digital Insurance Solutions in East Africa
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </footer>
        <!-- end Footer -->
    </div>
    <!-- end auth-page-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Select2 for better dropdowns
        $('.form-select').select2({
            theme: 'bootstrap-5',
            width: '100%'
        });

        // Password toggle functionality
        document.getElementById('password-toggle').addEventListener('click', function() {
            const passwordInput = document.getElementById('password');
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.className = 'ri-eye-off-line';
            } else {
                passwordInput.type = 'password';
                icon.className = 'ri-eye-line';
            }
        });

        document.getElementById('confirm-password-toggle').addEventListener('click', function() {
            const passwordInput = document.getElementById('confirm_password');
            const icon = this.querySelector('i');
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                icon.className = 'ri-eye-off-line';
            } else {
                passwordInput.type = 'password';
                icon.className = 'ri-eye-line';
            }
        });

        // Password strength checker
        const passwordInput = document.getElementById('password');
        const strengthBar = document.getElementById('password-strength');
        const requirements = {
            length: document.getElementById('req-length'),
            uppercase: document.getElementById('req-uppercase'),
            lowercase: document.getElementById('req-lowercase'),
            number: document.getElementById('req-number')
        };

        passwordInput.addEventListener('input', function() {
            const password = this.value;
            let score = 0;

            // Check length
            if (password.length >= 8) {
                requirements.length.className = 'requirement met';
                requirements.length.innerHTML = '<i class="ri-check-circle-line"></i> At least 8 characters';
                score++;
            } else {
                requirements.length.className = 'requirement unmet';
                requirements.length.innerHTML = '<i class="ri-close-circle-line"></i> At least 8 characters';
            }

            // Check uppercase
            if (/[A-Z]/.test(password)) {
                requirements.uppercase.className = 'requirement met';
                requirements.uppercase.innerHTML = '<i class="ri-check-circle-line"></i> One uppercase letter';
                score++;
            } else {
                requirements.uppercase.className = 'requirement unmet';
                requirements.uppercase.innerHTML = '<i class="ri-close-circle-line"></i> One uppercase letter';
            }

            // Check lowercase
            if (/[a-z]/.test(password)) {
                requirements.lowercase.className = 'requirement met';
                requirements.lowercase.innerHTML = '<i class="ri-check-circle-line"></i> One lowercase letter';
                score++;
            } else {
                requirements.lowercase.className = 'requirement unmet';
                requirements.lowercase.innerHTML = '<i class="ri-close-circle-line"></i> One lowercase letter';
            }

            // Check number
            if (/[0-9]/.test(password)) {
                requirements.number.className = 'requirement met';
                requirements.number.innerHTML = '<i class="ri-check-circle-line"></i> One number';
                score++;
            } else {
                requirements.number.className = 'requirement unmet';
                requirements.number.innerHTML = '<i class="ri-close-circle-line"></i> One number';
            }

            // Update strength bar
            const percentage = (score / 4) * 100;
            let color = '#dc3545'; // Red
            if (score >= 2) color = '#ffc107'; // Yellow
            if (score >= 3) color = '#fd7e14'; // Orange
            if (score === 4) color = '#28a745'; // Green

            strengthBar.style.width = percentage + '%';
            strengthBar.style.backgroundColor = color;
            strengthBar.style.height = '5px';
        });

        // Password match checker
        const confirmPasswordInput = document.getElementById('confirm_password');
        const passwordMatch = document.getElementById('password-match');

        function checkPasswordMatch() {
            const password = passwordInput.value;
            const confirmPassword = confirmPasswordInput.value;

            if (confirmPassword.length === 0) {
                passwordMatch.innerHTML = '';
                return;
            }

            if (password === confirmPassword) {
                passwordMatch.innerHTML = '<small class="text-success"><i class="ri-check-circle-line"></i> Passwords match</small>';
            } else {
                passwordMatch.innerHTML = '<small class="text-danger"><i class="ri-close-circle-line"></i> Passwords do not match</small>';
            }
        }

        confirmPasswordInput.addEventListener('input', checkPasswordMatch);
        passwordInput.addEventListener('input', checkPasswordMatch);

        // Phone number formatting for Kenya
        document.getElementById('phone_primary').addEventListener('input', function() {
            let value = this.value.replace(/\D/g, '');
            if (value.startsWith('254')) {
                value = '0' + value.slice(3);
            }
            this.value = value;
        });

        document.getElementById('phone_secondary').addEventListener('input', function() {
            let value = this.value.replace(/\D/g, '');
            if (value.startsWith('254')) {
                value = '0' + value.slice(3);
            }
            this.value = value;
        });

        // Form submission handler
        document.getElementById('registration-form').addEventListener('submit', function(event) {
            const submitBtn = document.getElementById('submit-btn');
            
            // Show loading state
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Processing...';
            submitBtn.disabled = true;
            
            // Basic client-side validation
            const requiredFields = this.querySelectorAll('[required]');
            let isValid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.classList.add('is-invalid');
                    isValid = false;
                } else {
                    field.classList.remove('is-invalid');
                    field.classList.add('is-valid');
                }
            });
            
            // Check password match
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (password !== confirmPassword) {
                document.getElementById('confirm_password').classList.add('is-invalid');
                isValid = false;
            }
            
            if (!isValid) {
                event.preventDefault();
                submitBtn.innerHTML = '<i class="ri-user-add-line me-2"></i>Submit Application';
                submitBtn.disabled = false;
                
                // Scroll to first invalid field
                const firstInvalid = this.querySelector('.is-invalid');
                if (firstInvalid) {
                    firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    firstInvalid.focus();
                }
            }
        });

        // Auto-focus on first field
        document.getElementById('first_name').focus();
    });
    </script>
</body>
</html>