<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '1');

$ip   = '192.168.100.254';   // <- IP actual del equipo
$user = 'admin';
$pass = 'TU_PASSWORD_REAL';

// Probamos primero por HTTP 80, que ya te respondió antes.
$baseUrls = [
    "http://{$ip}",
    "https://{$ip}",
];

// Endpoints probables para eventos en Hikvision Access Control
$eventTests = [
    [
        'name' => 'AcsEvent search json',
        'path' => '/ISAPI/AccessControl/AcsEvent?format=json',
        'method' => 'POST',
        'body' => [
            'AcsEventCond' => [
                'searchID' => '1',
                'searchResultPosition' => 0,
                'maxResults' => 20,
                'major' => 0,
                'minor' => 0,
                'startTime' => date('Y-m-d\T00:00:00P'),
                'endTime'   => date('Y-m-d\TH:i:sP'),
            ],
        ],
    ],
    [
        'name' => 'AcsEvent search xml-less json alt',
        'path' => '/ISAPI/AccessControl/AcsEvent',
        'method' => 'POST',
        'body' => [
            'AcsEventCond' => [
                'searchID' => '2',
                'searchResultPosition' => 0,
                'maxResults' => 20,
                'major' => 0,
                'minor' => 0,
                'startTime' => date('Y-m-d\T00:00:00P'),
                'endTime'   => date('Y-m-d\TH:i:sP'),
            ],
        ],
    ],
];

function hikRequest(
    string $url,
    string $user,
    string $pass,
    string $method = 'GET',
    ?array $jsonBody = null
): array {
    $ch = curl_init($url);

    $headers = ['Accept: application/json, application/xml, text/plain'];
    if ($jsonBody !== null) {
        $headers[] = 'Content-Type: application/json';
    }

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPAUTH       => CURLAUTH_DIGEST | CURLAUTH_BASIC,
        CURLOPT_USERPWD        => "{$user}:{$pass}",
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HEADER         => true,
    ]);

    if ($jsonBody !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($jsonBody, JSON_UNESCAPED_UNICODE));
    }

    $response = curl_exec($ch);
    $errno    = curl_errno($ch);
    $error    = curl_error($ch);
    $info     = curl_getinfo($ch);

    curl_close($ch);

    return [
        'errno' => $errno,
        'error' => $error,
        'info'  => $info,
        'raw'   => $response,
    ];
}

function splitHeadersBody(?string $raw): array {
    if (!is_string($raw)) {
        return ['', ''];
    }

    $parts = preg_split("/\r\n\r\n/", $raw, 2);
    if (!$parts || count($parts) < 2) {
        return [$raw, ''];
    }

    return [$parts[0], $parts[1]];
}

header('Content-Type: text/plain; charset=utf-8');

echo "=== TEST HIKVISION EVENTOS ===\n";
echo "IP: {$ip}\n";
echo "Hora servidor: " . date('Y-m-d H:i:s') . "\n\n";

foreach ($baseUrls as $baseUrl) {
    echo "######## BASE URL: {$baseUrl} ########\n\n";

    // Primero probamos deviceInfo para confirmar conectividad
    $deviceInfo = hikRequest($baseUrl . '/ISAPI/System/deviceInfo', $user, $pass, 'GET');

    echo "[deviceInfo]\n";
    echo "HTTP CODE: " . ($deviceInfo['info']['http_code'] ?? 'N/A') . "\n";
    echo "cURL errno: {$deviceInfo['errno']}\n";
    echo "cURL error: {$deviceInfo['error']}\n\n";

    foreach ($eventTests as $test) {
        $url = $baseUrl . $test['path'];
        $res = hikRequest($url, $user, $pass, $test['method'], $test['body']);
        [$respHeaders, $respBody] = splitHeadersBody($res['raw']);

        echo "----------------------------------------\n";
        echo "TEST: {$test['name']}\n";
        echo "URL: {$url}\n";
        echo "METHOD: {$test['method']}\n";
        echo "HTTP CODE: " . ($res['info']['http_code'] ?? 'N/A') . "\n";
        echo "cURL errno: {$res['errno']}\n";
        echo "cURL error: {$res['error']}\n";
        echo "CONTENT-TYPE: " . ($res['info']['content_type'] ?? '') . "\n\n";

        echo "REQUEST BODY:\n";
        echo json_encode($test['body'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";

        echo "RESPONSE HEADERS:\n";
        echo $respHeaders . "\n\n";

        echo "RESPONSE BODY (primeros 3000 chars):\n";
        echo substr($respBody, 0, 3000) . "\n\n";
    }

    echo "\n\n";
}