<?php

namespace App\Traits;

trait ObjectProcessorTrait
{
    /**
     * Process objects JSON and extract unique register IDs
     *
     * Extracts register IDs from 'infoReqBtn.register_id' and 'temp' fields
     * within the 'registers' array of the provided JSON string.
     * Returns a JSON-encoded array of unique, non-empty register values.
     *
     * @param  string|null  $objectsJson  JSON string containing registers data
     * @return string JSON-encoded array of unique register IDs
     */
    public function processObjectsAndExtractRegisters( ?string $objectsJson ) :string
    {
        $register_list = [];

        if (empty($objectsJson) || !is_string($objectsJson)) {
            return json_encode([]);
        }

        try {
            $object_json = json_decode($objectsJson , true , 512 , JSON_THROW_ON_ERROR);

            if (!is_array($object_json) || !isset($object_json['registers']) || !is_array($object_json['registers'])) {
                return json_encode([]);
            }

            foreach ( $object_json['registers'] as $object ) {
                if (!is_array($object)) {
                    continue;
                }

                // Ensure infoReqBtn exists and is an array
                if (!isset($object['infoReqBtn']) || !is_array($object['infoReqBtn'])) {
                    $object['infoReqBtn'] = [];
                }

                // Set default values for required keys
                $object['infoReqBtn']['singleIncrease'] = $object['infoReqBtn']['singleIncrease'] ?? false;
                $object['infoReqBtn']['singleReduction'] = $object['infoReqBtn']['singleReduction'] ?? false;
                $object['infoReqBtn']['register_id'] = $object['infoReqBtn']['register_id'] ?? '';
                $object['temp'] = $object['temp'] ?? '';

                // Extract from infoReqBtn (for text inputs)
                    if (!empty($object['infoReqBtn']['register_id'])) {
                        $register_list[] = $object['infoReqBtn']['register_id'];
                    }

                // Extract from temp (for labels)
                    if (!empty($object['temp'])) {
                        $register_list[] = $object['temp'];
                    }

                // Extract from infoReqBtn (for buttons)
                    if (($object['infoReqBtn']['singleIncrease'] || $object['infoReqBtn']['singleReduction']) &&
                        !empty($object['infoReqBtn']['register_id'])) {
                        $register_list[] = $object['infoReqBtn']['register_id'];
                    }
            }

            // Remove duplicate and empty values
            $filteredList = array_values(array_unique(array_filter($register_list)));
            return json_encode($filteredList , JSON_THROW_ON_ERROR);

        } catch (\JsonException $e) {
            logger()->error('Error processing objects JSON: '.$e->getMessage());
            return json_encode([]);
        }
    }
}
