<?php
/**
 * Add / Edit user form - admin only. Church staff roles only (see includes/user-roles.php).
 * New users get default password and must change on first login. Edit may change role among staff + fellowship assignments.
 */

require_once __DIR__ . '/../../includes/fellowships.php';
require_once __DIR__ . '/../../includes/user-roles.php';
require_once __DIR__ . '/../../includes/password-reset.php';

require_once __DIR__ . '/../../includes/user-defaults.php';
require_once __DIR__ . '/../../includes/memorable-password.php';
if (!defined('DEFAULT_USER_PASSWORD')) {
    define('DEFAULT_USER_PASSWORD', NAZARETH_DEFAULT_USER_PASSWORD);
}
$allowedRoles = nazarethChurchStaffRoleLabels();

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

$isEdit = ($action === 'edit' && $id);
$user = null;
$errors = [];
$managedFellowships = [];
$passwordResetResult = null;

if ($isEdit) {
    $stmt = $pdo->prepare('SELECT id, username, full_name, role FROM users WHERE id = ?');
    $stmt->execute([$id]);
    $user = $stmt->fetch();
    if (!$user || !in_array($user['role'], nazarethChurchStaffRoleSlugs(), true)) {
        header('Location: ' . BASE_PATH . '/users?toast_error=' . urlencode('User not found or cannot be edited.'));
        exit;
    }
    if ($user['role'] === 'group_manager') {
        $stmt = $pdo->prepare('SELECT fellowship_name FROM fellowship_managers WHERE user_id = ?');
        $stmt->execute([$id]);
        $managedFellowships = $stmt->fetchAll(PDO::FETCH_COLUMN);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $isEdit && !empty($_POST['reset_password'])) {
    $passwordResetResult = nazareth_admin_reset_user_password($pdo, (int) $id, (int) currentUserId());
    if (!$passwordResetResult['ok']) {
        $errors[] = $passwordResetResult['error'] ?? 'Could not reset password.';
        $passwordResetResult = null;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST['reset_password'])) {
    $username = trim($_POST['username'] ?? '');
    $full_name = trim($_POST['full_name'] ?? '');
    $r = $_POST['role'] ?? '';
    if (!isset($allowedRoles[$r])) {
        $errors[] = 'Invalid role selected.';
    }
    $role = isset($allowedRoles[$r]) ? $r : ($isEdit ? ($user['role'] ?? 'clerk') : 'clerk');

    if (empty($username)) {
        $errors[] = 'Username is required.';
    }

    if (empty($errors)) {
        $stmt = $pdo->prepare('SELECT id FROM users WHERE username = ?' . ($isEdit ? ' AND id != ?' : ''));
        $stmt->execute($isEdit ? [$username, $id] : [$username]);
        if ($stmt->fetch()) {
            $errors[] = 'Username already exists.';
        }
    }

    if (empty($errors)) {
        if ($isEdit) {
            $oldRole = $user['role'];
            $staffSlugs = nazarethChurchStaffRoleSlugs();
            $placeholders = implode(',', array_fill(0, count($staffSlugs), '?'));
            $sql = "UPDATE users SET username = ?, full_name = ?, role = ? WHERE id = ? AND role IN ($placeholders)";
            $params = array_merge([$username, $full_name ?: null, $role, $id], $staffSlugs);
            $pdo->prepare($sql)->execute($params);

            if ($role === 'group_manager') {
                $pdo->prepare('DELETE FROM fellowship_managers WHERE user_id = ?')->execute([$id]);
                $selected = isset($_POST['managed_fellowships']) && is_array($_POST['managed_fellowships']) ? $_POST['managed_fellowships'] : [];
                $insertFm = $pdo->prepare('INSERT INTO fellowship_managers (user_id, fellowship_name) VALUES (?, ?)');
                foreach ($selected as $fn) {
                    if (in_array($fn, $fellowshipNames, true)) {
                        $insertFm->execute([$id, $fn]);
                    }
                }
            } elseif ($oldRole === 'group_manager') {
                $pdo->prepare('DELETE FROM fellowship_managers WHERE user_id = ?')->execute([$id]);
            }
            header('Location: ' . BASE_PATH . '/users?toast=' . urlencode('User updated.'));
        } else {
            $newUserTempPassword = nazareth_generate_memorable_password();
            $hash = password_hash($newUserTempPassword, PASSWORD_DEFAULT);
            $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;
            }
            if ($hasMustChange) {
                $pdo->prepare('INSERT INTO users (username, password, full_name, role, must_change_password) VALUES (?, ?, ?, ?, 1)')
                    ->execute([$username, $hash, $full_name ?: null, $role]);
            } else {
                $pdo->prepare('INSERT INTO users (username, password, full_name, role) VALUES (?, ?, ?, ?)')
                    ->execute([$username, $hash, $full_name ?: null, $role]);
            }
            $newId = (int) $pdo->lastInsertId();
            if ($role === 'group_manager' && $newId) {
                $selected = isset($_POST['managed_fellowships']) && is_array($_POST['managed_fellowships']) ? $_POST['managed_fellowships'] : [];
                $insertFm = $pdo->prepare('INSERT INTO fellowship_managers (user_id, fellowship_name) VALUES (?, ?)');
                foreach ($selected as $fn) {
                    if (in_array($fn, $fellowshipNames, true)) {
                        $insertFm->execute([$newId, $fn]);
                    }
                }
            }
            $_SESSION['nazareth_new_user_temp_password'] = [
                'username' => $username,
                'password' => $newUserTempPassword,
            ];
            header('Location: ' . BASE_PATH . '/users?created=1');
        }
        exit;
    }

    $user = ['username' => $username, 'full_name' => $full_name, 'role' => $role];
}

$roleForForm = $_POST['role'] ?? ($isEdit ? ($user['role'] ?? 'clerk') : 'clerk');
$selectedFellowships = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (($_POST['role'] ?? '') === 'group_manager')) {
    $selectedFellowships = isset($_POST['managed_fellowships']) && is_array($_POST['managed_fellowships'])
        ? $_POST['managed_fellowships'] : [];
} elseif ($isEdit && (($user['role'] ?? '') === 'group_manager')) {
    $selectedFellowships = $managedFellowships;
}

$pageTitle = $isEdit ? 'Edit user' : 'Add user';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1><?= $isEdit ? 'Edit user' : 'Add user' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/users" class="link-muted">← Users</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div data-toast="error" data-toast-msg="<?= htmlspecialchars(implode(' ', $errors)) ?>" style="display:none"></div>
<?php endif; ?>

<?php if ($passwordResetResult && $passwordResetResult['ok']): ?>
    <div class="alert" style="background:#ecfdf5;border:1px solid #a7f3d0;padding:1rem 1.25rem;margin-bottom:1.25rem;border-radius:8px;color:#065f46;">
        <strong>Password reset for <?= htmlspecialchars($passwordResetResult['username'] ?? '') ?></strong><br>
        Temporary password (show only to this person): <strong style="font-family:monospace;font-size:1.1em;"><?= htmlspecialchars($passwordResetResult['temp_password'] ?? '') ?></strong><br>
        <span style="font-size:0.875rem;">Easy to say over the phone (e.g. red + pepper). They must change it when they sign in.</span>
    </div>
<?php endif; ?>

<div class="form-card">
    <form method="post" class="member-form">
        <div class="form-group">
            <label for="username">Username</label>
            <input type="text" id="username" name="username" required
                value="<?= htmlspecialchars($user['username'] ?? $_POST['username'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="full_name">Full name</label>
            <input type="text" id="full_name" name="full_name"
                value="<?= htmlspecialchars($user['full_name'] ?? $_POST['full_name'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="role">Role</label>
            <select id="role" name="role" required>
                <?php foreach ($allowedRoles as $value => $label): ?>
                    <option value="<?= htmlspecialchars($value) ?>" <?= $roleForForm === $value ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
            <?php if ($isEdit): ?>
            <span class="text-muted" style="font-size: 0.875rem; display: block; margin-top: 0.25rem;">You can change role among staff accounts; use System Users if you need a church administrator account.</span>
            <?php endif; ?>
        </div>
        <div class="form-group" id="managed-fellowships-group" style="<?= $roleForForm === 'group_manager' ? '' : 'display:none' ?>">
            <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, $selectedFellowships, true) ? 'checked' : '' ?>>
                    <?= htmlspecialchars($fn) ?>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="form-actions">
            <button type="submit" class="btn"><?= $isEdit ? 'Update' : 'Create' ?> user</button>
            <a href="<?= BASE_PATH ?>/users" class="btn btn-ghost">Cancel</a>
        </div>
    </form>
    <?php if ($isEdit): ?>
    <form method="post" style="margin-top:1.5rem;padding-top:1.5rem;border-top:1px solid #e2e8f0;" onsubmit="return confirm('Generate a new temporary password for this user?');">
        <h2 style="font-size:1rem;margin:0 0 0.5rem;">Reset password</h2>
        <p class="text-muted" style="font-size:0.875rem;margin:0 0 1rem;">For forgot-password requests. Creates a simple temporary password (color + food, e.g. redpepper) — shown once; give it to the user in person.</p>
        <button type="submit" name="reset_password" value="1" class="btn btn-secondary">Reset password &amp; show temporary password</button>
    </form>
    <?php endif; ?>
</div>

<script>
document.getElementById('role') && document.getElementById('role').addEventListener('change', function() {
    var el = document.getElementById('managed-fellowships-group');
    if (el) el.style.display = this.value === 'group_manager' ? '' : 'none';
});
</script>

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