<?php
/**
 * Audit tab — fokussierte View auf alle Audit-Trail-Events.
 *
 * Reuses shieldforge_log; filters server-side to the audit-event-types
 * Shieldforge_AuditLog::audit_event_types().
 *
 * @package Brainwerk Security Suite
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

$type_filter = isset( $_GET['sf_audit_type'] ) ? sanitize_key( wp_unslash( $_GET['sf_audit_type'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only filter param on a capability-gated admin view, no state change.
$page_num    = isset( $_GET['sf_audit_page'] ) ? max( 1, (int) $_GET['sf_audit_page'] ) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only pagination param on a capability-gated admin view, no state change.
$per_page    = 50;
$offset      = ( $page_num - 1 ) * $per_page;

$rows    = Shieldforge_AuditLog::recent_audit( $per_page, $offset, $type_filter );
$summary = Shieldforge_AuditLog::audit_summary( 168 ); // 7-day distribution

$enabled        = (bool) Shieldforge_Settings::get( 'audit_enabled', true );
$track_posts    = (bool) Shieldforge_Settings::get( 'audit_track_posts', true );
$track_users    = (bool) Shieldforge_Settings::get( 'audit_track_users', true );
$track_options  = (bool) Shieldforge_Settings::get( 'audit_track_options', true );
$track_updates  = (bool) Shieldforge_Settings::get( 'audit_track_updates', true );

// Map of event_type → human-readable group label, for the filter dropdown.
$type_labels = array(
    Shieldforge_Logger::EVT_LOGOUT               => __( 'Logout', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_POST_UPDATED         => __( 'Post updated', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_POST_TRASHED         => __( 'Post trashed', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_POST_DELETED         => __( 'Post deleted', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_USER_REGISTERED      => __( 'User registered', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_USER_DELETED         => __( 'User deleted', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_USER_PROFILE_UPDATED => __( 'User profile updated', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_ROLE_CHANGED         => __( 'Role changed', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_ADMIN_CREATED        => __( 'Admin created', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_PLUGIN_ACTIVATED     => __( 'Plugin activated', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_PLUGIN_DEACTIV       => __( 'Plugin deactivated', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_PLUGIN_UPDATED       => __( 'Plugin updated', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_THEME_SWITCHED       => __( 'Theme switched', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_THEME_UPDATED        => __( 'Theme updated', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_CORE_UPDATED         => __( 'Core updated', 'brainwerk-security-suite' ),
    Shieldforge_Logger::EVT_OPTION_CHANGED       => __( 'Option changed', 'brainwerk-security-suite' ),
);

/**
 * Render a one-line "what" cell from a log row by inspecting the event-type
 * and decoded context. Keeps the table compact while still readable.
 */
function shieldforge_audit_describe( $row ) {
    $ctx = is_array( $row->ctx ) ? $row->ctx : array();
    switch ( $row->event_type ) {
        case Shieldforge_Logger::EVT_POST_UPDATED:
        case Shieldforge_Logger::EVT_POST_TRASHED:
        case Shieldforge_Logger::EVT_POST_DELETED:
            $bits = array();
            if ( ! empty( $ctx['post_type'] ) ) {
                $bits[] = '[' . esc_html( $ctx['post_type'] ) . ']';
            }
            if ( ! empty( $ctx['post_title'] ) ) {
                $bits[] = '<strong>' . esc_html( $ctx['post_title'] ) . '</strong>';
            }
            if ( ! empty( $ctx['post_id'] ) ) {
                $bits[] = '<span class="muted">#' . (int) $ctx['post_id'] . '</span>';
            }
            return implode( ' ', $bits );

        case Shieldforge_Logger::EVT_USER_PROFILE_UPDATED:
            $changes = isset( $ctx['changes'] ) && is_array( $ctx['changes'] ) ? array_keys( $ctx['changes'] ) : array();
            return esc_html__( 'fields: ', 'brainwerk-security-suite' ) . '<code>' . esc_html( implode( ', ', $changes ) ) . '</code>';

        case Shieldforge_Logger::EVT_OPTION_CHANGED:
            $opt = isset( $ctx['option'] ) ? (string) $ctx['option'] : '';
            $scope = isset( $ctx['scope'] ) ? (string) $ctx['scope'] : '';
            $from = isset( $ctx['from'] ) ? $ctx['from'] : '';
            $to   = isset( $ctx['to'] ) ? $ctx['to'] : '';
            $from_str = is_scalar( $from ) ? (string) $from : wp_json_encode( $from );
            $to_str   = is_scalar( $to ) ? (string) $to : wp_json_encode( $to );
            return '<code>' . esc_html( $opt ) . '</code> <span class="muted">(' . esc_html( $scope ) . ')</span><br>'
                . '<span class="muted" style="font-size:11px">' . esc_html( shieldforge_audit_truncate( $from_str ) ) . ' → ' . esc_html( shieldforge_audit_truncate( $to_str ) ) . '</span>';

        case Shieldforge_Logger::EVT_PLUGIN_UPDATED:
            return '<code>' . esc_html( $ctx['plugin'] ?? '' ) . '</code>';
        case Shieldforge_Logger::EVT_PLUGIN_ACTIVATED:
        case Shieldforge_Logger::EVT_PLUGIN_DEACTIV:
            return '<code>' . esc_html( $ctx['plugin'] ?? '' ) . '</code>';
        case Shieldforge_Logger::EVT_THEME_UPDATED:
        case Shieldforge_Logger::EVT_THEME_SWITCHED:
            return '<code>' . esc_html( $ctx['theme'] ?? '' ) . '</code>';
        case Shieldforge_Logger::EVT_CORE_UPDATED:
            return esc_html__( 'WordPress', 'brainwerk-security-suite' ) . ' → <code>' . esc_html( $ctx['new_version'] ?? '?' ) . '</code>';
        case Shieldforge_Logger::EVT_USER_REGISTERED:
        case Shieldforge_Logger::EVT_USER_DELETED:
        case Shieldforge_Logger::EVT_ROLE_CHANGED:
        case Shieldforge_Logger::EVT_ADMIN_CREATED:
            $bits = array();
            if ( ! empty( $row->username ) ) {
                $bits[] = '<strong>' . esc_html( $row->username ) . '</strong>';
            }
            if ( ! empty( $ctx['role'] ) ) {
                $bits[] = '<span class="muted">role: ' . esc_html( $ctx['role'] ) . '</span>';
            }
            return implode( ' ', $bits );
        case Shieldforge_Logger::EVT_LOGOUT:
            return $row->username ? '<strong>' . esc_html( $row->username ) . '</strong>' : '';
    }
    return '';
}

function shieldforge_audit_truncate( $s ) {
    $s = (string) $s;
    return mb_strlen( $s ) > 60 ? mb_substr( $s, 0, 57 ) . '...' : $s;
}

function shieldforge_audit_actor( $row ) {
    $ctx = is_array( $row->ctx ) ? $row->ctx : array();
    // The "by whom" field varies by event-type. Prefer explicit fields,
    // fall back to user_id on the row.
    $uid = 0;
    foreach ( array( 'changed_by', 'edited_by', 'updated_by', 'deleted_by' ) as $k ) {
        if ( ! empty( $ctx[ $k ] ) ) { $uid = (int) $ctx[ $k ]; break; }
    }
    if ( ! $uid && $row->user_id ) {
        $uid = (int) $row->user_id;
    }
    if ( ! $uid ) {
        return '<span class="muted">' . esc_html__( 'system / cron', 'brainwerk-security-suite' ) . '</span>';
    }
    $u = get_user_by( 'id', $uid );
    if ( ! $u ) {
        return '<code>uid=' . (int) $uid . '</code>';
    }
    return '<a href="' . esc_url( admin_url( 'user-edit.php?user_id=' . $uid ) ) . '">' . esc_html( $u->user_login ) . '</a>';
}
?>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Audit trail', 'brainwerk-security-suite' ); ?></h2>
    <p class="muted">
        <?php esc_html_e( 'Who changed what, when. Covers post edits, user changes, plugin/theme/core updates, and security-sensitive option changes. Useful for incident response and DSGVO Art. 32 compliance.', 'brainwerk-security-suite' ); ?>
    </p>

    <?php if ( ! empty( $summary ) ) : ?>
        <div style="display:flex; flex-wrap:wrap; gap:6px; margin:10px 0;">
            <?php foreach ( $summary as $s ) :
                $label = $type_labels[ $s->event_type ] ?? $s->event_type;
            ?>
                <span class="sf-badge" style="background:#eef2ff; color:#1d3a8a; padding:3px 9px; font-size:11px; border-radius:10px;">
                    <strong><?php echo (int) $s->n; ?></strong> <?php echo esc_html( $label ); ?>
                </span>
            <?php endforeach; ?>
            <span class="muted" style="font-size:11px; align-self:center;"><?php esc_html_e( '(last 7 days)', 'brainwerk-security-suite' ); ?></span>
        </div>
    <?php endif; ?>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Recent audit events', 'brainwerk-security-suite' ); ?></h2>

    <form method="get" style="margin:0 0 12px;">
        <input type="hidden" name="page" value="brainwerk-security-suite">
        <input type="hidden" name="tab" value="audit">
        <label>
            <?php esc_html_e( 'Filter by type:', 'brainwerk-security-suite' ); ?>
            <select name="sf_audit_type" onchange="this.form.submit()">
                <option value=""><?php esc_html_e( 'All audit events', 'brainwerk-security-suite' ); ?></option>
                <?php foreach ( $type_labels as $type => $label ) : ?>
                    <option value="<?php echo esc_attr( $type ); ?>" <?php selected( $type_filter, $type ); ?>>
                        <?php echo esc_html( $label ); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </label>
        <?php if ( $type_filter ) : ?>
            &nbsp; <a href="<?php echo esc_url( admin_url( 'admin.php?page=brainwerk-security-suite&tab=audit' ) ); ?>"><?php esc_html_e( 'clear', 'brainwerk-security-suite' ); ?></a>
        <?php endif; ?>
    </form>

    <?php if ( empty( $rows ) ) : ?>
        <div class="sf-empty-state">
            <div class="sf-empty-icon dashicons dashicons-clipboard"></div>
            <h3><?php esc_html_e( 'No audit events yet.', 'brainwerk-security-suite' ); ?></h3>
            <p><?php esc_html_e( 'The audit trail starts recording from now. Edit a post, change a setting, deactivate a plugin — anything you do shows up here. Useful for "who changed what when" investigations.', 'brainwerk-security-suite' ); ?></p>
            <a href="<?php echo esc_url( admin_url( 'profile.php' ) ); ?>" class="button"><?php esc_html_e( 'Edit my profile (test it)', 'brainwerk-security-suite' ); ?></a>
        </div>
    <?php else : ?>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th style="width:140px;"><?php esc_html_e( 'When', 'brainwerk-security-suite' ); ?></th>
                    <th style="width:120px;"><?php esc_html_e( 'Who', 'brainwerk-security-suite' ); ?></th>
                    <th style="width:160px;"><?php esc_html_e( 'Action', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'What', 'brainwerk-security-suite' ); ?></th>
                    <th style="width:80px;"><?php esc_html_e( 'IP', 'brainwerk-security-suite' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $rows as $r ) :
                    $label = $type_labels[ $r->event_type ] ?? str_replace( '_', ' ', $r->event_type );
                ?>
                    <tr>
                        <td><code style="font-size:11px;"><?php echo esc_html( $r->created_at ); ?></code></td>
                        <td><?php echo wp_kses_post( shieldforge_audit_actor( $r ) ); ?></td>
                        <td><span class="sf-event-type"><?php echo esc_html( $label ); ?></span></td>
                        <td><?php echo wp_kses_post( shieldforge_audit_describe( $r ) ); ?></td>
                        <td><code style="font-size:11px;"><?php echo esc_html( $r->ip ?: '—' ); ?></code></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <p style="margin-top:10px;">
            <?php if ( $page_num > 1 ) : ?>
                <a class="button" href="<?php echo esc_url( add_query_arg( array( 'page' => 'brainwerk-security-suite', 'tab' => 'audit', 'sf_audit_page' => $page_num - 1, 'sf_audit_type' => $type_filter ) ) ); ?>">&larr; <?php esc_html_e( 'Previous', 'brainwerk-security-suite' ); ?></a>
            <?php endif; ?>
            <?php if ( count( $rows ) === $per_page ) : ?>
                <a class="button" href="<?php echo esc_url( add_query_arg( array( 'page' => 'brainwerk-security-suite', 'tab' => 'audit', 'sf_audit_page' => $page_num + 1, 'sf_audit_type' => $type_filter ) ) ); ?>"><?php esc_html_e( 'Next', 'brainwerk-security-suite' ); ?> &rarr;</a>
            <?php endif; ?>
            <span class="muted" style="margin-left:10px;"><?php
                /* translators: %d: page number */
                printf( esc_html__( 'Page %d', 'brainwerk-security-suite' ), (int) $page_num );
            ?></span>
        </p>
    <?php endif; ?>
</div>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Audit settings', 'brainwerk-security-suite' ); ?></h2>
    <form method="post" action="">
        <?php wp_nonce_field( Shieldforge_Admin::NONCE ); ?>
        <input type="hidden" name="shieldforge_action" value="save_settings">
        <input type="hidden" name="shieldforge_tab_keys[]" value="audit_enabled">
        <input type="hidden" name="shieldforge_tab_keys[]" value="audit_track_posts">
        <input type="hidden" name="shieldforge_tab_keys[]" value="audit_track_users">
        <input type="hidden" name="shieldforge_tab_keys[]" value="audit_track_options">
        <input type="hidden" name="shieldforge_tab_keys[]" value="audit_track_updates">

        <table class="form-table" role="presentation">
            <tr>
                <th scope="row"><?php esc_html_e( 'Enable audit log', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[audit_enabled]" value="1" <?php checked( $enabled ); ?>>
                        <?php esc_html_e( 'Master toggle. Off = no audit hooks register at all (zero overhead).', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Track post changes', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[audit_track_posts]" value="1" <?php checked( $track_posts ); ?>>
                        <?php esc_html_e( 'post_updated, wp_trash_post, before_delete_post (skips revisions, auto-drafts, nav-menu-items)', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Track user changes', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[audit_track_users]" value="1" <?php checked( $track_users ); ?>>
                        <?php esc_html_e( 'profile_update, deleted_user (logouts always logged)', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Track option changes', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[audit_track_options]" value="1" <?php checked( $track_options ); ?>>
                        <?php esc_html_e( 'Whitelist of security-sensitive keys: siteurl, home, admin_email, users_can_register, default_role, blogname, registration (network), site_admins (network).', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Track updates', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[audit_track_updates]" value="1" <?php checked( $track_updates ); ?>>
                        <?php esc_html_e( 'Plugin / theme / core updates via the WordPress updater.', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
        </table>

        <p>
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Save', 'brainwerk-security-suite' ); ?></button>
        </p>
    </form>
</div>
