<?php
/**
 * Edit User - System Admin only
 * Can edit church users (all non–system_admin roles) but not system admins.
 * Role may be changed among church admin + staff; group_manager fellowship rows stay in sync.
 */

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

requireAuth();
requireSystemAdmin();

$pageTitle = 'Edit User';
$currentPage = 'system';

$id = (int) $route_id;
$errors = [];
$success = false;

$editableRoles = nazarethSystemEditableChurchRoleLabels();

// Get user
$stmt = $pdo->prepare('SELECT id, username, full_name, role, active FROM users WHERE id = ?');
$stmt->execute([$id]);
$user = $stmt->fetch();

if (!$user) {
    header('Location: ' . BASE_PATH . '/system/users');
    exit;
}

// System admins cannot edit other system admins
if ($user['role'] === 'system_admin') {
    header('Location: ' . BASE_PATH . '/system/users?toast_error=' . urlencode('Cannot edit system admin users.'));
    exit;
}

$fellowshipNames = array_filter(getFellowshipOrder(), static function ($v) {
    return $v !== null;
});
$managedFellowships = [];
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') {
    $fullName = trim($_POST['full_name'] ?? '');
    $active = !empty($_POST['active']);
    $password = trim($_POST['password'] ?? '');
    $passwordConfirm = trim($_POST['password_confirm'] ?? '');
    $postedRole = $_POST['role'] ?? '';

    if (!isset($editableRoles[$postedRole])) {
        $errors[] = 'Invalid role selected.';
    }
    $newRole = isset($editableRoles[$postedRole]) ? $postedRole : $user['role'];

    if (!empty($password)) {
        if (strlen($password) < 6) {
            $errors[] = 'Password must be at least 6 characters.';
        } elseif ($password !== $passwordConfirm) {
            $errors[] = 'Passwords do not match.';
        }
    }

    if (empty($errors)) {
        $oldRole = $user['role'];
        $changes = [];
        if ($user['full_name'] !== $fullName) {
            $changes['full_name'] = ['old' => $user['full_name'], 'new' => $fullName];
        }
        if ($user['active'] != ($active ? 1 : 0)) {
            $changes['active'] = ['old' => $user['active'], 'new' => $active ? 1 : 0];
        }
        if ($oldRole !== $newRole) {
            $changes['role'] = ['old' => $oldRole, 'new' => $newRole];
        }
        if (!empty($password)) {
            $changes['password'] = ['changed' => true];
        }

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

        try {
            $pdo->beginTransaction();

            if (!empty($password)) {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare('UPDATE users SET full_name = ?, active = ?, role = ?, password = ? WHERE id = ?');
                $stmt->execute([$fullName ?: null, $active ? 1 : 0, $newRole, $hash, $id]);
            } else {
                $stmt = $pdo->prepare('UPDATE users SET full_name = ?, active = ?, role = ? WHERE id = ?');
                $stmt->execute([$fullName ?: null, $active ? 1 : 0, $newRole, $id]);
            }

            if ($newRole === 'group_manager') {
                $pdo->prepare('DELETE FROM fellowship_managers WHERE user_id = ?')->execute([$id]);
                $insertFm = $pdo->prepare('INSERT INTO fellowship_managers (user_id, fellowship_name) VALUES (?, ?)');
                foreach ($selectedFellowships 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]);
            }

            $pdo->commit();

            if (!empty($changes)) {
                logUserUpdated($_SESSION['user_id'], $id, $user['username'], $changes);
            }
            $success = true;
            $user['full_name'] = $fullName ?: null;
            $user['active'] = $active ? 1 : 0;
            $user['role'] = $newRole;
            if ($newRole === 'group_manager') {
                $managedFellowships = array_values(array_filter($selectedFellowships, static function ($fn) use ($fellowshipNames) {
                    return in_array($fn, $fellowshipNames, true);
                }));
            } else {
                $managedFellowships = [];
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $errors[] = 'Could not save changes: ' . $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$success && !empty($errors)) {
    $postRole = $_POST['role'] ?? $user['role'];
    if ($postRole === 'group_manager') {
        $managedFellowships = isset($_POST['managed_fellowships']) && is_array($_POST['managed_fellowships'])
            ? $_POST['managed_fellowships']
            : [];
    }
}

$roleForForm = $_SERVER['REQUEST_METHOD'] === 'POST' ? ($_POST['role'] ?? $user['role']) : $user['role'];
if (!isset($editableRoles[$roleForForm])) {
    $roleForForm = $user['role'];
}

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

<div class="header">
    <h1>Edit User</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 updated successfully.</p>
    <p style="margin: 0.5rem 0 0;"><a href="<?= BASE_PATH ?>/system/users">Back to 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;">Edit <?= htmlspecialchars(nazarethUserRoleShortLabel($user['role'])) ?></h2>
    <form method="post">
        <div class="form-group">
            <label>Username</label>
            <input type="text" value="<?= htmlspecialchars($user['username']) ?>" disabled style="background: #f1f5f9; color: #64748b;">
            <span class="text-muted" style="font-size: 0.875rem; display: block; margin-top: 0.25rem;">Username cannot be changed.</span>
        </div>
        <div class="form-group">
            <label for="role">Role</label>
            <select id="role" name="role" required style="width: 100%; max-width: 28rem;">
                <?php foreach ($editableRoles as $slug => $label): ?>
                <option value="<?= htmlspecialchars($slug) ?>" <?= $roleForForm === $slug ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
                <?php endforeach; ?>
            </select>
        </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'] ?? '') ?>"
                placeholder="John Doe">
        </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, $managedFellowships, true) ? 'checked' : '' ?>>
                    <?= htmlspecialchars($fn) ?>
                </label>
                <?php endforeach; ?>
            </div>
        </div>
        <div class="form-group checkbox-row">
            <label>
                <input type="checkbox" name="active" value="1" <?= $user['active'] ? 'checked' : '' ?>>
                Active (user can login)
            </label>
        </div>
        <div class="form-group">
            <label for="password">New Password (leave blank to keep current)</label>
            <input type="password" id="password" name="password"
                placeholder="Minimum 6 characters">
        </div>
        <div class="form-group">
            <label for="password_confirm">Confirm New Password</label>
            <input type="password" id="password_confirm" name="password_confirm"
                placeholder="Re-enter password">
        </div>
        <div class="form-actions">
            <button type="submit" class="btn">Update User</button>
            <a href="<?= BASE_PATH ?>/system/users" class="btn btn-ghost">Cancel</a>
        </div>
    </form>
</div>

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

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