<?php

declare(strict_types=1);

namespace Inpsyde\MultilingualPress\MediaLibrary\BulkCopyAttachments;

use Inpsyde\MultilingualPress\Attachment\Copier;
use Inpsyde\MultilingualPress\Framework\Http\RequestHandler;
use Inpsyde\MultilingualPress\Framework\Http\ServerRequest;
use Inpsyde\MultilingualPress\Framework\Nonce\Nonce;

use function Inpsyde\MultilingualPress\siteExists;

class BulkCopyAttachmentsRequestHandler implements RequestHandler
{
    public const ACTION = 'multilingualpress.MediaLibrary.BulkCopyAttachments';
    protected const PARAM_NAME_FOR_SITE_IDS = 'siteIds';
    protected const PARAM_NAME_FOR_ATTACHMENT_IDS = 'attachmentIds';

    /**
     * @var Nonce
     */
    protected $nonce;

    /**
     * @var Copier
     */
    protected $copier;

    public function __construct(Nonce $nonce, Copier $copier)
    {
        $this->nonce = $nonce;
        $this->copier = $copier;
    }

    /**
     * @inheritdoc
     */
    public function handle(ServerRequest $request)
    {
        if (!wp_doing_ajax() || !$this->nonce->isValid()) {
            return;
        }

        if (!doing_action('wp_ajax_' . self::ACTION)) {
            wp_send_json_error('Invalid action.');
        }

        $siteIds = $request->bodyValue(
            self::PARAM_NAME_FOR_SITE_IDS,
            INPUT_POST,
            FILTER_SANITIZE_NUMBER_INT,
            FILTER_FORCE_ARRAY
        );

        if (empty($siteIds)) {
            wp_send_json_error('Invalid remote site(s)');
        }

        $attachmentIds = $request->bodyValue(
            self::PARAM_NAME_FOR_ATTACHMENT_IDS,
            INPUT_POST,
            FILTER_SANITIZE_NUMBER_INT,
            FILTER_FORCE_ARRAY
        );

        if (empty($attachmentIds)) {
            wp_send_json_error('Invalid attachment(s)');
        }

        foreach ($siteIds as $siteId) {
            $siteId = (int)$siteId;
            if (!siteExists($siteId)) {
                continue;
            }

            $remoteAttachments = $this->copier->copyById(get_current_blog_id(), $siteId, $attachmentIds);
        }

        wp_send_json_success($remoteAttachments ?? []);
    }
}
