<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=utf-8");

$startTime = microtime(true);

// -------------------------------------------------------------
// 1) FUNCTION: Safe HTTPS fetch using cURL
// -------------------------------------------------------------
function curl_get($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

// -------------------------------------------------------------
// 2) FETCH ODYSSEY TEXT
// -------------------------------------------------------------
$url = "https://pleiades.math.uoi.gr/odyssey.txt";
$text = curl_get($url);

if ($text === false || strlen($text) < 100) {
    echo json_encode(["error" => "Failed to fetch text"]);
    exit;
}

// -------------------------------------------------------------
// 3) SPAWN 26 PARALLEL SUBTASKS USING curl_multi
// -------------------------------------------------------------
$mh = curl_multi_init();
$handles = [];

for ($i = 0; $i < 1; $i++) {
    $letter = chr(97 + $i); // a..z
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,
        "https://pleiades.math.uoi.gr/~test/public_html_2024/ADE/Erg8/js/countLetter.php?letter=$letter"
    );

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(["text" => $text]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $handles[$letter] = $ch;
    curl_multi_add_handle($mh, $ch);
}

// -------------------------------------------------------------
// 4) EXECUTE ALL 26 SUBTASKS IN PARALLEL
// -------------------------------------------------------------
$running = null;
do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while ($running > 0);

// -------------------------------------------------------------
// 5) COLLECT RESULTS
// -------------------------------------------------------------
$counts = [];

foreach ($handles as $letter => $ch) {
    $response = curl_multi_getcontent($ch);
    $data = json_decode($response, true);
    $counts[$letter] = $data["count"] ?? 0;

    curl_multi_remove_handle($mh, $ch);
    curl_close($ch);
}

curl_multi_close($mh);

// -------------------------------------------------------------
// 6) EXECUTION TIME
// -------------------------------------------------------------
$time = round((microtime(true) - $startTime) * 1000, 2); // ms

// -------------------------------------------------------------
// 7) SEND JSON RESULT
// -------------------------------------------------------------
echo json_encode([
    "execution_time_ms" => $time,
    "counts" => $counts
]);
?>

