<?php
declare(strict_types=1);

namespace WP_AUX\Services\AuxCF;

class DeprecatedFieldsService
{
  protected static function videoEmbeds(): void
  {
    $deprecatedVideoFields = ['video'];
    foreach ($deprecatedVideoFields as $deprecatedVideoField) {
      add_filter('acf/load_value/name=' . $deprecatedVideoField, function ($value, $postId, $field) {
        $deprecatedLinkKey = false;
        $deprecatedFileKey = false;
        $finalFieldKey = false;

        switch ($field['parent']) {
          case 'aux_video_embed':
            $deprecatedLinkKey = 'video_embed_video_link';
            $finalFieldKey = 'video';
            break;
          case 'aux_captioned_media':
            $deprecatedLinkKey = 'captioned_media_video_link';
            $finalFieldKey = 'video';
            break;
        }

        if (empty($finalFieldKey) || !empty($value['field_' . $finalFieldKey . '_source'])) {
          return $value;
        }

        if ($deprecatedLinkKey && $deprecatedLinkValue = get_field($deprecatedLinkKey, $postId)) {
          $value['field_' . $finalFieldKey . '_source'] = 'external';
          $value['field_' . $finalFieldKey . '_title'] = $deprecatedLinkValue['title'];
          $value['field_' . $finalFieldKey . '_url'] = $deprecatedLinkValue['url'];
        } elseif ($deprecatedFileKey && $deprecatedFileValue = get_field($deprecatedFileKey, $postId)) {
          $value['field_' . $finalFieldKey . '_source'] = 'internal';
          $value['field_' . $finalFieldKey . '_file'] = $deprecatedFileValue;
        }

        return $value;
      }, 10, 3);
    }
  }

  protected static function imagesWithSizes(): void
  {
    $deprecatedVideoFields = ['image'];
    foreach ($deprecatedVideoFields as $deprecatedVideoField) {
      add_filter('acf/load_value/name=' . $deprecatedVideoField, function ($value, $postId, $field) {
        $deprecatedLinkKey = false;
        $finalFieldKey = false;

        switch ($field['parent']) {
          case 'aux_captioned_media':
            $deprecatedLinkKey = 'captioned_media_image';
            $finalFieldKey = 'image';
            break;
        }

        if (empty($finalFieldKey) || !empty($value['field_' . $finalFieldKey . '_file'])) {
          return $value;
        }

        if ($deprecatedLinkKey && $deprecatedLinkValue = get_field($deprecatedLinkKey, $postId)) {
          $value['field_' . $finalFieldKey . '_file'] = $deprecatedLinkValue['ID'];
          $value['field_' . $finalFieldKey . '_size'] = 'large';
        }

        return $value;
      }, 10, 3);
    }
  }

  public static function prepareHooks(): void
  {
    self::videoEmbeds();
    self::imagesWithSizes();
  }
}
