<?php

namespace BitApps\PiPro\src\Integrations\AdvancedCustomFields;

use BitApps\Pi\Deps\BitApps\WPKit\Helpers\JSON;
use BitApps\Pi\Services\FlowService;
use BitApps\PiPro\src\Integrations\IntegrationHelper;

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

final class AdvancedCustomFieldsTrigger
{
    public static function postAcfFieldUpdated($metaId, $postId, $metaKey, $metaValue)
    {
        if ($metaKey === '_edit_lock' || empty($postId) || !\is_int($postId) || empty($_POST['acf'])) {
            return;
        }

        $data = [
            'post_id'    => $postId,
            'meta_id'    => $metaId,
            'meta_key'   => $metaKey,
            'meta_value' => $metaValue,
            'post_data'  => get_post($postId),
            'post_type'  => get_post_type($postId),
        ];

        if (\function_exists('get_fields')) {
            $fields = get_fields($postId);

            if (\is_array($fields) && \array_key_exists($metaKey, $fields)) {
                $data['post_fields'] = $fields;
            }
        }

        if (\function_exists('get_field')) {
            $data[$metaKey] = get_field($metaKey, $postId);
        }

        self::execute(__FUNCTION__, $data);
    }

    public static function userAcfFieldUpdated($metaId, $userId, $metaKey, $metaValue)
    {
        if (
            empty($metaId)
            || empty($userId)
            || empty($metaKey)
            || empty($metaValue)
            || $metaKey === 'last_update'
        ) {
            return;
        }

        $data = [
            'user_id'    => $userId,
            'meta_id'    => $metaId,
            'meta_key'   => $metaKey,
            'meta_value' => $metaValue,
        ];

        self::execute(__FUNCTION__, $data);
    }

    public static function optionsAcfFieldUpdated($postId)
    {
        if ($postId !== 'options' || !\function_exists('get_fields')) {
            return;
        }

        $fieldKey = 'all';
        $fields = get_fields($postId);

        $acfValue = empty($fields[$fieldKey]) ? $fields : $fields[$fieldKey];

        if (!\is_array($acfValue)) {
            $data = ['field_key' => $fieldKey, $fieldKey => $acfValue];

            return self::execute(__FUNCTION__, $data);
        }

        $firstIndex = 0;

        if (isset($acfValue[$firstIndex]) && \is_array($acfValue[$firstIndex])) {
            $data = [
                'field_key' => $fieldKey,
                $fieldKey   => JSON::maybeEncode($acfValue)
            ];
        } else {
            $data = array_map(
                function ($value) {
                    return \is_array($value) ? JSON::maybeEncode($value) : $value;
                },
                $acfValue
            );

            $data['field_key'] = key($acfValue);
        }

        return self::execute(__FUNCTION__, $data);
    }

    /**
     * Execute the trigger.
     *
     * @param string $machineSlug
     * @param array  $data
     */
    private static function execute($machineSlug, $data)
    {
        $flows = FlowService::exists('AdvancedCustomFields', $machineSlug);

        if (!$flows) {
            return;
        }

        IntegrationHelper::handleFlowForForm($flows, $data);
    }
}
