<?php

declare(strict_types=1);

use Inpsyde\MultilingualPress\Attachment\Copier;
use Inpsyde\MultilingualPress\Framework\Service\Container;
use Inpsyde\MultilingualPress\MediaLibrary\ServiceProvider as MediaLibraryModule;
use Inpsyde\MultilingualPress\MediaLibrary\Settings\MediaLibrarySetting;
use Inpsyde\MultilingualPress\MediaLibrary\Settings\RelatedSitesSetting;
use Inpsyde\MultilingualPress\Core\ServiceProvider as CoreModule;

(static function (Container $container) {
    $allSettings = $container->get(MediaLibraryModule::PARAMETER_CONFIG_SETTINGS_ALL_SETTINGS);
    $relatedSitesSetting = $container->get(RelatedSitesSetting::class);
    $attachmentsCopier = $container->get(Copier::class);
    $allRelatedSiteIds = array_keys($container->get(CoreModule::PARAMETER_CONFIG_RELATED_SITES));
    $settingsTitle = $container->get(MediaLibraryModule::PARAMETER_CONFIG_SETTINGS_TITLE);

    /**
     * Adds the MLP setting fields to attachment(modal and edit screen).
     */
    add_filter(
        'attachment_fields_to_edit',
        static function (array $formFields, WP_Post $post) use ($allSettings, $settingsTitle): array {
            global $pagenow;

            $moduleId = MediaLibraryModule::MODULE_ID;
            $headingKey = "multilingualpress-{$moduleId}-settings";

            $formFields[$headingKey] = ['label' => "<h3>{$settingsTitle}</h3>", 'input' => 'html', 'html' => ' '];

            foreach ($allSettings as $setting) {
                assert($setting instanceof MediaLibrarySetting);

                /**
                 * When the attachment modal is open we need to pass additional arguments to render appropriate select.
                 * phpcs:disable Inpsyde.CodeQuality.LineLength.TooLong
                 */
                if ($pagenow !== 'post.php') {
                    $args = [
                        'render_type' => 'select',
                        'include_empty' => true,
                        'include_all' => true,
                        'description' => __('The attachment will be automatically copied to the connected site upon selection. 
                        Existing attachments with the same file name will be overwritten when copied.', 'multilingualpress'),
                    ];
                }
                $args['name'] = "attachments[{$post->ID}][{$setting->key()}]";
                // phpcs:enable

                ob_start();
                $setting->render($args);
                $render = ob_get_clean();

                $formFields[$setting->key()] = [
                        'label' => esc_html($setting->label()),
                        'input' => 'html',
                        'html' => $render,
                    ];
            }

            return $formFields;
        },
        10,
        2
    );

    /**
     * Hook into attachment save and handle MLP settings save.
     */
    add_filter(
        'attachment_fields_to_save',
        static function (array $post, array $attachment) use ($relatedSitesSetting, $attachmentsCopier, $allRelatedSiteIds): array {
            $selectedSiteIds = $attachment[$relatedSitesSetting->key()] ?? [];
            $remoteSiteIds = $selectedSiteIds === 'all' ? $allRelatedSiteIds : (array)$selectedSiteIds;

            foreach ($remoteSiteIds as $siteId) {
                $attachmentsCopier->copyById(get_current_blog_id(), (int)$siteId, [$post['ID']]);
            }

            return $post;
        },
        10,
        2
    );
}
)($container); //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
