<?php

namespace Silvanus\includes\helpers;

class TimberFunctions{
    /**
     * The <html> element language attributes for the current site/page,
     * e.g. `lang="en-GB"`.
     */
    public static function language_attributes(string $doctype = 'html'): string
    {
        if (!function_exists('get_language_attributes')) {
            return '';
        }

        return (string) get_language_attributes($doctype);
    }

    public static function normalize_theme_image($image): array
    {
        if (empty($image)) {
            return [];
        }

        $id = null;

        if (is_numeric($image)) {
            $id = (int) $image;
        } elseif (is_array($image)) {
            $id = (int) ($image['ID'] ?? $image['id'] ?? 0);
        } elseif (is_object($image)) {
            $id = (int) ($image->ID ?? $image->id ?? 0);
        }

        $available_sizes = wp_get_registered_image_subsizes();
        $image_sizes = [];

        if (! $id) {
            return [];
        }

        $alt = get_post_meta($id, '_wp_attachment_image_alt', true);
        $caption = wp_get_attachment_caption($id);
        $src = wp_get_attachment_image_url($id, 'full');
        $srcset = wp_get_attachment_image_srcset($id, 'full');

        foreach (array_reverse($available_sizes) as $key => $size) {
            $image_sizes[] = [
                'image_width' => $size['width'],
                'media' => "(min-width: {$size['width']}px)",
                'srcset' => wp_get_attachment_image_url($id, $key),
            ];
        }

        $meta = wp_get_attachment_metadata($id);

        return [
            'id' => $id,
            'alt' => is_string($alt) ? $alt : '',
            'caption' => is_string($caption) ? $caption : '',
            'src' => is_string($src) ? $src : '',
            'srcset' => is_string($srcset) ? $srcset : '',
            'sizes' => empty($image_sizes) ? ['media' => 'min-width:650px', $src] : $image_sizes,
            'width' => isset($meta['width']) ? (int) $meta['width'] : null,
            'height' => isset($meta['height']) ? (int) $meta['height'] : null,
            'mime_type' => get_post_mime_type($id),
        ];
    }
}