<?php

// Eventin (wp-event-solution): post types 'etn' and 'etn-*', meta and options prefixed etn_ or eventin_.

add_action( 'wpmc_scan_once', 'wpmc_scan_once_eventin', 10, 0 );
add_action( 'wpmc_scan_postmeta', 'wpmc_scan_postmeta_eventin', 10, 1 );

// Only these keys are read as media IDs: Eventin data is full of other numeric IDs
// (events, speakers, tickets) that must never be mistaken for attachments.
function wpmc_eventin_media_keys() {
  return [
    'image', 'image_id', 'image_url', 'banner', 'banner_id', 'banner_url', 'banner_image',
    'logo', 'logo_id', 'logo_url', 'event_logo', 'event_banner',
    'thumbnail', 'thumbnail_id', 'thumbnail_url', 'avatar', 'avatar_id', 'avatar_url',
    'speaker_avatar', 'speaker_image', 'organizer_image', 'organizer_logo',
    'profile_image', 'profile_photo', 'photo', 'photo_id',
    'featured_image', 'featured_image_id', 'featured_image_url',
    'cover', 'cover_image', 'cover_image_id', 'background_image',
    'media_id', 'media_url', 'attachment_id',
  ];
}

function wpmc_eventin_collect( $key, $raw, &$ids, &$urls ) {
  global $wpmc;
  // Any uploads URL in Eventin data is a reference, whatever key holds it.
  $urls = array_merge( $urls, $wpmc->get_urls_from_string( $raw ) );
  $data = maybe_unserialize( $raw );
  if ( is_string( $data ) ) {
    $decoded = json_decode( $data, true );
    if ( json_last_error() === JSON_ERROR_NONE ) {
      $data = $decoded;
    }
  }
  // Keyed by its unprefixed name so a scalar like etn_event_logo = 12 is matched too.
  $key = preg_replace( '/^_?(?:etn|eventin)[_-]/', '', $key );
  $wpmc->get_from_meta( [ $key => $data ], wpmc_eventin_media_keys(), $ids, $urls );
}

function wpmc_scan_once_eventin() {
  global $wpdb, $wpmc;
  $ids = [];
  $urls = [];
  $options = $wpdb->get_results( "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE 'etn\\_%' OR option_name LIKE 'eventin\\_%'" );
  foreach ( $options as $option ) {
    wpmc_eventin_collect( $option->option_name, $option->option_value, $ids, $urls );
  }
  $wpmc->add_reference_id( $ids, 'EVENTIN OPTIONS' );
  $wpmc->add_reference_url( $urls, 'EVENTIN OPTIONS' );
}

function wpmc_scan_postmeta_eventin( $post_id ) {
  global $wpmc;
  $type = get_post_type( $post_id );
  $is_eventin = $type === 'etn' || strpos( (string) $type, 'etn-' ) === 0;
  $ids = [];
  $urls = [];
  foreach ( get_post_meta( $post_id ) as $key => $values ) {
    // On Eventin's own posts every field counts; elsewhere only Eventin's meta.
    if ( !$is_eventin && !preg_match( '/^_?(?:etn|eventin)[_-]/', $key ) ) {
      continue;
    }
    foreach ( $values as $raw ) {
      wpmc_eventin_collect( $key, $raw, $ids, $urls );
    }
  }
  $wpmc->add_reference_id( $ids, 'EVENTIN', $post_id );
  $wpmc->add_reference_url( $urls, 'EVENTIN', $post_id );
}
