<?php

require_once __DIR__ . '/HikvisionClient.php';
require_once dirname(__DIR__, 2) . '/helpers/hikvision_helper.php';

class HikvisionDeviceService
{
    private HikvisionClient $client;

    public function __construct(HikvisionClient $client)
    {
        $this->client = $client;
    }

    public function detectar(): array
    {
        $deviceInfoResponse = $this->client->get('/ISAPI/System/deviceInfo');
        $capabilitiesResponse = $this->client->get('/ISAPI/System/capabilities');

        $deviceInfoParsed = $this->parseXmlOrJson($deviceInfoResponse['body'] ?? '');
        $capabilitiesParsed = $this->parseXmlOrJson($capabilitiesResponse['body'] ?? '');

        $deviceInfo = is_array($deviceInfoParsed) ? $deviceInfoParsed : [];
        $capabilities = is_array($capabilitiesParsed) ? $capabilitiesParsed : [];

        return [
            'ok' => $deviceInfoResponse['ok'],
            'device_info_response' => $deviceInfoResponse,
            'capabilities_response' => $capabilitiesResponse,
            'device_info' => $deviceInfo,
            'capabilities' => $capabilities,
            'resumen' => [
                'modelo' => $this->findValue($deviceInfo, ['model', 'DeviceInfo.model']),
                'serial_number' => $this->findValue($deviceInfo, ['serialNumber', 'DeviceInfo.serialNumber']),
                'firmware_version' => $this->findValue($deviceInfo, ['firmwareVersion', 'DeviceInfo.firmwareVersion']),
                'device_name' => $this->findValue($deviceInfo, ['deviceName', 'DeviceInfo.deviceName']),
            ],
        ];
    }

    private function parseXmlOrJson(string $body)
    {
        $body = trim($body);

        if ($body === '') {
            return [];
        }

        if (function_exists('hikvision_is_json') && hikvision_is_json($body)) {
            return json_decode($body, true);
        }

        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA);

        if ($xml !== false) {
            return json_decode(json_encode($xml), true);
        }

        return [];
    }

    private function findValue(array $data, array $paths)
    {
        foreach ($paths as $path) {
            $segments = explode('.', $path);
            $value = $data;
            $found = true;

            foreach ($segments as $segment) {
                if (is_array($value) && array_key_exists($segment, $value)) {
                    $value = $value[$segment];
                } else {
                    $found = false;
                    break;
                }
            }

            if ($found) {
                return $value;
            }
        }

        return null;
    }
}