<?php

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

class YATOON_Activity_Log {
    const OPTION_KEY = 'yatoon_activity_log_v1';
    const LIMIT = 200;

    public static function record( $event, $message, array $context = array() ) {
        $rows = get_option( self::OPTION_KEY, array() );
        if ( ! is_array( $rows ) ) {
            $rows = array();
        }

        $user = wp_get_current_user();
        $actor = ! empty( $context['actor'] )
            ? sanitize_text_field( $context['actor'] )
            : ( $user && $user->exists() ? $user->display_name : 'System' );
        unset( $context['actor'] );

        array_unshift( $rows, array(
            'time'    => current_time( 'mysql' ),
            'event'   => sanitize_key( $event ),
            'message' => sanitize_text_field( $message ),
            'actor'   => sanitize_text_field( $actor ),
            'context' => array_map( 'sanitize_text_field', $context ),
        ) );

        update_option( self::OPTION_KEY, array_slice( $rows, 0, self::LIMIT ), false );
        self::send_webhook( $event, $message, $actor, $context );
    }

    public static function recent( $limit = 50 ) {
        $rows = get_option( self::OPTION_KEY, array() );
        return is_array( $rows ) ? array_slice( $rows, 0, max( 1, absint( $limit ) ) ) : array();
    }

    private static function send_webhook( $event, $message, $actor, array $context ) {
        $url = esc_url_raw( get_option( 'yatoon_webhook_url', '' ) );
        $events = array_filter( array_map( 'sanitize_key', explode( ',', (string) get_option( 'yatoon_webhook_events', '' ) ) ) );
        if ( ! $url || ! in_array( sanitize_key( $event ), $events, true ) ) {
            return;
        }

        $payload = wp_json_encode( array(
            'event'      => sanitize_key( $event ),
            'message'    => sanitize_text_field( $message ),
            'actor'      => sanitize_text_field( $actor ),
            'context'    => $context,
            'occurred_at'=> current_time( 'c' ),
            'site'       => home_url( '/' ),
        ) );
        $headers = array( 'Content-Type' => 'application/json' );
        $secret = (string) get_option( 'yatoon_webhook_secret', '' );
        if ( $secret !== '' ) {
            $headers['X-Yatoon-Signature'] = hash_hmac( 'sha256', $payload, $secret );
        }

        wp_remote_post( $url, array(
            'timeout'   => 5,
            'blocking'  => false,
            'headers'   => $headers,
            'body'      => $payload,
            'sslverify' => true,
        ) );
    }
}
