<?php

namespace App\Traits;

use CodeIgniter\API\ResponseTrait as BaseResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;

trait ResponseTrait
{
    use BaseResponseTrait {
        respond as baseRespond;
    }

    /**
     * Send a response with automatic conversion of empty strings to null
     * 
     * @param mixed $data
     * @param int $status
     * @param string $message
     * @return ResponseInterface
     */
    public function respond($data = null, int $status = 200, string $message = '')
    {
        // Convert empty strings to null in the data
        if ($data !== null && (is_array($data) || is_object($data))) {
            $data = $this->convertEmptyStringsToNull($data);
        }
        
        return $this->baseRespond($data, $status, $message);
    }

    /**
     * Recursively convert empty strings to null in arrays or objects
     * 
     * @param mixed $data The data to process (array, object, or scalar)
     * @return mixed The processed data with empty strings converted to null
     */
    private function convertEmptyStringsToNull($data)
    {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                if (is_array($value)) {
                    $data[$key] = $this->convertEmptyStringsToNull($value);
                } elseif (is_object($value)) {
                    $data[$key] = $this->convertEmptyStringsToNull($value);
                } elseif ($value === '') {
                    $data[$key] = null;
                }
            }
        } elseif (is_object($data)) {
            foreach ($data as $key => $value) {
                if (is_array($value)) {
                    $data->$key = $this->convertEmptyStringsToNull($value);
                } elseif (is_object($value)) {
                    $data->$key = $this->convertEmptyStringsToNull($value);
                } elseif ($value === '') {
                    $data->$key = null;
                }
            }
        }
        return $data;
    }
}
