<?php

namespace BitApps\PiPro\src\Integrations\Acpt;

use BitApps\Pi\Helpers\Utility;
use BitApps\Pi\src\Flow\NodeInfoProvider;
use Throwable;

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



final class AcptServices
{
    private NodeInfoProvider $nodeInfoProvider;

    /**
     * Acpt services constructor.
     */
    public function __construct(NodeInfoProvider $nodeInfoProvider)
    {
        $this->nodeInfoProvider = $nodeInfoProvider;
    }

    /**
     * Create custom post type.
     *
     * @return collection
     */
    public function createCustomPostType(): array
    {
        $fieldsMap = $this->nodeInfoProvider->getFieldMapData();
        $fieldsMap['labels'] = $this->nodeInfoProvider->getFieldMapRepeaters('label-field-map.value', false, true, 'acptLabelField', 'value') ?? [];

        $rules = [
            'name'     => ['required', 'sanitize:text'],
            'singular' => ['required', 'sanitize:text'],
            'plural'   => ['required', 'sanitize:text'],
        ];

        $validationErrors = AcptActionHelper::validatePostTypeFields(
            $fieldsMap,
            $rules,
            null,
            true,
            $fieldsMap['name']
        );

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $requiredModules = ['postTypeRepository', 'customPostTypeModel', 'taxonomyRepository', 'uuid'];
        $errors = AcptActionHelper::validateRequiredModules($requiredModules, $fieldsMap);

        if (!empty($errors)) {
            return $errors;
        }

        if (!AcptActionHelper::isValidCustomPostType($fieldsMap['name'])) {
            return [
                'response'    => __('Invalid Post type', 'bit-pi'),
                'payload'     => $fieldsMap,
                'status_code' => 422
            ];
        }

        $fieldsMap['name'] = str_replace(' ', '-', strtolower($fieldsMap['name']));

        $data = AcptActionHelper::preparePostTypeData($fieldsMap);
        $customPostTypeRepoClass = AcptActionHelper::getCustomPostTypeRepoClassName();
        $customPostTypeModelClass = AcptActionHelper::getCustomPostTypeModelClassName();

        try {
            $postModel = $customPostTypeModelClass::hydrateFromArray($data);

            $customPostTypeRepoClass::save($postModel);

            AcptActionHelper::registerRelatedTaxonomies($fieldsMap['name']);

            return [
                'response'    => __('Post type created successfully', 'bit-pi'),
                'payload'     => $fieldsMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed created Post type', 'bit-pi'),
                'payload'     => $fieldsMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Get all custom post types.
     *
     * @return collection
     */
    public function getAllPostType(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['postTypeRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $customPostTypeRepoClass = AcptActionHelper::getCustomPostTypeRepoClassName();

        $data = $customPostTypeRepoClass::get();

        return [
            'response'    => Utility::jsonEncodeDecode($data),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Get custom post type.
     *
     * @return collection
     */
    public function getPostType(): array
    {
        $postType = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['postType' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($postType, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['postTypeRepository'], $postType);

        if (!empty($errors)) {
            return $errors;
        }

        $customPostTypeRepoClass = AcptActionHelper::getCustomPostTypeRepoClassName();

        $data = $customPostTypeRepoClass::get($postType);

        return [
            'response'    => Utility::jsonEncodeDecode($data),
            'payload'     => $postType,
            'status_code' => 200
        ];
    }

    /**
     * Delete post type.
     *
     * @return collection
     */
    public function deletePostType(): array
    {
        $payload = $this->nodeInfoProvider->getFieldMapData();

        $payload['delete_post'] = $this->nodeInfoProvider->getFieldMapConfigs('delete-post.value') ?? false;

        $rules = ['postType' => ['required', 'sanitize:text']];
        $postType = $payload['postType'];

        $validationErrors = AcptActionHelper::validatePostTypeFields(
            $payload,
            $rules,
            null,
            false,
            $postType
        );

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['postTypeRepository'], $payload);

        if (!empty($errors)) {
            return $errors;
        }

        $customPostTypeRepoClass = AcptActionHelper::getCustomPostTypeRepoClassName();

        $status = $customPostTypeRepoClass::delete($postType, $payload['delete_post']);

        if (empty($status) || is_wp_error($status)) {
            $response = __('Failed to delete post type', 'bit-pi');
            $code = 500;
        } else {
            $response = __('Post type deleted successfully', 'bit-pi');
            $code = 200;
        }

        return ['response' => $response, 'payload' => $payload, 'status_code' => $code];
    }

    /**
     * Delete all post by post type.
     *
     * @return collection
     */
    public function deleteAllPostByPostType(): array
    {
        $payload = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['postType' => ['required', 'sanitize:text']];
        $postType = $payload['postType'];

        $validationErrors = AcptActionHelper::validatePostTypeFields(
            $payload,
            $rules,
            $payload,
            false,
            $postType
        );

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['postTypeRepository', 'acptDb'], $payload);

        if (!empty($errors)) {
            return $errors;
        }

        $acptDb = AcptActionHelper::getAcptDBClassName();
        $customPostTypeRepoClass = AcptActionHelper::getCustomPostTypeRepoClassName();

        try {
            global $wpdb;

            $query = "DELETE a,b,c
            FROM `{$wpdb->prefix}posts` a
            LEFT JOIN `{$wpdb->prefix}term_relationships` b
                ON (a.ID = b.object_id)
            LEFT JOIN `{$wpdb->prefix}postmeta` c
                ON (a.ID = c.post_id)
            WHERE a.post_type = %s";

            $acptDb::executeQueryOrThrowException($query, [$postType]);
            $acptDb::invalidateCacheTag($customPostTypeRepoClass);

            return [
                'response'    => __('Posts deleted successfully', 'bit-pi'),
                'payload'     => $payload,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed deleted Posts', 'bit-pi'),
                'payload'     => $payload,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Get all field group.
     *
     * @return collection
     */
    public function getAllFieldGroup(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $fieldGroups = AcptActionHelper::getFieldGroups();

        return [
            'response'    => $fieldGroups,
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Get field group by field.
     *
     * @param string $key
     *
     * @return collection
     */
    public function getFieldGroupByField($key): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = [$key => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $fieldGroups = AcptActionHelper::getFieldGroups($fieldMap);

        return [
            'response'    => $fieldGroups,
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Delete all field group.
     *
     * @return collection
     */
    public function deleteAllFieldGroup()
    {
        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();

        $status = $metaRepoClass::deleteAll([]);

        if (!$status) {
            return [
                'response'    => __('Failed to deleted all field group', 'bit-pi'),
                'payload'     => [],
                'status_code' => 500
            ];
        }

        return [
            'response'    => __('Deleted all field group successfully', 'bit-pi'),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Delete field group.
     *
     * @return collection
     */
    public function deleteFieldGroup(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['id' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();

        try {
            $metaRepoClass::deleteMetaGroup($fieldMap['id']);

            return [
                'response'    => __('Deleted field group successfully', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed deleted Posts', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Get All meta box.
     *
     * @return collection
     */
    public function getAllMetaBox(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['groupName' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $fieldGroups = AcptActionHelper::getFieldGroups($fieldMap);

        $fieldGroup = \count($fieldGroups) > 0 ? reset($fieldGroups) : [];
        $boxes = !empty($fieldGroup->boxes) ? $fieldGroup->boxes : [];

        return [
            'response'    => $boxes,
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Get meta box by name.
     *
     * @return collection
     */
    public function getMetaBoxByName(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['boxName' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();
        $metaBox = $metaRepoClass::getMetaBoxByName($fieldMap['boxName']);

        return [
            'response'    => Utility::jsonEncodeDecode($metaBox),
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Get meta box by id.
     *
     * @return collection
     */
    public function getMetaBoxById(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['id' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();
        $metaBox = $metaRepoClass::getMetaBoxById($fieldMap['id']);

        return [
            'response'    => Utility::jsonEncodeDecode($metaBox),
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Delete meta box.
     *
     * @return collection
     */
    public function deleteMetaBox(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['id' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();
        $metaBox = $metaRepoClass::getMetaBoxById($fieldMap['id']);

        if (empty($metaBox)) {
            return [
                'response'    => __('Meta box not found', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 400
            ];
        }

        try {
            $metaRepoClass::deleteMetaBox($fieldMap['id']);

            return [
                'response'    => __('Deleted meta box successfully', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed to deleted meta box', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Get all meta box field.
     *
     * @return collection
     */
    public function getAllMetaField(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();
        $metaFields = $metaRepoClass::getMetaFields([]);

        return [
            'response'    => Utility::jsonEncodeDecode($metaFields),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Get meta box field by meta box.
     *
     * @return collection
     */
    public function getMetaFieldsByMetaBox(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['boxName' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();
        $metaBox = $metaRepoClass::getMetaBoxByName($fieldMap['boxName']);
        $metaFields = !empty($metaBox->getFields()) ? Utility::jsonEncodeDecode($metaBox->getFields()) : [];

        return [
            'response'    => $metaFields,
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Get meta box.
     *
     * @return collection
     */
    public function getMetaField(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['boxName' => ['required', 'sanitize:text'], 'fieldName' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();
        $metaField = $metaRepoClass::getMetaFieldByName($fieldMap);

        return [
            'response'    => Utility::jsonEncodeDecode($metaField),
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Delete meta box field.
     *
     * @return collection
     */
    public function deleteMetaField(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['id' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();
        $metaFields = $metaRepoClass::getMetaFields([]);

        $field = array_filter(
            $metaFields,
            function ($field) use ($fieldMap) {
                return $field->getId() === $fieldMap['id'];
            }
        );

        if (empty($field)) {
            return [
                'response'    => __('Meta field not found', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 400
            ];
        }

        try {
            $metaRepoClass::deleteMetaField($fieldMap['id']);

            return [
                'response'    => __('Deleted meta box field successfully', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed to deleted meta box field', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Get All Associated Post Types And Taxonomies.
     *
     * @return collection
     */
    public function getAllAssociatedPostTypesAndTaxonomies(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['metaRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $metaRepoClass = AcptActionHelper::getMetaRepoClassName();
        $data = $metaRepoClass::getAllAssociatedPostTypesAndTaxonomies();

        return [
            'response'    => $data,
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Register new taxonomy.
     *
     * @return collection
     */
    public function registerTaxonomy(): array
    {
        $fieldsMap = $this->nodeInfoProvider->getFieldMapData();
        $fieldsMap['labels'] = $this->nodeInfoProvider->getFieldMapRepeaters('label-field-map.value', false, true, 'acptLabelField', 'value') ?? [];

        $rules = [
            'slug'     => ['required', 'sanitize:text'],
            'singular' => ['required', 'sanitize:text'],
            'plural'   => ['required', 'sanitize:text'],
        ];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldsMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $requiredModules = ['TaxonomyModel', 'taxonomyRepository', 'uuid', 'acptDb'];
        $errors = AcptActionHelper::validateRequiredModules($requiredModules, $fieldsMap);

        if (!empty($errors)) {
            return $errors;
        }

        try {
            $taxonomyModel = AcptActionHelper::prepareTaxonomyData($fieldsMap);

            $acptDb = AcptActionHelper::getAcptDBClassName();
            $TaxonomyRepoClass = AcptActionHelper::getTaxonomyRepoClassName();

            $TaxonomyRepoClass::save($taxonomyModel);
            $acptDb::flushCache();

            return [
                'response'    => __('Taxonomy registered successfully', 'bit-pi'),
                'payload'     => $fieldsMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed to register taxonomy', 'bit-pi'),
                'payload'     => $fieldsMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Get the registered taxonomies.
     *
     * @return collection
     */
    public function getAllTaxonomy(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['taxonomyRepository']);
        if (!empty($errors)) {
            return $errors;
        }

        return [
            'response'    => AcptActionHelper::getTaxonomies(),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Get the registered taxonomy.
     *
     * @return collection
     */
    public function getTaxonomy(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['taxonomy' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['taxonomyRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        return [
            'response'    => AcptActionHelper::getTaxonomies($fieldMap),
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Get taxonomies slug.
     *
     * @return collection
     */
    public function getTaxonomiesSlug(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['taxonomyRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $TaxonomyRepoClass = AcptActionHelper::getTaxonomyRepoClassName();

        return [
            'response'    => $TaxonomyRepoClass::getSlugs(),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Associate a post with a taxonomy.
     *
     * @return collection
     */
    public function associatePostWithTaxonomy(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['taxonomyId' => ['required', 'sanitize:text'], 'postId' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['taxonomyRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        try {
            $TaxonomyRepoClass = AcptActionHelper::getTaxonomyRepoClassName();

            $TaxonomyRepoClass::assocToPostType($fieldMap['postId'], $fieldMap['taxonomyId']);

            return [
                'response'    => __('Post with taxonomy successfully associated', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed to associate post with taxonomy', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Delete all post's associations with taxonomies.
     *
     * @return collection
     */
    public function deletePostAssociations(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['postTypeId' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['taxonomyRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        try {
            $TaxonomyRepoClass = AcptActionHelper::getTaxonomyRepoClassName();

            $TaxonomyRepoClass::deleteAssociations($fieldMap['postTypeId']);

            return [
                'response'    => __("Delete all post's associations with taxonomies", 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed to deleted post associations with taxonomies', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Delete taxonomy.
     *
     * @return collection
     */
    public function deleteTaxonomy(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['taxonomy' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['taxonomyRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $TaxonomyRepoClass = AcptActionHelper::getTaxonomyRepoClassName();

        if (!$TaxonomyRepoClass::exists($fieldMap['taxonomy'])) {
            return [
                'response'    => __('Taxonomy not found', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 400
            ];
        }

        try {
            $TaxonomyRepoClass::delete($fieldMap['taxonomy']);

            return [
                'response'    => __('Taxonomy deleted successfully', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed to deleted taxonomy', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Get dynamic blocks.
     *
     * @return collection
     */
    public function getAllDynamicBlock(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['DynamicBlockRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $dynamicBlockRepository = AcptActionHelper::getDynamicBlockRepoClassName();
        $block = $dynamicBlockRepository::get([]);

        return [
            'response'    => Utility::jsonEncodeDecode($block),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Get dynamic block by id.
     *
     * @return collection
     */
    public function getDynamicBlockById(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['id' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['DynamicBlockRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $dynamicBlockRepository = AcptActionHelper::getDynamicBlockRepoClassName();
        $block = $dynamicBlockRepository::getById($fieldMap['id']);

        return [
            'response'    => Utility::jsonEncodeDecode($block),
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Get dynamic block by id.
     *
     * @return collection
     */
    public function getDynamicBlockByName(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['blockName' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['DynamicBlockRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $dynamicBlockRepository = AcptActionHelper::getDynamicBlockRepoClassName();
        $block = $dynamicBlockRepository::getByName($fieldMap['blockName']);

        return [
            'response'    => Utility::jsonEncodeDecode($block),
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Get dynamic blocks Controls name.
     *
     * @return collection
     */
    public function getDynamicBlockControlsName(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['DynamicBlockRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $dynamicBlockRepository = AcptActionHelper::getDynamicBlockRepoClassName();

        return [
            'response'    => $dynamicBlockRepository::getControlNames(),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Get dynamic block by id.
     *
     * @return collection
     */
    public function deleteDynamicBlock(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['id' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['DynamicBlockRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        try {
            $dynamicBlockRepository = AcptActionHelper::getDynamicBlockRepoClassName();
            $dynamicBlockRepository::delete($fieldMap['id']);

            return [
                'response'    => __('Deleted dynamic block Successfully', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed deleted dynamic block', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }

    /**
     * Get forms.
     *
     * @return collection
     */
    public function getAllForms(): array
    {
        $errors = AcptActionHelper::validateRequiredModules(['FormRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        return [
            'response'    => AcptActionHelper::getForms(),
            'payload'     => [],
            'status_code' => 200
        ];
    }

    /**
     * Get form by id.
     *
     * @return collection
     */
    public function getFormById(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['id' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['FormRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $formRepoClassName = AcptActionHelper::getFormRepoClassName();

        $form = $formRepoClassName::getById($fieldMap['id']);

        return [
            'response'    => Utility::jsonEncodeDecode($form),
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Get form by name.
     *
     * @return collection
     */
    public function getFormByName(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['formName' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['FormRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $forms = AcptActionHelper::getForms($fieldMap);

        return [
            'response'    => $forms,
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Get form submissions.
     *
     * @return collection
     */
    public function getFormSubmissions(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['formId' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['FormRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        $formRepoClassName = AcptActionHelper::getFormRepoClassName();

        $submissions = $formRepoClassName::getSubmissions($fieldMap['formId']);

        return [
            'response'    => Utility::jsonEncodeDecode($submissions),
            'payload'     => $fieldMap,
            'status_code' => 200
        ];
    }

    /**
     * Delete form.
     *
     * @return collection
     */
    public function deleteForm(): array
    {
        $fieldMap = $this->nodeInfoProvider->getFieldMapData();

        $rules = ['id' => ['required', 'sanitize:text']];

        $validationErrors = AcptActionHelper::validateFieldMap($fieldMap, $rules);

        if (!empty($validationErrors)) {
            return $validationErrors;
        }

        $errors = AcptActionHelper::validateRequiredModules(['FormRepository']);

        if (!empty($errors)) {
            return $errors;
        }

        try {
            $formRepoClassName = AcptActionHelper::getFormRepoClassName();
            $formRepoClassName::delete($fieldMap['id']);

            return [
                'response'    => __('Deleted form Successfully', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => 200
            ];
        } catch (Throwable $th) {
            return [
                'response'    => $th->getMessage() ?? __('Failed deleted form', 'bit-pi'),
                'payload'     => $fieldMap,
                'status_code' => $th->getCode() ?? 500
            ];
        }
    }
}
