<?php

namespace Silvanus\includes\helpers;

class Image
{
    /**
     * @param  $id  - WordPress Image Size
     * @param  bool  $fetchAll  - Get all known sizes (Default True)
     * @param  array  $sizes  - Define specific sizes requested.
     */
    public static function getImageById($id, array $sizes = [], bool $fetchAll = true): array
    {
        $data = [];
        $availableSizes = get_intermediate_image_sizes();
        $data['full'] = wp_get_attachment_image_src($id, 'full');
        if ($data['full'] !== false) {
            $sizesToFetch = $fetchAll ? $availableSizes : array_intersect($availableSizes, $sizes);
            if (! empty($sizesToFetch)) {
                foreach ($sizesToFetch as $size) {
                    $data[$size] = wp_get_attachment_image_src($id, $size);
                }
            }
            $data['meta'] = wp_get_attachment_metadata($id);
            $data['alt'] = get_post_meta($id, '_wp_attachment_image_alt', true);
        } else {
            // We need to provide the default missing image block.
            $defaultImage = '/images/defaults/no-image.png';
            $themeURI = get_template_directory_uri();
            $size = getimagesize($themeURI.'/'.$defaultImage);
            $data['full'] = [
                $themeURI.'/'.$defaultImage,
                $size[0],
                $size[1],
                false,
            ];

            $data['meta'] = [
                'width' => $data['full'][1],
                'height' => $data['full'][2],
                'file' => 'no-image.png',
                'sizes' => ['full' => $data['full']],
                'image_meta' => [],
                'filesize' => filesize(get_template_directory().'/'.$defaultImage),
            ];
            $data['alt'] = "Default Holding Image - The image requested hasn't been found.";
        }

        return $data;
    }
}
