<?php

namespace BitApps\PiPro\src\Integrations\AdvancedCustomFields;

use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\src\Flow\NodeInfoProvider;
use BitApps\Pi\src\Interfaces\ActionInterface;

if (!\defined('ABSPATH')) {
    exit;
}

class AdvancedCustomFieldsAction implements ActionInterface
{
    private $nodeInfoProvider;

    public function __construct(NodeInfoProvider $nodeInfoProvider)
    {
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    public function execute(): array
    {
        $executedNodeAction = $this->executeAdvancedCustomFieldsAction();

        return Utility::formatResponseData(
            $executedNodeAction['status_code'] ?? 200,
            $executedNodeAction['payload'] ?? [],
            $executedNodeAction['response'] ?? []
        );
    }

    private function executeAdvancedCustomFieldsAction()
    {
        if (!class_exists('ACF')) {
            return [
                'status_code' => 400,
                'payload'     => [],
                'response'    => __('Advanced Custom Fields plugin is not active.', 'bit-pi'),
            ];
        }

        $acfService = new AdvancedCustomFieldsService($this->nodeInfoProvider);

        $machineSlug = $this->nodeInfoProvider->getMachineSlug();

        if (!method_exists($acfService, $machineSlug)) {
            return [
                'status_code' => 400,
                'payload'     => [],
                'response'    => __('Advanced Custom Fields action not found.', 'bit-pi'),
            ];
        }

        return $acfService->{$machineSlug}();
    }
}
