<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is admin
adminOnly();

$user = getUserContext();
$pdo = getDB();

// Check if editing existing user
$edit_mode = isset($_GET['id']) && !empty($_GET['id']);
$user_id = $edit_mode ? intval($_GET['id']) : 0;

$errors = [];
$success = '';
$user_data = [];
$user_profile = [];

// If editing, load existing data
if ($edit_mode) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user_data = $stmt->fetch();

    if (!$user_data) {
        header('Location: users.php');
        exit;
    }

    $stmt = $pdo->prepare("SELECT * FROM user_profiles WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $user_profile = $stmt->fetch() ?: [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $role = $_POST['role'] ?? 'student';
    $email_verified = isset($_POST['email_verified']) ? 1 : 0;
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $send_welcome_email = isset($_POST['send_welcome_email']);
    $change_password = isset($_POST['change_password']);

    // Validation
    if (!$username) {
        $errors[] = 'Username is required.';
    } elseif (!preg_match('/^[a-zA-Z0-9_]{3,50}$/', $username)) {
        $errors[] = 'Username must be 3-50 characters and contain only letters, numbers, and underscores.';
    }

    if (!$email) {
        $errors[] = 'Email is required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address.';
    }

    // Password validation - required for new users, optional for edits
    if (!$edit_mode && !$password) {
        $errors[] = 'Password is required.';
    } elseif ($password && strlen($password) < 6) {
        $errors[] = 'Password must be at least 6 characters long.';
    } elseif ($password && $password !== $confirm_password) {
        $errors[] = 'Passwords do not match.';
    }

    if (!in_array($role, getAllRoles())) {
        $errors[] = 'Invalid role selected.';
    }

    // Check if username or email already exists (excluding current user in edit mode)
    if (empty($errors)) {
        $query = "SELECT COUNT(*) FROM users WHERE (username = ? OR email = ?)";
        $params = [$username, $email];
        if ($edit_mode) {
            $query .= " AND id != ?";
            $params[] = $user_id;
        }
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        if ($stmt->fetchColumn() > 0) {
            $errors[] = 'Username or email already exists.';
        }
    }

    // Create or update user if no errors
    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            if ($edit_mode) {
                // Update existing user
                $update_data = [
                    'username' => $username,
                    'email' => $email,
                    'role' => $role,
                    'email_verified' => $email_verified
                ];

                if ($change_password && $password) {
                    $update_data['password'] = password_hash($password, PASSWORD_DEFAULT);
                }

                $set_parts = [];
                foreach (array_keys($update_data) as $column) {
                    $set_parts[] = "$column = ?";
                }
                $set_clause = implode(', ', $set_parts);

                $stmt = $pdo->prepare("UPDATE users SET $set_clause WHERE id = ?");
                $stmt->execute(array_merge(array_values($update_data), [$user_id]));

                // Update or insert profile
                $profile_data = [
                    'first_name' => $first_name,
                    'last_name' => $last_name,
                    'phone' => $phone,
                    'updated_at' => date('Y-m-d H:i:s')
                ];

                if (empty($user_profile)) {
                    // Insert new profile
                    $profile_data['user_id'] = $user_id;
                    $columns = implode(', ', array_keys($profile_data));
                    $placeholders = str_repeat('?, ', count($profile_data) - 1) . '?';
                    $stmt = $pdo->prepare("INSERT INTO user_profiles ($columns) VALUES ($placeholders)");
                    $stmt->execute(array_values($profile_data));
                } else {
                    // Update existing profile
                    $set_parts = [];
                    foreach (array_keys($profile_data) as $column) {
                        $set_parts[] = "$column = ?";
                    }
                    $set_clause = implode(', ', $set_parts);
                    $stmt = $pdo->prepare("UPDATE user_profiles SET $set_clause WHERE user_id = ?");
                    $stmt->execute(array_merge(array_values($profile_data), [$user_id]));
                }

                // Log activity
                $changes = [];
                if ($username !== $user_data['username']) $changes[] = "username: {$user_data['username']} → $username";
                if ($email !== $user_data['email']) $changes[] = "email: {$user_data['email']} → $email";
                if ($role !== $user_data['role']) $changes[] = "role: {$user_data['role']} → $role";
                if ($email_verified != $user_data['email_verified']) $changes[] = "email_verified: " . ($user_data['email_verified'] ? 'true' : 'false') . " → " . ($email_verified ? 'true' : 'false');
                if ($change_password) $changes[] = "password changed";

                if (!empty($changes)) {
                    $stmt = $pdo->prepare("
                        INSERT INTO user_activities (user_id, action_type, action_description, ip_address, user_agent)
                        VALUES (?, 'user_updated', ?, ?, ?)
                    ");
                    $stmt->execute([
                        $_SESSION['user_id'],
                        "Updated user {$username}: " . implode(', ', $changes),
                        $_SERVER['REMOTE_ADDR'] ?? '',
                        $_SERVER['HTTP_USER_AGENT'] ?? ''
                    ]);
                }

                $success = 'User updated successfully!';
            } else {
                // Create new user
                // Hash password
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);

                // Generate email verification token if not verified
                $verification_token = $email_verified ? null : bin2hex(random_bytes(32));

                // Insert user
                $stmt = $pdo->prepare("
                    INSERT INTO users (username, email, password, role, email_verified, email_verification_token, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$username, $email, $hashed_password, $role, $email_verified, $verification_token]);
                $user_id = $pdo->lastInsertId();

                // Create user profile if additional info provided
                if ($first_name || $last_name || $phone) {
                    $stmt = $pdo->prepare("
                        INSERT INTO user_profiles (user_id, first_name, last_name, phone)
                        VALUES (?, ?, ?, ?)
                    ");
                    $stmt->execute([$user_id, $first_name, $last_name, $phone]);
                }

                // Log activity
                $stmt = $pdo->prepare("
                    INSERT INTO user_activities (user_id, action_type, action_description, ip_address, user_agent)
                    VALUES (?, 'user_created', ?, ?, ?)
                ");
                $stmt->execute([
                    $_SESSION['user_id'],
                    "Created new user: $username ($role)",
                    $_SERVER['REMOTE_ADDR'] ?? '',
                    $_SERVER['HTTP_USER_AGENT'] ?? ''
                ]);

                // Add welcome achievement
                $stmt = $pdo->prepare("
                    INSERT INTO user_achievements (user_id, achievement_type, title, description, icon)
                    VALUES (?, 'welcome', 'Welcome to the LMS', 'Account created successfully', 'fas fa-user-plus')
                ");
                $stmt->execute([$user_id]);

                $success = 'User created successfully!';

                // Send welcome email if requested
                if ($send_welcome_email) {
                    // TODO: Implement welcome email sending
                    // sendWelcomeEmail($email, $username, $password);
                }

                // Reset form for new user creation
                $username = $email = $password = $confirm_password = $first_name = $last_name = $phone = '';
                $role = 'student';
                $email_verified = 0;
            }

            $pdo->commit();

        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = 'Error ' . ($edit_mode ? 'updating' : 'creating') . ' user: ' . $e->getMessage();
        }
    }
}

$page_title = $edit_mode ? 'Edit User' : 'Create New User';
include 'includes/admin_header.php';
?>

<div class="user-form-page">
    <div class="form-header">
        <h1><i class="fas fa-<?php echo $edit_mode ? 'user-edit' : 'user-plus'; ?>"></i> <?php echo $edit_mode ? 'Edit User' : 'Create New User'; ?></h1>
        <p><?php echo $edit_mode ? 'Modify user information, role, and permissions.' : 'Add a new user to the system with appropriate role and permissions.'; ?></p>
        <div class="header-actions">
            <?php if ($edit_mode): ?>
                <a href="user_profile.php?id=<?php echo $user_id; ?>" class="btn btn-secondary">
                    <i class="fas fa-eye"></i> View Profile
                </a>
            <?php endif; ?>
            <a href="users.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Users
            </a>
        </div>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="alert alert-success">
            <?php echo htmlspecialchars($success); ?>
        </div>
    <?php endif; ?>

    <div class="form-container">
        <form method="POST" class="user-form">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">

            <div class="form-section">
                <h2><i class="fas fa-user"></i> Account Information</h2>

                <div class="form-row">
                    <div class="form-group">
                        <label for="username">Username *</label>
                        <input type="text" id="username" name="username" required
                                value="<?php echo htmlspecialchars($edit_mode ? $user_data['username'] : ($username ?? '')); ?>"
                                pattern="[a-zA-Z0-9_]{3,50}" title="3-50 characters, letters, numbers, underscores only">
                        <small><?php echo $edit_mode ? 'User ID: ' . $user_data['id'] : 'Unique identifier for login'; ?></small>
                    </div>

                    <div class="form-group">
                        <label for="email">Email Address *</label>
                        <input type="email" id="email" name="email" required
                                value="<?php echo htmlspecialchars($edit_mode ? $user_data['email'] : ($email ?? '')); ?>">
                        <small>Used for login and notifications</small>
                    </div>
                </div>

                <?php if (!$edit_mode): ?>
                <div class="form-row">
                    <div class="form-group">
                        <label for="password">Password *</label>
                        <input type="password" id="password" name="password" required minlength="6">
                        <small>Minimum 6 characters</small>
                    </div>

                    <div class="form-group">
                        <label for="confirm_password">Confirm Password *</label>
                        <input type="password" id="confirm_password" name="confirm_password" required minlength="6">
                    </div>
                </div>
                <?php endif; ?>

                <div class="form-row">
                    <div class="form-group">
                        <label for="role">Role *</label>
                        <select id="role" name="role" required>
                            <?php foreach (getAllRoles() as $role_option): ?>
                                <option value="<?php echo $role_option; ?>" <?php echo ($edit_mode ? $user_data['role'] : ($role ?? 'student')) === $role_option ? 'selected' : ''; ?>>
                                    <?php echo getRoleDisplayName($role_option); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="checkbox-label">
                            <input type="checkbox" name="email_verified" <?php echo ($edit_mode ? $user_data['email_verified'] : ($email_verified ?? 0)) ? 'checked' : ''; ?>>
                            Email Verified
                        </label>
                        <small><?php echo $edit_mode ? 'Last login: ' . ($user_data['last_login'] ? formatDate($user_data['last_login']) : 'Never') : 'Skip email verification process'; ?></small>
                    </div>
                </div>
            </div>

            <div class="form-section">
                <h2><i class="fas fa-id-card"></i> Profile Information</h2>
                <p class="form-help">Optional information to enhance the user profile.</p>

                <div class="form-row">
                    <div class="form-group">
                        <label for="first_name">First Name</label>
                        <input type="text" id="first_name" name="first_name"
                                value="<?php echo htmlspecialchars($edit_mode ? ($user_profile['first_name'] ?? '') : ($first_name ?? '')); ?>">
                    </div>

                    <div class="form-group">
                        <label for="last_name">Last Name</label>
                        <input type="text" id="last_name" name="last_name"
                                value="<?php echo htmlspecialchars($edit_mode ? ($user_profile['last_name'] ?? '') : ($last_name ?? '')); ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label for="phone">Phone Number</label>
                    <input type="tel" id="phone" name="phone"
                            value="<?php echo htmlspecialchars($edit_mode ? ($user_profile['phone'] ?? '') : ($phone ?? '')); ?>">
                </div>
            </div>

            <?php if ($edit_mode): ?>
            <div class="form-section">
                <h2><i class="fas fa-key"></i> Password Management</h2>

                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="change_password" id="change_password">
                        Change Password
                    </label>
                </div>

                <div id="password-fields" style="display: none;">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="new_password">New Password *</label>
                            <input type="password" id="new_password" name="password" minlength="6">
                            <small>Minimum 6 characters</small>
                        </div>

                        <div class="form-group">
                            <label for="confirm_password">Confirm New Password *</label>
                            <input type="password" id="confirm_password" name="confirm_password">
                        </div>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <div class="form-section">
                <h2><i class="fas fa-cogs"></i> Additional Options</h2>

                <div class="form-group">
                    <label class="checkbox-label">
                        <input type="checkbox" name="send_welcome_email" checked>
                        Send welcome email
                    </label>
                    <small>Send login credentials to the user via email</small>
                </div>
            </div>
            <?php endif; ?>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-<?php echo $edit_mode ? 'save' : 'user-plus'; ?>"></i> <?php echo $edit_mode ? 'Save Changes' : 'Create User'; ?>
                </button>
                <a href="users.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Password confirmation validation
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirm_password');

    if (password && confirmPassword) {
        confirmPassword.addEventListener('input', function() {
            if (this.value && this.value !== password.value) {
                this.setCustomValidity('Passwords do not match');
            } else {
                this.setCustomValidity('');
            }
        });
    }

    // Username validation
    const username = document.getElementById('username');
    username.addEventListener('input', function() {
        const regex = /^[a-zA-Z0-9_]{3,50}$/;
        if (!regex.test(this.value)) {
            this.setCustomValidity('Username must be 3-50 characters and contain only letters, numbers, and underscores');
        } else {
            this.setCustomValidity('');
        }
    });

    <?php if ($edit_mode): ?>
    // Toggle password fields
    const changePassword = document.getElementById('change_password');
    const passwordFields = document.getElementById('password-fields');

    changePassword.addEventListener('change', function() {
        passwordFields.style.display = this.checked ? 'block' : 'none';
        const inputs = passwordFields.querySelectorAll('input');
        inputs.forEach(input => {
            input.required = this.checked;
        });
    });
    <?php endif; ?>
});
</script>

<?php include 'includes/admin_footer.php'; ?>