<?php
require_once __DIR__ . '/../../app/includes/auth.php';
require_auth(); require_admin(); verify_csrf();

$name = trim((string)post('name'));
$email = strtolower(trim((string)post('email')));
$role = (string)post('role');
$status = (string)post('status');
$password = (string)post('password');
$confirm = (string)post('confirm_password');

if ($name === '' || !filter_var($email, FILTER_VALIDATE_EMAIL) || !allowed_role($role) || !allowed_user_status($status)) {
    flash('error', 'Please provide valid user details.');
    redirect('/users/create.php');
}
if ($password !== $confirm) {
    flash('error', 'Temporary password and confirmation must match.');
    redirect('/users/create.php');
}
if ($errors = validate_strong_password($password)) {
    flash('error', implode(' ', $errors));
    redirect('/users/create.php');
}
$stmt = db()->prepare('SELECT id FROM users WHERE email = ? LIMIT 1');
$stmt->execute([$email]);
if ($stmt->fetch()) {
    flash('error', 'Email address already exists.');
    redirect('/users/create.php');
}
$stmt = db()->prepare('INSERT INTO users (name, email, password_hash, role, status, must_change_password, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 1, ?, ?)');
$stmt->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT), $role, $status, now(), now()]);
log_activity('user.created', 'Created user ' . $email);
flash('success', 'User created successfully.');
redirect('/users/index.php');
