<?php

namespace ProudNerds\Helpers;

/**
 * Class: Image
 *
 * Used for retrieving media and setting the required parameters.
 */
class Image {
    /**
     * Get image HTML given an image ID or name.
     *
     * @param int|string $image Image ID or name.
     * @param string|null $size Image size (thumbnail, full, etc.).
     */
    public function __construct(int|string $image, null|string $size = null) {
        if($id = is_int($image) ? $image : attachment_url_to_postid($image)) {
            $alt = get_post_meta($id, '_wp_attachment_image_alt', true) ?: '';
            $title = get_the_title($id) ?: '';
            $caption = wp_get_attachment_caption($id) ? '<figcaption>' . wp_get_attachment_caption($id) . '</figcaption>' : '';

            if($image = $size ? (wp_get_attachment_image_src($id, $size) ?: get_the_post_thumbnail_url($id, $size)) : wp_get_attachment_image_src($id)) {
                $image = is_array($image) ? $image[0] : $image;
                return '<figure><img src="' . $image . '" alt="' . $alt . '" title="' . $title . '">' . $caption . '</figure>' ;
            } else {
                return 'No image found';
            }
        } else {
            // No ID is found based on the URL, try to find by file name
            $file_dir =  '/assets/general-assets/images/' . $image;
            $file_location_dir = get_stylesheet_directory() . $file_dir;
            $file_location_uri = get_stylesheet_directory_uri() . $file_dir;

            return file_exists($file_location_dir) ? '<figure><img src="' . $file_location_uri . '" alt="" ></figure>' : 'No image found';
        }
    }
}