<?php

if (!isset($_POST['reftag'])) {
    die("No reftag supplied.");
}

$reftag = "pd_sl_00fc12a23e094aa0abc98518b992dd5b_e";
//$reftag = $_POST['reftag'];

// Elasticsearch hosts
$hosts = [
    "192.168.26.133",
    "172.16.17.7",
    "10.0.28.157",
    "10.9.31.170",
    "10.8.24.19"
];

// auth & index
$index = "amazon_shop_reftag_1004";
$username = "admedia";
$password = "AdMedads@#4*";

// query payload
$payload = [
    "size" => 1,
    "_source" => ["sku"],
    "query" => [
        "term" => [
            "reftag" => $reftag
        ]
    ]
];

$results = [];

foreach ($hosts as $host) {

    $url = "https://$host:9200/$index/_search";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Content-Type: application/json"
    ]);

    // allow self-signed TLS
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);

    // store results for this host
    $results[] = [
        "host" => $host,
        "success" => ($response !== false && $httpCode >= 200 && $httpCode < 300),
        "http_code" => $httpCode,
        "error" => $err ?: null,
        "raw_response" => $response,
        "decoded" => json_decode($response, true)
    ];
}

// ========== OUTPUT SECTION ==========

echo "<h2>Search results for reftag: <code>$reftag</code></h2>";

foreach ($results as $r) {

    echo "<h3>Host: {$r['host']}</h3>";

    if ($r['success']) {
        echo "<strong>Status:</strong> ✔️ Success (HTTP {$r['http_code']})<br>";
        echo "<pre>";
        print_r($r['decoded']);
        echo "</pre>";
    } else {
        echo "<strong>Status:</strong> ❌ Failed<br>";
        echo "HTTP Code: {$r['http_code']}<br>";
        if ($r['error']) {
            echo "Curl Error: {$r['error']}<br>";
        }
        echo "<pre>Raw response:\n{$r['raw_response']}</pre>";
    }

    echo "<hr>";
}

