<?php
/**
 * Functions that customize sizes and options for images
 *
 * This file is included by the top-level functions.php
 * Global variables are defined there.
 *
 * @since 1.0.0
 */
if (!defined("ABSPATH")) {
  exit();
} // Exit if accessed directly

/**
 * Replace the native WordPress image sizes with default sizes used
 * in Aggie UX, remove image sizes that are not used by this theme.
 *
 * @since 1.0.0
 */
function aux_image_sizes(): void {
  // Remove some of the default WordPress image sizes
  remove_image_size('medium_large');
  remove_image_size('1536x1536');
  remove_image_size('2048x2048');

  // Add custom image sizes. These will all crop from the center.
  add_image_size('full-screen-width', 2400, 1350); // 16x9 aspect ratio

  // Update the default image sizes in WordPress settings.
  // Visible in the WP admin at /wp-admin/options-media.php
  update_option('thumbnail_size_w', 300);
  update_option('thumbnail_size_h', 300);
  update_option('thumbnail_crop', false);

  update_option('medium_size_w', 608);
  update_option('medium_size_h', 608);

  update_option('large_size_w', 1408);
  update_option('large_size_h', 1408);

  // Disable medium_large size completely
  update_option('medium_large_size_w', 0);
  update_option('medium_large_size_h', 0);

  // Set default image options.
  // Visible in the WP admin at /wp-admin/options.php
  update_option('image_default_align', 'left');
	update_option('image_default_link_type', 'none');
	update_option('image_default_size', 'large');
}
add_action('init', 'aux_image_sizes');

/**
 * @todo This should be moved to the TAMU WordPress plugin
 *
 * Resize large original uploaded images during upload.
 *
 * If the original image is larger than 2560px wide or high, resize it before saving it.
 *
 * WordPress keeps the original image with all the thumbnails. The original is used
 * if new thumbnail sizes are created or if thumbnails are regenerated but there's no need for
 * print quality source images - 2560px is twice the size of the width of this theem but still
 * much smaller files than an image straight from a modern camera.
 *
 * Without this, WP also adds a "-scaled" version of the original image created by the
 * "Big Image" feature. By default, WP creates a scaled-down version of any uploaded image larger
 * than 2560px and uses that as the full-size image. It keeps both the -scaled image and the
 * original on the file system. Enterprise storage is expensive, there's no need to keep both.
 *
 * @param array $upload_file Array of upload data.
 *     @type string $file Filename of the newly-uploaded file.
 *     @type string $url  URL of the newly-uploaded file.
 *     @type string $type Mime type of the newly-uploaded file.
 *
 * @return array $upload_file
 *
 * @since 1.0.0
 */
function aux_resize_giant_original_image($upload_file) {
  // Only process image files
  if (substr($upload_file['type'], 0, 5) !== 'image') {
    return $upload_file;
  }

  $image = getimagesize($upload_file['file']);

  if (!$image) {
    return $upload_file;
  }

  $maximum = array(
    'width' => 2560,
    'height' => 2560
  );

  $image_width = $image[0];
  $image_height = $image[1];

  // Load WP_Image_Editor, WP's native class for manipulating images
  $image_editor = wp_get_image_editor($upload_file['file']);

  if (!is_wp_error($image_editor)) {
    // Calculate new dimensions while maintaining aspect ratio
    $ratio = min($maximum['width'] / $image_width, $maximum['height'] / $image_height);
    $new_width = round($image_width * $ratio);
    $new_height = round($image_height * $ratio);

    /*
      Set quality to 100. By default, WP will run the image through ImageMagick to compress to 82.
      The compression is wanted for the different sizes produced but not the original.
    */
    $image_editor->set_quality(100);

    // Resize the image
    $result = $image_editor->resize($new_width, $new_height, false);

    if (!is_wp_error($result)) {
      // Get file info
      $info = pathinfo($upload_file['file']);
      $dir = $info['dirname'];
      $ext = $info['extension'];
      $name = $info['filename'];

      // Save the resized image over the original
      $image_editor->save($upload_file['file']);

      // Update file size in the array
      $upload_file['size'] = filesize($upload_file['file']);
    }
  }

  return $upload_file;
}
add_filter('wp_handle_upload', 'aux_resize_giant_original_image', 10, 1);

/**
 * Set the sizes property on the img tag.
 *
 * The sizes property tells the browser the width the image should be rendered
 * in relation to the viewport. The browser uses sizes to select from the
 * available images in the srcset.
 *
 * AUX important widths:
 * 1400px - desktop max content area, xxl breakpoint
 * 1200px - xl breakpoint
 * 1050px - width of content area if there's a sidebar
 * 992px  - lg breakpoint
 * 768px  - md breakpoint
 * 576px  - sm breakpoint
 *
 * @param string  $sizes  Value for the img sizes attribute.
 * @since 1.0.0
 */
function aux_image_sizes_property($sizes): string {
  /*
    If the viewport is smaller than 992px, display the image at 100% of the
    viewport width. Otherwise, display at 1400px;
  */
  $sizes = '(max-width: 992px) 100vw, 1400px';

  return $sizes;
}
add_filter('wp_calculate_image_sizes', 'aux_image_sizes_property');
