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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check permissions
/*$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT HasPermission(?, 'agents_create') as has_permission");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$permission_result = $stmt->get_result()->fetch_assoc();

if (!$permission_result['has_permission']) {
    header('Location: index.php?error=no_permission');
    exit();
}*/

$errors = [];
$success_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate and sanitize input
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone_number = trim($_POST['phone_number']);
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $role_id = (int)$_POST['role_id'];
    $branch_id = !empty($_POST['branch_id']) ? (int)$_POST['branch_id'] : null;
    $supervisor_id = !empty($_POST['supervisor_id']) ? (int)$_POST['supervisor_id'] : null;
    $license_number = trim($_POST['license_number']);
    $license_expiry = !empty($_POST['license_expiry']) ? $_POST['license_expiry'] : null;
    $commission_rate = (float)$_POST['commission_rate'];
    $target_monthly = (float)$_POST['target_monthly'];
    $date_of_birth = !empty($_POST['date_of_birth']) ? $_POST['date_of_birth'] : null;
    $gender = $_POST['gender'];
    $national_id = trim($_POST['national_id']);
    $address = trim($_POST['address']);
    $emergency_contact = trim($_POST['emergency_contact']);
    $emergency_phone = trim($_POST['emergency_phone']);
    $hire_date = !empty($_POST['hire_date']) ? $_POST['hire_date'] : date('Y-m-d');

    // Validation
    if (empty($full_name)) $errors[] = "Full name is required";
    if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email is required";
    if (empty($username)) $errors[] = "Username is required";
    if (empty($password)) $errors[] = "Password is required";
    if ($password !== $confirm_password) $errors[] = "Passwords do not match";
    if (strlen($password) < 8) $errors[] = "Password must be at least 8 characters";
    if (empty($role_id)) $errors[] = "Role is required";
    if ($commission_rate < 0 || $commission_rate > 100) $errors[] = "Commission rate must be between 0 and 100";

    // Check for existing username/email
    if (empty($errors)) {
        $check_sql = "SELECT COUNT(*) as count FROM users WHERE username = ? OR email = ?";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->bind_param("ss", $username, $email);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result()->fetch_assoc();
        
        if ($check_result['count'] > 0) {
            $errors[] = "Username or email already exists";
        }
    }

    // Generate agent code
    $agent_code = '';
    if (empty($errors)) {
        // Generate unique agent code (e.g., AG2024001)
        $year = date('Y');
        $code_sql = "SELECT MAX(CAST(SUBSTRING(agent_code, 7) AS UNSIGNED)) as max_code 
                     FROM users WHERE agent_code LIKE 'AG{$year}%'";
        $code_result = $conn->query($code_sql);
        $max_code = $code_result->fetch_assoc()['max_code'] ?? 0;
        $new_code = $max_code + 1;
        $agent_code = 'AG' . $year . str_pad($new_code, 3, '0', STR_PAD_LEFT);
    }

    // Insert new agent
    if (empty($errors)) {
        $conn->begin_transaction();
        
        try {
            // Hash password
            $password_hash = password_hash($password, PASSWORD_DEFAULT);
            
            // Insert user
            $insert_sql = "INSERT INTO users (
                username, email, password_hash, full_name, phone_number, role_id, 
                agent_code, license_number, license_expiry, branch_id, supervisor_id, 
                commission_rate, target_monthly, status, date_of_birth, gender, 
                national_id, address, emergency_contact, emergency_phone, hire_date
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ACTIVE', ?, ?, ?, ?, ?, ?, ?)";
            
            $insert_stmt = $conn->prepare($insert_sql);
            $insert_stmt->bind_param("sssssississsssssssss", 
                $username, $email, $password_hash, $full_name, $phone_number, $role_id,
                $agent_code, $license_number, $license_expiry, $branch_id, $supervisor_id,
                $commission_rate, $target_monthly, $date_of_birth, $gender,
                $national_id, $address, $emergency_contact, $emergency_phone, $hire_date
            );
            
            if ($insert_stmt->execute()) {
                $new_user_id = $conn->insert_id;
                
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values) 
                           VALUES (?, 'CREATE', 'AGENT', ?, 'USER', ?)";
                $log_stmt = $conn->prepare($log_sql);
                $log_data = json_encode([
                    'agent_code' => $agent_code,
                    'full_name' => $full_name,
                    'email' => $email,
                    'created_by' => $_SESSION['full_name']
                ]);
                $log_stmt->bind_param("iis", $user_id, $new_user_id, $log_data);
                $log_stmt->execute();
                
                $conn->commit();
                
                // Send welcome email (optional)
                // You can implement email sending here
                
                $success_message = "Agent created successfully! Agent Code: $agent_code";
                
                // Redirect after successful creation
                header("Location: list_agents.php?success=created&agent_code=$agent_code");
                exit();
                
            } else {
                throw new Exception("Failed to create agent account");
            }
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Error creating agent: " . $e->getMessage();
        }
    }
}

// Get branches for dropdown
$branches_sql = "SELECT branch_id, branch_name FROM branches WHERE is_active = 1 ORDER BY branch_name";
$branches_result = $conn->query($branches_sql);

// Get agent roles for dropdown
$roles_sql = "SELECT role_id, role_name FROM user_roles WHERE role_name LIKE '%Agent%' ORDER BY role_name";
$roles_result = $conn->query($roles_sql);

// Get supervisors (agents and managers)
$supervisors_sql = "SELECT u.user_id, u.full_name, u.agent_code, ur.role_name 
                   FROM users u 
                   INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                   WHERE u.status = 'ACTIVE' 
                   AND (ur.role_name LIKE '%Supervisor%' OR ur.role_name LIKE '%Manager%' OR ur.role_name LIKE '%Senior%')
                   ORDER BY u.full_name";
$supervisors_result = $conn->query($supervisors_sql);

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Agent - Ultrasure Insurance Platform')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .form-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        .form-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px 15px 0 0;
            padding: 20px;
        }
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        .step {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 10px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .step.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .step.completed {
            background: #28a745;
            color: white;
        }
        .step.inactive {
            background: #e9ecef;
            color: #6c757d;
        }
        .step-line {
            height: 2px;
            background: #e9ecef;
            width: 80px;
            margin-top: 19px;
        }
        .step-line.completed {
            background: #28a745;
        }
        .form-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .section-title {
            color: #495057;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e9ecef;
        }
        .password-strength {
            margin-top: 5px;
        }
        .strength-meter {
            height: 5px;
            border-radius: 3px;
            transition: all 0.3s ease;
        }
        .required-field {
            color: #dc3545;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Add New Agent</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_agents.php">Agents</a></li>
                                        <li class="breadcrumb-item active">Add Agent</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Display Messages -->
                    <?php if (!empty($errors)): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <i class="ri-error-warning-line me-2"></i>
                                    <strong>Please correct the following errors:</strong>
                                    <ul class="mb-0 mt-2">
                                        <?php foreach ($errors as $error): ?>
                                            <li><?php echo htmlspecialchars($error); ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                    <i class="ri-checkbox-circle-line me-2"></i>
                                    <?php echo htmlspecialchars($success_message); ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Agent Form -->
                    <div class="row justify-content-center">
                        <div class="col-xl-10">
                            <form method="POST" id="agentForm" novalidate>
                                
                                <!-- Step Indicator -->
                                <div class="step-indicator">
                                    <div class="step active" id="step1">1</div>
                                    <div class="step-line" id="line1"></div>
                                    <div class="step inactive" id="step2">2</div>
                                    <div class="step-line" id="line2"></div>
                                    <div class="step inactive" id="step3">3</div>
                                </div>

                                <!-- Step 1: Basic Information -->
                                <div class="form-section" id="section1">
                                    <h5 class="section-title">
                                        <i class="ri-user-line me-2"></i>Basic Information
                                    </h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Full Name <span class="required-field">*</span></label>
                                            <input type="text" class="form-control" name="full_name" 
                                                   value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>" required>
                                            <div class="invalid-feedback">Please provide a valid full name.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Email Address <span class="required-field">*</span></label>
                                            <input type="email" class="form-control" name="email" 
                                                   value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" required>
                                            <div class="invalid-feedback">Please provide a valid email address.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Phone Number</label>
                                            <input type="tel" class="form-control" name="phone_number" 
                                                   value="<?php echo htmlspecialchars($_POST['phone_number'] ?? ''); ?>"
                                                   placeholder="+254 700 000 000">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">National ID</label>
                                            <input type="text" class="form-control" name="national_id" 
                                                   value="<?php echo htmlspecialchars($_POST['national_id'] ?? ''); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Date of Birth</label>
                                            <input type="date" class="form-control" name="date_of_birth" 
                                                   value="<?php echo htmlspecialchars($_POST['date_of_birth'] ?? ''); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Gender</label>
                                            <select class="form-select" name="gender">
                                                <option value="">Select Gender</option>
                                                <option value="MALE" <?php echo ($_POST['gender'] ?? '') == 'MALE' ? 'selected' : ''; ?>>Male</option>
                                                <option value="FEMALE" <?php echo ($_POST['gender'] ?? '') == 'FEMALE' ? 'selected' : ''; ?>>Female</option>
                                                <option value="OTHER" <?php echo ($_POST['gender'] ?? '') == 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                            </select>
                                        </div>
                                        <div class="col-12 mb-3">
                                            <label class="form-label">Address</label>
                                            <textarea class="form-control" name="address" rows="3"><?php echo htmlspecialchars($_POST['address'] ?? ''); ?></textarea>
                                        </div>
                                    </div>
                                    <div class="d-flex justify-content-end">
                                        <button type="button" class="btn btn-primary" onclick="nextStep(1)">
                                            Next <i class="ri-arrow-right-line ms-1"></i>
                                        </button>
                                    </div>
                                </div>

                                <!-- Step 2: Account & Role Information -->
                                <div class="form-section d-none" id="section2">
                                    <h5 class="section-title">
                                        <i class="ri-shield-user-line me-2"></i>Account & Role Information
                                    </h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Username <span class="required-field">*</span></label>
                                            <input type="text" class="form-control" name="username" 
                                                   value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required>
                                            <div class="form-text">Username must be unique and will be used for login</div>
                                            <div class="invalid-feedback">Please provide a valid username.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Role <span class="required-field">*</span></label>
                                            <select class="form-select" name="role_id" required>
                                                <option value="">Select Role</option>
                                                <?php while($role = $roles_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $role['role_id']; ?>" 
                                                            <?php echo ($_POST['role_id'] ?? '') == $role['role_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($role['role_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                            <div class="invalid-feedback">Please select a role.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Password <span class="required-field">*</span></label>
                                            <input type="password" class="form-control" name="password" id="password" required>
                                            <div class="password-strength">
                                                <div class="strength-meter bg-light" id="strengthMeter"></div>
                                                <small class="text-muted" id="strengthText">Password strength will appear here</small>
                                            </div>
                                            <div class="invalid-feedback">Password must be at least 8 characters long.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Confirm Password <span class="required-field">*</span></label>
                                            <input type="password" class="form-control" name="confirm_password" id="confirmPassword" required>
                                            <div class="invalid-feedback" id="passwordMismatch">Passwords do not match.</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Branch</label>
                                            <select class="form-select" name="branch_id">
                                                <option value="">Select Branch</option>
                                                <?php while($branch = $branches_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $branch['branch_id']; ?>" 
                                                            <?php echo ($_POST['branch_id'] ?? '') == $branch['branch_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($branch['branch_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Supervisor</label>
                                            <select class="form-select" name="supervisor_id">
                                                <option value="">Select Supervisor</option>
                                                <?php while($supervisor = $supervisors_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $supervisor['user_id']; ?>" 
                                                            <?php echo ($_POST['supervisor_id'] ?? '') == $supervisor['user_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($supervisor['full_name']); ?>
                                                        <?php if($supervisor['agent_code']): ?>
                                                            (<?php echo htmlspecialchars($supervisor['agent_code']); ?>)
                                                        <?php endif; ?>
                                                        - <?php echo htmlspecialchars($supervisor['role_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Hire Date</label>
                                            <input type="date" class="form-control" name="hire_date" 
                                                   value="<?php echo htmlspecialchars($_POST['hire_date'] ?? date('Y-m-d')); ?>">
                                        </div>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <button type="button" class="btn btn-secondary" onclick="prevStep(2)">
                                            <i class="ri-arrow-left-line me-1"></i> Previous
                                        </button>
                                        <button type="button" class="btn btn-primary" onclick="nextStep(2)">
                                            Next <i class="ri-arrow-right-line ms-1"></i>
                                        </button>
                                    </div>
                                </div>

                                <!-- Step 3: Professional Information -->
                                <div class="form-section d-none" id="section3">
                                    <h5 class="section-title">
                                        <i class="ri-briefcase-line me-2"></i>Professional Information
                                    </h5>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">License Number</label>
                                            <input type="text" class="form-control" name="license_number" 
                                                   value="<?php echo htmlspecialchars($_POST['license_number'] ?? ''); ?>"
                                                   placeholder="e.g., IRA/AGT/2024/001">
                                            <div class="form-text">Insurance Regulatory Authority license number</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">License Expiry Date</label>
                                            <input type="date" class="form-control" name="license_expiry" 
                                                   value="<?php echo htmlspecialchars($_POST['license_expiry'] ?? ''); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Commission Rate (%)</label>
                                            <input type="number" class="form-control" name="commission_rate" 
                                                   value="<?php echo htmlspecialchars($_POST['commission_rate'] ?? '5'); ?>"
                                                   min="0" max="100" step="0.1">
                                            <div class="form-text">Commission percentage (0-100)</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Monthly Target (KSH)</label>
                                            <input type="number" class="form-control" name="target_monthly" 
                                                   value="<?php echo htmlspecialchars($_POST['target_monthly'] ?? '50000'); ?>"
                                                   min="0" step="1000">
                                            <div class="form-text">Monthly sales target in KSH</div>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Emergency Contact Name</label>
                                            <input type="text" class="form-control" name="emergency_contact" 
                                                   value="<?php echo htmlspecialchars($_POST['emergency_contact'] ?? ''); ?>">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Emergency Contact Phone</label>
                                            <input type="tel" class="form-control" name="emergency_phone" 
                                                   value="<?php echo htmlspecialchars($_POST['emergency_phone'] ?? ''); ?>"
                                                   placeholder="+254 700 000 000">
                                        </div>
                                    </div>
                                    
                                    <!-- Agent Terms and Conditions -->
                                    <div class="card border-info">
                                        <div class="card-header bg-info text-white">
                                            <h6 class="mb-0"><i class="ri-information-line me-2"></i>Agent Agreement</h6>
                                        </div>
                                        <div class="card-body">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="agentTerms" required>
                                                <label class="form-check-label" for="agentTerms">
                                                    I confirm that:
                                                </label>
                                            </div>
                                            <ul class="list-unstyled ms-4 mt-2">
                                                <li>✓ The agent information provided is accurate and complete</li>
                                                <li>✓ The agent agrees to comply with Ultrasure's policies and procedures</li>
                                                <li>✓ The agent will maintain confidentiality of customer information</li>
                                                <li>✓ The agent holds valid insurance regulatory licenses (if applicable)</li>
                                                <li>✓ The agent will use the platform responsibly and ethically</li>
                                            </ul>
                                        </div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-between mt-4">
                                        <button type="button" class="btn btn-secondary" onclick="prevStep(3)">
                                            <i class="ri-arrow-left-line me-1"></i> Previous
                                        </button>
                                        <div>
                                            <button type="button" class="btn btn-outline-primary me-2" onclick="saveAsDraft()">
                                                <i class="ri-save-line me-1"></i> Save as Draft
                                            </button>
                                            <button type="submit" class="btn btn-success" id="submitBtn">
                                                <i class="ri-user-add-line me-1"></i> Create Agent
                                            </button>
                                        </div>
                                    </div>
                                </div>

                            </form>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
    let currentStep = 1;
    const totalSteps = 3;

    // Step navigation functions
    function nextStep(step) {
        if (validateStep(step)) {
            currentStep++;
            updateStepDisplay();
        }
    }

    function prevStep(step) {
        currentStep--;
        updateStepDisplay();
    }

    function updateStepDisplay() {
        // Hide all sections
        for (let i = 1; i <= totalSteps; i++) {
            document.getElementById(`section${i}`).classList.add('d-none');
            document.getElementById(`step${i}`).className = 'step inactive';
            if (i < totalSteps) {
                document.getElementById(`line${i}`).className = 'step-line';
            }
        }

        // Show current section and update step indicators
        document.getElementById(`section${currentStep}`).classList.remove('d-none');
        
        for (let i = 1; i <= totalSteps; i++) {
            if (i < currentStep) {
                document.getElementById(`step${i}`).className = 'step completed';
                if (i < totalSteps) {
                    document.getElementById(`line${i}`).className = 'step-line completed';
                }
            } else if (i === currentStep) {
                document.getElementById(`step${i}`).className = 'step active';
            }
        }
    }

    function validateStep(step) {
        const section = document.getElementById(`section${step}`);
        const inputs = section.querySelectorAll('input[required], select[required]');
        let isValid = true;

        inputs.forEach(input => {
            if (!input.value.trim()) {
                input.classList.add('is-invalid');
                isValid = false;
            } else {
                input.classList.remove('is-invalid');
                input.classList.add('is-valid');
            }
        });

        // Additional validation for step 2 (passwords)
        if (step === 2) {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            if (password.length < 8) {
                document.getElementById('password').classList.add('is-invalid');
                isValid = false;
            }
            
            if (password !== confirmPassword) {
                document.getElementById('confirmPassword').classList.add('is-invalid');
                isValid = false;
            }
        }

        // Validation for step 3 (terms checkbox)
        if (step === 3) {
            const termsCheckbox = document.getElementById('agentTerms');
            if (!termsCheckbox.checked) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Agreement Required',
                    text: 'Please confirm the agent agreement to proceed.'
                });
                isValid = false;
            }
        }

        if (!isValid) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please fill in all required fields correctly.'
            });
        }

        return isValid;
    }

    // Password strength checker
    function checkPasswordStrength(password) {
        let strength = 0;
        let feedback = '';
        
        if (password.length >= 8) strength++;
        if (password.match(/[a-z]/)) strength++;
        if (password.match(/[A-Z]/)) strength++;
        if (password.match(/[0-9]/)) strength++;
        if (password.match(/[^a-zA-Z0-9]/)) strength++;
        
        const meter = document.getElementById('strengthMeter');
        const text = document.getElementById('strengthText');
        
        switch (strength) {
            case 0:
            case 1:
                meter.className = 'strength-meter bg-danger';
                meter.style.width = '20%';
                feedback = 'Very Weak';
                break;
            case 2:
                meter.className = 'strength-meter bg-warning';
                meter.style.width = '40%';
                feedback = 'Weak';
                break;
            case 3:
                meter.className = 'strength-meter bg-info';
                meter.style.width = '60%';
                feedback = 'Fair';
                break;
            case 4:
                meter.className = 'strength-meter bg-primary';
                meter.style.width = '80%';
                feedback = 'Good';
                break;
            case 5:
                meter.className = 'strength-meter bg-success';
                meter.style.width = '100%';
                feedback = 'Strong';
                break;
        }
        
        text.textContent = feedback;
    }

    // Event listeners
    document.getElementById('password').addEventListener('input', function() {
        checkPasswordStrength(this.value);
    });

    document.getElementById('confirmPassword').addEventListener('input', function() {
        const password = document.getElementById('password').value;
        const confirmPassword = this.value;
        
        if (password !== confirmPassword) {
            this.classList.add('is-invalid');
        } else {
            this.classList.remove('is-invalid');
            this.classList.add('is-valid');
        }
    });

    // Form submission
    document.getElementById('agentForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (!validateStep(3)) {
            return;
        }
        
        const submitBtn = document.getElementById('submitBtn');
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Creating Agent...';
        submitBtn.disabled = true;
        
        // Submit the form
        this.submit();
    });

    // Save as draft function
    function saveAsDraft() {
        Swal.fire({
            title: 'Save as Draft?',
            text: 'This will save the current information and create an inactive agent account.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Save Draft',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Add hidden field to indicate draft status
                const draftInput = document.createElement('input');
                draftInput.type = 'hidden';
                draftInput.name = 'save_as_draft';
                draftInput.value = '1';
                document.getElementById('agentForm').appendChild(draftInput);
                
                // Submit form
                document.getElementById('agentForm').submit();
            }
        });
    }

    // Auto-generate username from full name
    document.querySelector('input[name="full_name"]').addEventListener('blur', function() {
        const fullName = this.value.trim();
        const usernameField = document.querySelector('input[name="username"]');
        
        if (fullName && !usernameField.value) {
            // Generate username from full name
            const username = fullName.toLowerCase()
                .replace(/\s+/g, '.')
                .replace(/[^a-z0-9.]/g, '');
            usernameField.value = username;
        }
    });

    // Auto-generate email from username
    document.querySelector('input[name="username"]').addEventListener('blur', function() {
        const username = this.value.trim();
        const emailField = document.querySelector('input[name="email"]');
        
        if (username && !emailField.value) {
            emailField.value = username + '@ultrasure.co.ke';
        }
    });

    // Initialize tooltips
    document.addEventListener('DOMContentLoaded', function() {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>