<?php
/**
 * System Users Management - System Admin only
 * Lists all accounts: system_admin rows (no edit/delete here) and church-role users (create/edit/delete).
 * Church admins manage church users separately via /users (they cannot see system_admin accounts).
 */

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/audit.php';
require_once __DIR__ . '/../../includes/csrf.php';

require_once __DIR__ . '/../../includes/user-roles.php';
requireAuth();
requireSystemAdmin();

$pageTitle = 'System Users';
$currentPage = 'system';

$action = $route_action ?? 'list';

// Parse route to determine sub-action
// URL: /system/users/create -> routeParts = ['system', 'users', 'create']
// URL: /system/users/edit/123 -> routeParts = ['system', 'users', 'edit', '123']
$route = $_GET['route'] ?? '';
$routeParts = $route ? explode('/', trim($route, '/')) : [];
$subAction = isset($routeParts[2]) ? $routeParts[2] : (isset($route_id) ? $route_id : null);
$userId = isset($routeParts[3]) ? (int) $routeParts[3] : null;

// Handle create action
if ($subAction === 'create') {
    require __DIR__ . '/create-user.php';
    return;
}

// Handle edit action
if ($subAction === 'edit' && $userId) {
    $route_id = $userId;
    require __DIR__ . '/edit-user.php';
    return;
}

// Handle delete action
if ($subAction === 'delete' && $userId) {
    $id = (int) $userId;
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!nazareth_csrf_validate()) {
            header('Location: ' . BASE_PATH . '/system/users?toast_error=' . urlencode('Invalid security token. Try again.'));
            exit;
        }
        if (!nazareth_verify_current_user_password($pdo, (string) ($_POST['confirm_password'] ?? ''))) {
            header('Location: ' . BASE_PATH . '/system/users/delete/' . $id . '?toast_error=' . urlencode('Incorrect password. User was not deleted.'));
            exit;
        }
        try {
            $stmt = $pdo->prepare('SELECT role, username FROM users WHERE id = ?');
            $stmt->execute([$id]);
            $user = $stmt->fetch();
            if ($user && $user['role'] !== 'system_admin') {
                $deletedUsername = $user['username'];
                $deletedRole = $user['role'];
                $pdo->prepare('DELETE FROM users WHERE id = ?')->execute([$id]);
                logUserDeleted($_SESSION['user_id'], $deletedUsername, $deletedRole);
                header('Location: ' . BASE_PATH . '/system/users?toast=' . urlencode('User deleted.'));
                exit;
            }
            header('Location: ' . BASE_PATH . '/system/users?toast_error=' . urlencode('Cannot delete system admin users.'));
            exit;
        } catch (PDOException $e) {
            header('Location: ' . BASE_PATH . '/system/users?toast_error=' . urlencode('Error deleting user.'));
            exit;
        }
    }
    // Show confirmation
    $stmt = $pdo->prepare('SELECT username, full_name FROM users WHERE id = ?');
    $stmt->execute([$id]);
    $user = $stmt->fetch();
    if (!$user) {
        header('Location: ' . BASE_PATH . '/system/users');
        exit;
    }
    require_once __DIR__ . '/../../includes/system-header.php';
    ?>
    <div class="header">
        <h1>Delete 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>
    <div class="card">
        <p>Delete user <strong><?= htmlspecialchars($user['username']) ?></strong>? This revokes login immediately.</p>
        <form method="post" class="form-card" style="max-width: 24rem;">
            <?= nazareth_csrf_field() ?>
            <div class="form-group">
                <label for="confirm_password_del">Your password (required)</label>
                <input type="password" id="confirm_password_del" name="confirm_password" required autocomplete="current-password">
            </div>
            <div class="form-actions">
                <button type="submit" class="btn" style="background: #ef4444; color: white;">Delete user</button>
                <a href="<?= BASE_PATH ?>/system/users" class="btn btn-ghost">Cancel</a>
            </div>
        </form>
    </div>
    <?php require_once __DIR__ . '/../../includes/system-footer.php';
    return;
}

// List all users (system_admin sees everyone; church /users excludes system_admin)
$users = [];
try {
    $stmt = $pdo->query("SELECT id, username, full_name, role, active, created_at FROM users ORDER BY role, username");
    $users = $stmt->fetchAll();
} catch (PDOException $e) {
    // ignore
}

// Separate by role
$systemAdmins = array_filter($users, function($u) { return $u['role'] === 'system_admin'; });
$churchUsers = array_filter($users, function($u) { return $u['role'] !== 'system_admin'; });

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

<div class="header">
    <h1>System Users</h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/system" class="link-muted">← Dashboard</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">System Administrators</h2>
    <p class="text-muted" style="margin-bottom: 1rem;">Users with access to <strong>/system</strong> only. They cannot open church modules (members, finance, events, etc.), but they <strong>can</strong> manage login accounts for church roles on this page.</p>
    <?php if (empty($systemAdmins)): ?>
    <p class="text-muted">No system admin users found.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Username</th>
                    <th>Full Name</th>
                    <th>Status</th>
                    <th>Created</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($systemAdmins as $user): ?>
                <tr>
                    <td><?= htmlspecialchars($user['username']) ?></td>
                    <td><?= htmlspecialchars($user['full_name'] ?? '—') ?></td>
                    <td>
                        <?php if ($user['active']): ?>
                        <span style="color: #10b981; font-size: 0.875rem;">Active</span>
                        <?php else: ?>
                        <span style="color: #ef4444; font-size: 0.875rem;">Inactive</span>
                        <?php endif; ?>
                    </td>
                    <td><?= date('Y-m-d', strtotime($user['created_at'])) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Church Users</h2>
    <p class="text-muted" style="margin-bottom: 1rem;">Accounts that use the main church app (admin, clerk, finance, and other church roles). Church admins also manage many of these under <strong>Users</strong> in the main menu—they cannot see or edit <code>system_admin</code> accounts. Use care before deleting: it revokes that person’s login immediately.</p>
    <?php if (empty($churchUsers)): ?>
    <p class="text-muted">No church users found.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Username</th>
                    <th>Full Name</th>
                    <th>Role</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($churchUsers as $user): ?>
                <tr>
                    <td><?= htmlspecialchars($user['username']) ?></td>
                    <td><?= htmlspecialchars($user['full_name'] ?? '—') ?></td>
                    <td>
                        <span style="padding: 0.25rem 0.5rem; background: #f1f5f9; border-radius: 4px; font-size: 0.8125rem;">
                            <?= htmlspecialchars(nazarethUserRoleShortLabel($user['role'])) ?>
                        </span>
                    </td>
                    <td>
                        <?php if ($user['active']): ?>
                        <span style="color: #10b981; font-size: 0.875rem;">Active</span>
                        <?php else: ?>
                        <span style="color: #ef4444; font-size: 0.875rem;">Inactive</span>
                        <?php endif; ?>
                    </td>
                    <td><?= date('Y-m-d', strtotime($user['created_at'])) ?></td>
                    <td>
                        <a href="<?= BASE_PATH ?>/system/users/edit/<?= $user['id'] ?>" class="btn-icon" title="Edit">
                            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                        </a>
                        <a href="<?= BASE_PATH ?>/system/users/delete/<?= $user['id'] ?>" class="btn-icon btn-icon-danger" title="Delete" data-confirm="Delete this user?">
                            <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<div class="card">
    <h2 style="margin-top: 0; margin-bottom: 1rem;">Add User</h2>
    <p class="text-muted" style="margin-bottom: 1rem;">Create a new system administrator or church user.</p>
    <div style="display: flex; gap: 0.75rem; flex-wrap: wrap;">
        <?php foreach (nazarethSystemCreatableRoleSlugs() as $slug): ?>
        <a href="<?= BASE_PATH ?>/system/users/create?role=<?= htmlspecialchars($slug, ENT_QUOTES, 'UTF-8') ?>"
            class="btn<?= $slug === 'system_admin' ? '' : ' btn-secondary' ?>">Create <?= htmlspecialchars(nazarethSystemCreateButtonLabel($slug)) ?></a>
        <?php endforeach; ?>
    </div>
</div>

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