<?php
$page_title = "Create New User";
require_once 'header.php';

$db = Database::getInstance()->connect();
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $full_name = trim($_POST['full_name']);
    $phone = trim($_POST['phone']);
    $country = $_POST['country'];
    $account_status = $_POST['account_status'];
    $initial_balance = floatval($_POST['initial_balance']);
    $referral_code = trim($_POST['referral_code']);
    $send_welcome_email = isset($_POST['send_welcome_email']);
    
    // Validation
    if (empty($username) || empty($email) || empty($password)) {
        $error = "Username, email, and password are required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email address";
    } elseif ($password !== $confirm_password) {
        $error = "Passwords do not match";
    } elseif (strlen($password) < 6) {
        $error = "Password must be at least 6 characters";
    } else {
        // Check if username or email exists
        $check_stmt = $db->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $check_stmt->execute([$username, $email]);
        
        if ($check_stmt->rowCount() > 0) {
            $error = "Username or email already exists";
        } else {
            try {
                $db->beginTransaction();
                
                // Hash password
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                
                // Generate referral code if not provided
                if (empty($referral_code)) {
                    $referral_code = strtoupper(substr(md5(time() . $username), 0, 8));
                }
                
                // Insert user
                $insert_stmt = $db->prepare("
                    INSERT INTO users (username, email, password, full_name, phone, country, 
                                      account_status, balance, referral_code, email_verified)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
                ");
                
                $insert_stmt->execute([
                    $username, $email, $hashed_password, $full_name, $phone, $country,
                    $account_status, $initial_balance, $referral_code
                ]);
                
                $user_id = $db->lastInsertId();
                
                // If initial balance > 0, record transaction
                if ($initial_balance > 0) {
                    $reference = 'ADM' . time() . rand(1000, 9999);
                    $tx_stmt = $db->prepare("
                        INSERT INTO transactions (user_id, type, amount, method, description, reference, status, admin_action_by)
                        VALUES (?, 'credit', ?, 'manual', 'Initial account funding by admin', ?, 'completed', ?)
                    ");
                    $tx_stmt->execute([$user_id, $initial_balance, $reference, $_SESSION['admin_id']]);
                }
                
                // Log the action
                $log_stmt = $db->prepare("
                    INSERT INTO activity_logs (admin_id, user_id, action, details)
                    VALUES (?, ?, 'user_create', ?)
                ");
                
                $log_stmt->execute([
                    $_SESSION['admin_id'],
                    $user_id,
                    json_encode([
                        'username' => $username,
                        'email' => $email,
                        'initial_balance' => $initial_balance,
                        'created_by' => $_SESSION['admin_username']
                    ])
                ]);
                
                // Send welcome email if requested
                if ($send_welcome_email) {
                    // Email sending logic here
                    $subject = "Welcome to " . SITE_NAME . "!";
                    $message = "Dear $username,\n\nYour account has been created successfully.\n\nUsername: $username\nPassword: [hidden]\n\nYou can login at: " . SITE_URL . "/login.php";
                    // mail($email, $subject, $message);
                }
                
                $db->commit();
                $success = "User created successfully! User ID: $user_id";
                
                // Clear form if successful
                $_POST = [];
                
            } catch (Exception $e) {
                $db->rollBack();
                $error = "Failed to create user: " . $e->getMessage();
            }
        }
    }
}
?>

<div class="container-fluid">
    <div class="max-w-4xl mx-auto">
        <div class="bg-white rounded-xl shadow p-6 mb-6">
            <div class="flex items-center justify-between mb-6">
                <h1 class="text-2xl font-bold">Create New User</h1>
                <a href="users.php" class="text-gray-600 hover:text-gray-800">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Users
                </a>
            </div>
            
            <?php if ($error): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
                <?php echo $error; ?>
            </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                <?php echo $success; ?>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="" class="space-y-6">
                <!-- Basic Information -->
                <div>
                    <h3 class="text-lg font-bold mb-4">Basic Information</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Username *</label>
                            <input type="text" name="username" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                   placeholder="johndoe">
                            <p class="text-xs text-gray-500 mt-1">3-20 characters, letters and numbers only</p>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Email Address *</label>
                            <input type="email" name="email" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                   placeholder="john@example.com">
                        </div>
                    </div>
                </div>
                
                <!-- Password -->
                <div>
                    <h3 class="text-lg font-bold mb-4">Password</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Password *</label>
                            <div class="relative">
                                <input type="password" name="password" required
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                       placeholder="••••••••">
                                <button type="button" onclick="togglePassword(this)"
                                        class="absolute right-3 top-2 text-gray-500 hover:text-gray-700">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                            <p class="text-xs text-gray-500 mt-1">Minimum 6 characters</p>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Confirm Password *</label>
                            <div class="relative">
                                <input type="password" name="confirm_password" required
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                       placeholder="••••••••">
                                <button type="button" onclick="togglePassword(this)"
                                        class="absolute right-3 top-2 text-gray-500 hover:text-gray-700">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Personal Information -->
                <div>
                    <h3 class="text-lg font-bold mb-4">Personal Information</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Full Name</label>
                            <input type="text" name="full_name" value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                   placeholder="John Doe">
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Phone Number</label>
                            <input type="text" name="phone" value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                   placeholder="+1234567890">
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Country</label>
                            <select name="country" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                                <option value="">Select Country</option>
                                <option value="US" <?php echo ($_POST['country'] ?? '') == 'US' ? 'selected' : ''; ?>>United States</option>
                                <option value="UK" <?php echo ($_POST['country'] ?? '') == 'UK' ? 'selected' : ''; ?>>United Kingdom</option>
                                <option value="CA" <?php echo ($_POST['country'] ?? '') == 'CA' ? 'selected' : ''; ?>>Canada</option>
                                <option value="AU" <?php echo ($_POST['country'] ?? '') == 'AU' ? 'selected' : ''; ?>>Australia</option>
                                <option value="NG" <?php echo ($_POST['country'] ?? '') == 'NG' ? 'selected' : ''; ?>>Nigeria</option>
                                <option value="IN" <?php echo ($_POST['country'] ?? '') == 'IN' ? 'selected' : ''; ?>>India</option>
                                <!-- Add more countries -->
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Initial Balance ($)</label>
                            <input type="number" step="0.01" name="initial_balance" value="<?php echo $_POST['initial_balance'] ?? '0.00'; ?>"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            <p class="text-xs text-gray-500 mt-1">Initial account balance</p>
                        </div>
                    </div>
                </div>
                
                <!-- Account Settings -->
                <div>
                    <h3 class="text-lg font-bold mb-4">Account Settings</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Account Status</label>
                            <select name="account_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                                <option value="pending">Pending</option>
                                <option value="active" selected>Active</option>
                                <option value="suspended">Suspended</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-gray-700 font-medium mb-2">Referral Code (Optional)</label>
                            <input type="text" name="referral_code" value="<?php echo htmlspecialchars($_POST['referral_code'] ?? ''); ?>"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                   placeholder="Leave empty to auto-generate">
                        </div>
                    </div>
                </div>
                
                <!-- Options -->
                <div class="border-t pt-6">
                    <div class="space-y-3">
                        <div class="flex items-center">
                            <input type="checkbox" id="send_welcome_email" name="send_welcome_email" value="1" checked
                                   class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                            <label for="send_welcome_email" class="ml-2 text-gray-700">
                                Send welcome email with login details
                            </label>
                        </div>
                        
                        <div class="flex items-center">
                            <input type="checkbox" id="require_password_change" name="require_password_change" value="1"
                                   class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                            <label for="require_password_change" class="ml-2 text-gray-700">
                                Require password change on first login
                            </label>
                        </div>
                        
                        <div class="flex items-center">
                            <input type="checkbox" id="email_verified" name="email_verified" value="1" checked
                                   class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                            <label for="email_verified" class="ml-2 text-gray-700">
                                Mark email as verified
                            </label>
                        </div>
                    </div>
                </div>
                
                <!-- Submit -->
                <div class="border-t pt-6">
                    <div class="flex justify-end space-x-4">
                        <a href="users.php" class="px-6 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                            Cancel
                        </a>
                        <button type="submit" 
                                class="bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold px-6 py-3 rounded-lg hover:opacity-90">
                            <i class="fas fa-user-plus mr-2"></i>Create User
                        </button>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Quick Help -->
        <div class="bg-blue-50 border border-blue-200 rounded-xl p-6">
            <h4 class="font-bold text-blue-800 mb-3">
                <i class="fas fa-info-circle mr-2"></i>Quick Help
            </h4>
            <ul class="space-y-2 text-sm text-blue-700">
                <li>• Usernames must be unique and cannot be changed later</li>
                <li>• Email addresses must be valid and unique</li>
                <li>• Initial balance will be credited to the user's account immediately</li>
                <li>• Referral codes must be unique if manually specified</li>
                <li>• Welcome emails include login credentials (if enabled)</li>
                <li>• Consider using strong passwords for user accounts</li>
            </ul>
        </div>
    </div>
</div>

<script>
function togglePassword(button) {
    const input = button.parentElement.querySelector('input');
    const icon = button.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
}

// Password strength indicator
document.querySelector('input[name="password"]').addEventListener('input', function(e) {
    const password = e.target.value;
    const strength = calculatePasswordStrength(password);
    updateStrengthIndicator(strength);
});

function calculatePasswordStrength(password) {
    let score = 0;
    
    if (password.length >= 6) score++;
    if (password.length >= 8) score++;
    if (/[A-Z]/.test(password)) score++;
    if (/[0-9]/.test(password)) score++;
    if (/[^A-Za-z0-9]/.test(password)) score++;
    
    return Math.min(score, 5);
}

function updateStrengthIndicator(strength) {
    const indicator = document.getElementById('passwordStrength');
    if (!indicator) return;
    
    const colors = ['bg-red-500', 'bg-orange-500', 'bg-yellow-500', 'bg-blue-500', 'bg-green-500'];
    const texts = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong'];
    
    indicator.className = h-2 rounded ${colors[strength - 1] || 'bg-red-500'} w-${strength * 20}/5;
    document.getElementById('strengthText').textContent = texts[strength - 1] || 'Very Weak';
}

// Generate random password
function generatePassword() {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
    let password = '';
    for (let i = 0; i < 12; i++) {
        password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    document.querySelector('input[name="password"]').value = password;
    document.querySelector('input[name="confirm_password"]').value = password;
    
    // Update strength indicator
    const strength = calculatePasswordStrength(password);
    updateStrengthIndicator(strength);
}
</script>

<?php require_once 'footer.php'; ?>