<?php
/**
 * User Registration (Admin only)
 */
require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/middleware/role_middleware.php';

// Only admins can register new users
admin_only();

$pageTitle = 'Register New User';
$db = Database::getInstance();
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();

    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $fullName = trim($_POST['full_name'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['password_confirmation'] ?? '';
    $role = $_POST['role'] ?? ROLE_COUNTER;

    $validator = new Validator();
    $data = ['username' => $username, 'email' => $email, 'full_name' => $fullName, 'password' => $password, 'password_confirmation' => $confirmPassword, 'role' => $role];

    if (!$validator->validate($data, [
        'username' => 'required|min:3|max:50|unique:users,username',
        'email' => 'required|email|unique:users,email',
        'full_name' => 'required|min:2|max:100',
        'password' => 'required|min:6|confirmed',
        'role' => 'required|in:admin,counter,checker,controller',
    ])) {
        $error = $validator->getFirstError();
    } else {
        try {
            $db->insert('users', [
                'username' => $username,
                'email' => $email,
                'full_name' => $fullName,
                'password_hash' => hash_password($password),
                'role' => $role,
                'status' => 'active',
            ]);
            log_action(SessionManager::getUserId(), 'create', 'users', $db->fetchColumn("SELECT LAST_INSERT_ID()"), ['username' => $username, 'role' => $role]);
            set_success("User '$username' created successfully.");
            redirect(APP_URL . '/admin/users.php');
        } catch (Exception $e) {
            $error = 'Failed to create user: ' . $e->getMessage();
        }
    }
}

include APP_ROOT . '/templates/header.php';
?>

<div style="margin-bottom: 16px;">
    <a href="<?= APP_URL ?>/admin/users.php" class="btn btn-outline">Back to Users</a>
</div>

<div class="card">
    <div class="card-body">
        <?php if ($error): ?>
        <div class="alert alert-error"><?= e($error) ?></div>
        <?php endif; ?>

        <form method="POST" action="">
            <?= Csrf::field() ?>
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Full Name *</label>
                    <input type="text" name="full_name" class="form-control" value="<?= e($fullName ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Username *</label>
                    <input type="text" name="username" class="form-control" value="<?= e($username ?? '') ?>" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Email *</label>
                    <input type="email" name="email" class="form-control" value="<?= e($email ?? '') ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Role *</label>
                    <select name="role" class="form-control" required>
                        <option value="counter" <?= ($role ?? '') === 'counter' ? 'selected' : '' ?>>Counter</option>
                        <option value="checker" <?= ($role ?? '') === 'checker' ? 'selected' : '' ?>>Checker</option>
                        <option value="controller" <?= ($role ?? '') === 'controller' ? 'selected' : '' ?>>Controller</option>
                        <option value="admin" <?= ($role ?? '') === 'admin' ? 'selected' : '' ?>>Admin</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Password *</label>
                    <input type="password" name="password" class="form-control" required minlength="6">
                    <span class="form-hint">Minimum 6 characters</span>
                </div>
                <div class="form-group">
                    <label class="form-label">Confirm Password *</label>
                    <input type="password" name="password_confirmation" class="form-control" required>
                </div>
            </div>
            <div class="btn-group mt-2">
                <button type="submit" class="btn btn-primary">Create User</button>
                <a href="<?= APP_URL ?>/admin/users.php" class="btn btn-outline">Cancel</a>
            </div>
        </form>
    </div>
</div>

<?php include APP_ROOT . '/templates/footer.php'; ?>
