<?php

namespace Twnt4All\Mixin;

use Twnt4All\Support\Journal;

trait OrderAwareTrait
{
    private $process_id;

    protected function log_event( $event )
    {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- captures the caller frame for structured logging; not a debug print.
        $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
        $caller    = array_shift( $backtrace );

        Journal::event( $this->get_formatted_log( $event ), $caller );
    }

    protected function log_error( $error )
    {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace -- captures the caller frame for structured logging; not a debug print.
        $backtrace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
        $caller    = array_shift( $backtrace );

        Journal::event( $this->get_formatted_log( $error ), $caller );
    }

    /**
     * @param $content
     * @return string
     */
    private function get_formatted_log( $content )
    {
        if ( !is_string( $content ) ) {
            $content = json_encode( $content );
        }

        return sprintf( '[order_id=%1$s][pid=%2$s] %3$s', $this->order->get_id(), $this->get_process_id(), $content );
    }

    private function get_process_id()
    {
        if ( $this->process_id ) {
            return $this->process_id;
        }

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- server-generated float timestamp, never user input.
        $this->process_id = isset( $_SERVER[ 'REQUEST_TIME_FLOAT' ] ) ? (float) $_SERVER[ 'REQUEST_TIME_FLOAT' ] : uniqid();
    }
}
