<?php
/**
 * Create user — System Admin only
 * Same church staff roles as /users/add, plus system_admin and church admin.
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/audit.php';
require_once __DIR__ . '/../../includes/security.php';
require_once __DIR__ . '/../../includes/user-roles.php';
require_once __DIR__ . '/../../includes/fellowships.php';

requireAuth();
requireSystemAdmin();

$allowedRoles = nazarethSystemCreatableRoleSlugs();
$roleLabels = nazarethSystemCreatableRoleLabels();

$role = $_GET['role'] ?? 'system_admin';
if (!in_array($role, $allowedRoles, true)) {
    $role = 'system_admin';
}

$fellowshipNames = array_filter(getFellowshipOrder(), static function ($v) {
    return $v !== null;
});

$pageTitle = 'Create ' . $roleLabels[$role];
$currentPage = 'system';

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $passwordConfirm = trim($_POST['password_confirm'] ?? '');
    $fullName = trim($_POST['full_name'] ?? '');
    $role = $_POST['role'] ?? 'system_admin';

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

    if (empty($username)) {
        $errors[] = 'Username is required.';
    } elseif (strlen($username) < 3) {
        $errors[] = 'Username must be at least 3 characters.';
    }

    if (empty($password)) {
        $errors[] = 'Password is required.';
    } else {
        $passwordValidation = validatePassword($password);
        if (!$passwordValidation['valid']) {
            $errors = array_merge($errors, $passwordValidation['errors']);
        }
    }

    if ($password !== $passwordConfirm) {
        $errors[] = 'Passwords do not match.';
    }

    if (empty($errors)) {
        $stmt = $pdo->prepare('SELECT id FROM users WHERE username = ?');
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            $errors[] = 'Username already exists.';
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $mustChangePassword = ($role === 'system_admin') ? 0 : 1;

            $hasMustChange = false;
            try {
                $pdo->query('SELECT must_change_password FROM users LIMIT 1');
                $hasMustChange = true;
            } catch (PDOException $e) {
                if (strpos($e->getMessage(), 'Unknown column') === false) {
                    throw $e;
                }
            }

            $selectedFellowships = [];
            if ($role === 'group_manager') {
                $selectedFellowships = isset($_POST['managed_fellowships']) && is_array($_POST['managed_fellowships'])
                    ? $_POST['managed_fellowships']
                    : [];
            }

            try {
                $pdo->beginTransaction();

                if ($hasMustChange) {
                    $stmt = $pdo->prepare('INSERT INTO users (username, password, full_name, role, active, must_change_password) VALUES (?, ?, ?, ?, 1, ?)');
                    $stmt->execute([$username, $hash, $fullName ?: null, $role, $mustChangePassword]);
                } else {
                    $stmt = $pdo->prepare('INSERT INTO users (username, password, full_name, role, active) VALUES (?, ?, ?, ?, 1)');
                    $stmt->execute([$username, $hash, $fullName ?: null, $role]);
                }
                $newUserId = (int) $pdo->lastInsertId();

                if ($role === 'group_manager' && $newUserId) {
                    $insertFm = $pdo->prepare('INSERT INTO fellowship_managers (user_id, fellowship_name) VALUES (?, ?)');
                    foreach ($selectedFellowships as $fn) {
                        if (in_array($fn, $fellowshipNames, true)) {
                            $insertFm->execute([$newUserId, $fn]);
                        }
                    }
                }

                $pdo->commit();
                logUserCreated($_SESSION['user_id'], $newUserId, $username, $role);
                $success = true;
            } catch (PDOException $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $errors[] = 'Error creating user: ' . $e->getMessage();
            }
        }
    }
}

require_once __DIR__ . '/../../includes/system-header.php';

$selectedFromPost = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['managed_fellowships']) && is_array($_POST['managed_fellowships'])) {
    $selectedFromPost = $_POST['managed_fellowships'];
}
?>

<div class="header">
    <h1>Create <?= htmlspecialchars($roleLabels[$role]) ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/system/users" class="link-muted">← System Users</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if ($success): ?>
<div class="card" style="background: #f0fdf4; border: 1px solid #86efac;">
    <p style="color: #166534; margin: 0;"><strong>Success!</strong> User created successfully.</p>
    <p style="margin: 0.5rem 0 0;"><a href="<?= BASE_PATH ?>/system/users">View all users</a></p>
</div>
<?php endif; ?>

<?php if (!empty($errors)): ?>
<div class="card" style="background: #fef2f2; border: 1px solid #fecaca;">
    <ul style="margin: 0; padding-left: 1.5rem; color: #991b1b;">
        <?php foreach ($errors as $error): ?>
        <li><?= htmlspecialchars($error) ?></li>
        <?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">New <?= htmlspecialchars($roleLabels[$role]) ?></h2>
    <form method="post">
        <input type="hidden" name="role" value="<?= htmlspecialchars($role) ?>">
        <div class="form-group">
            <label for="username">Username *</label>
            <input type="text" id="username" name="username" required autofocus
                value="<?= htmlspecialchars($_POST['username'] ?? '') ?>"
                placeholder="<?= $role === 'system_admin' ? 'sysadmin2' : ($role === 'admin' ? 'admin2' : 'username') ?>">
        </div>
        <div class="form-group">
            <label for="full_name">Full Name</label>
            <input type="text" id="full_name" name="full_name"
                value="<?= htmlspecialchars($_POST['full_name'] ?? '') ?>"
                placeholder="John Doe">
        </div>
        <div class="form-group">
            <label for="password">Password *</label>
            <input type="password" id="password" name="password" required
                placeholder="Minimum 6 characters">
            <?php if ($role !== 'system_admin'): ?>
            <span class="text-muted" style="font-size: 0.875rem; display: block; margin-top: 0.25rem;">Church users are prompted to change this password on first login.</span>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="password_confirm">Confirm Password *</label>
            <input type="password" id="password_confirm" name="password_confirm" required
                placeholder="Re-enter password">
        </div>
        <?php if ($role === 'group_manager'): ?>
        <div class="form-group" id="managed-fellowships-group">
            <label>Managed generational groups</label>
            <p class="text-muted" style="font-size: 0.875rem; margin-bottom: 0.5rem;">Select which groups this user can manage.</p>
            <div class="checkbox-group">
                <?php foreach ($fellowshipNames as $fn): ?>
                <label class="checkbox-label">
                    <input type="checkbox" name="managed_fellowships[]" value="<?= htmlspecialchars($fn) ?>"
                        <?= in_array($fn, $selectedFromPost, true) ? 'checked' : '' ?>>
                    <?= htmlspecialchars($fn) ?>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        <div class="form-actions">
            <button type="submit" class="btn">Create <?= htmlspecialchars($roleLabels[$role]) ?></button>
            <a href="<?= BASE_PATH ?>/system/users" class="btn btn-ghost">Cancel</a>
        </div>
    </form>
</div>

<?php require_once __DIR__ . '/../../includes/system-footer.php'; ?>
