<?php
set_time_limit(0);
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
$base = 'https://ruka-dopomohy-uzhhorod.netlify.app/assets/img/';
$paths = [
  'logo.png',
  'logo-cropped.png',
  'logo-header.png',
  'logo-header-en.png',
  'meals-01.webp',
  'meals-02.webp',
  'meals-03.webp',
  'meals-04.webp',
  'meals-05.webp',
  'meals-06.webp',
  'meals-07.webp',
  'meals-08.webp',
  'meals-09.webp',
  'children-01.webp',
  'children-02.webp',
  'children-03.webp',
  'children-04.webp',
  'children-05.webp',
  'children-06.webp',
  'children-07.webp',
  'children-08.webp',
  'children-09.webp',
  'children-10.webp',
  'children-11.webp',
  'medical-01.webp',
  'medical-02.webp',
  'medical-03.webp',
  'medical-04.webp',
  'elderly-01.webp',
  'elderly-02.webp',
  'elderly-03.webp',
  'elderly-04.webp',
  'elderly-05.webp',
  'elderly-06.webp',
  'elderly-07.webp',
  'food-01.webp',
  'food-02.webp',
  'food-03.webp',
  'food-04.webp',
  'food-05.webp',
  'food-06.webp',
  'food-07.webp',
  'food-08.webp',
  'mawa-products/soap-01.webp',
  'mawa-products/soap-02.webp',
  'mawa-products/soap-03.webp',
  'mawa-products/soap-04.webp',
  'mawa-products/soap-05.webp',
  'mawa-products/ceramic-01.webp',
  'mawa-products/knit-01.webp'
];
function ruka_find_existing_attachment_by_old_url($old_url) {
  $ids = get_posts([
    'post_type' => 'attachment',
    'post_status' => 'inherit',
    'posts_per_page' => 1,
    'fields' => 'ids',
    'meta_key' => '_ruka_old_url',
    'meta_value' => $old_url,
  ]);
  if (!empty($ids)) {
    return (int) $ids[0];
  }
  return 0;
}
function ruka_import_one_image($old_url, $path) {
  $existing_id = ruka_find_existing_attachment_by_old_url($old_url);
  if ($existing_id) {
    $existing_url = wp_get_attachment_url($existing_id);
    if ($existing_url) {
      echo "ALREADY IMPORTED: $path => $existing_url\n";
      return $existing_url;
    }
  }
  echo "IMPORTING: $path\n";
  $id = media_sideload_image($old_url, 0, null, 'id');
  if (is_wp_error($id)) {
    echo "FAILED: $path | " . $id->get_error_message() . "\n";
    return '';
  }
  $filename = basename($path);
  $title = pathinfo($filename, PATHINFO_FILENAME);
  $title = str_replace(['-', '_'], ' ', $title);
  $title = trim($title);
  wp_update_post([
    'ID' => $id,
    'post_title' => $title,
    'post_excerpt' => '',
    'post_content' => '',
  ]);
  update_post_meta($id, '_ruka_old_url', $old_url);
  update_post_meta($id, '_wp_attachment_image_alt', $title);
  $new_url = wp_get_attachment_url($id);
  echo "IMPORTED: $path => $new_url\n";
  return $new_url;
}
function ruka_replace_string($value, $replacements) {
  if (!is_string($value) || $value === '') {
    return $value;
  }
  return str_replace(array_keys($replacements), array_values($replacements), $value);
}
function ruka_replace_deep($value, $replacements, &$changed) {
  if (is_string($value)) {
    $new = ruka_replace_string($value, $replacements);
    if ($new !== $value) {
      $changed = true;
    }
    return $new;
  }
  if (is_array($value)) {
    foreach ($value as $k => $v) {
      $value[$k] = ruka_replace_deep($v, $replacements, $changed);
    }
    return $value;
  }
  if (is_object($value)) {
    foreach ($value as $k => $v) {
      $value->$k = ruka_replace_deep($v, $replacements, $changed);
    }
    return $value;
  }
  return $value;
}
echo "RUKA IMAGE IMPORT START\n";
$replacements = [];
foreach ($paths as $path) {
  $old_url = $base . $path;
  $new_url = ruka_import_one_image($old_url, $path);
  if ($new_url) {
    $replacements[$old_url] = $new_url;
  }
}
if (!empty($replacements[$base . 'logo-header.png'])) {
  $replacements[$base . 'reports-01.webp'] = $replacements[$base . 'logo-header.png'];
}
if (empty($replacements)) {
  echo "NO IMAGES IMPORTED. STOP.\n";
  return;
}
echo "REPLACING IMAGE URLS IN POSTS AND PAGES\n";
$posts = get_posts([
  'post_type' => 'any',
  'post_status' => 'any',
  'numberposts' => -1,
]);
foreach ($posts as $post) {
  $old_content = $post->post_content;
  $new_content = ruka_replace_string($old_content, $replacements);
  $old_excerpt = $post->post_excerpt;
  $new_excerpt = ruka_replace_string($old_excerpt, $replacements);
  if ($new_content !== $old_content || $new_excerpt !== $old_excerpt) {
    wp_update_post([
      'ID' => $post->ID,
      'post_content' => $new_content,
      'post_excerpt' => $new_excerpt,
    ]);
    echo "UPDATED CONTENT: {$post->post_title}\n";
  }
  $meta = get_post_meta($post->ID);
  foreach ($meta as $meta_key => $values) {
    foreach ($values as $value) {
      $decoded = maybe_unserialize($value);
      $changed = false;
      $new_value = ruka_replace_deep($decoded, $replacements, $changed);
      if ($changed) {
        update_post_meta($post->ID, $meta_key, $new_value);
        echo "UPDATED META: {$post->post_title} | $meta_key\n";
      }
    }
  }
}
echo "REPLACING IMAGE URLS IN OPTIONS\n";
global $wpdb;
$like = '%' . $wpdb->esc_like($base) . '%';
$options = $wpdb->get_results(
  $wpdb->prepare(
    "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_value LIKE %s",
    $like
  )
);
foreach ($options as $option) {
  $decoded = maybe_unserialize($option->option_value);
  $changed = false;
  $new_value = ruka_replace_deep($decoded, $replacements, $changed);
  if ($changed) {
    update_option($option->option_name, $new_value);
    echo "UPDATED OPTION: {$option->option_name}\n";
  }
}
echo "RUKA IMAGE IMPORT DONE\n";
