prefix . 'pxsync_logs'; // ✅ NEW: Log rotation — keep only latest 500 rows // Prevents DB bloat on busy stores (1000 visitors/day = 30,000+ rows/month without this) $count = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table_name ) ); if ( $count > 500 ) { $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE id NOT IN ( SELECT id FROM ( SELECT id FROM %i ORDER BY id DESC LIMIT 500 ) AS keep_rows )', $table_name, $table_name ) ); } // 1. Normalize details to JSON if ( is_array( $details ) ) { $details = wp_json_encode( $details ); } // 2. Identify Error State (Treat anything not 200/Matched/Logged as an Error) $status_str = (string)$status; $is_error = ( ! in_array( $status_str, ['200', 'Matched', 'Logged'] ) && ! empty( $status_str ) ); // 3. Logic Branching $existing = false; // We only search for an existing record to MERGE if the current hit is a SUCCESS.(Deduplication Handshake) // Errors are always treated as unique separate entries. if ( ! $is_error && ! empty( $event_id ) ) { $existing = $wpdb->get_row( $wpdb->prepare( 'SELECT id, source, status, details FROM %i WHERE event_id = %s AND status NOT LIKE %s LIMIT 1', $table_name, $event_id, $wpdb->esc_like( 'Error' ) . '%' ) ); } if ( $existing ) { /** * MERGE CASE: Handshake between Browser and Server * We keep the original platform (e.g. Facebook) but upgrade the source. */ $new_source = ( strpos( $existing->source, $source ) === false ) ? 'Browser & Server' : $existing->source; $base_status = ($new_source === 'Browser & Server') ? 'Matched' : '200'; $wpdb->update( $table_name, [ 'source' => $new_source, 'status' => $base_status, 'created_at' => current_time( 'mysql' ) ], [ 'id' => $existing->id ] ); } else { // ISOLATION CASE: (Error Signal OR Success with no existing success record) // To prevent the "Second one not recorded" bug caused by DB Unique Constraints: // If it's an error, we append a unique suffix to the event_id so the DB allows the INSERT. $storage_event_id = $is_error ? $event_id . '_err_' . uniqid() : $event_id; $wpdb->insert( $table_name, [ 'event_id' => $storage_event_id, 'event_name' => $name, 'source' => $source, 'source_platform' => $platform, // e.g., "Facebook" 'status' => $is_error ? 'Error: ' . $status_str : $status_str, 'details' => $details ]); } } } // phpcs:enable