<?php

/**
 * Online Solution Sync Images.
 *
 * @package northmill-online-shared
 */
declare (strict_types=1);
namespace Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Sync_Settings\Sync;

use Northmill_Online_Shared_Checkout\Northmill_Online_Shared\Modules\Admin\Pages\Page\Admin_Sync_Settings\Models\Properties\Settings_Image_Model;
defined('ABSPATH') || exit;
/**
 * Class Online_Solutions_Sync_Images
 */
readonly class Online_Solution_Sync_Images
{
    /**
     * Get the image model for the attachment.
     * Name in Moreflo Light: get_attachment_as_apps_image()
     *
     * @param int $id WordPress Post ID.
     *
     * @return Settings_Image_Model|false
     *
     * @used Northmill Express Order
     */
    public function get_attachment_as_image_model(int $id): Settings_Image_Model|false
    {
        if (!$id) {
            return \false;
        }
        $attachment = wp_get_attachment_metadata($id);
        if (!$attachment) {
            return \false;
        }
        return new Settings_Image_Model(array('Name' => basename($attachment['file']), 'IsMainFile' => \true, 'URL' => wp_get_attachment_image_url($id), 'WPId' => $id));
    }
    /**
     * Get the main attachment ID from a list of images.
     *
     * @param Settings_Image_Model[] $images Images.
     *
     * @return int|null Main attachment ID, or null if no main image found.
     *
     * @used Northmill Express Order
     */
    public function get_main_attachment(array $images): ?int
    {
        $main_id = $this->get_main_image($images);
        if (is_null($main_id)) {
            return null;
        }
        $posts = get_posts(array('post_type' => 'attachment', 'posts_per_page' => 1, 'ignore_sticky_posts' => \true, 'meta_query' => array(array('key' => 'mf_id', 'value' => $main_id))));
        return empty($posts) ? null : $posts[0]->ID;
    }
    /**
     * Get the main image ID from a list of images.
     *
     * @param Settings_Image_Model[] $images Images.
     *
     * @return string|null Main image ID, or null if no main image found.
     */
    protected function get_main_image(array $images): ?string
    {
        $main_id = null;
        if (!empty($images)) {
            foreach ($images as $image) {
                if ($image->is_main_file()) {
                    return $image->get_id();
                }
                $main_id = $image->get_id();
            }
        }
        return $main_id;
    }
}
