<?php
$auth_user = 'medij028';
$auth_pass = 'Tyn1iYe5Tl7KYr8QKs';
$api_url = 'https://www.apis-it.hr:8443/izbori/';

$context = stream_context_create([
  'http' => [
    'header' => 'Authorization: Basic ' . base64_encode("$auth_user:$auth_pass")
  ]
]);

$listing = @file_get_contents($api_url, false, $context);
if (!$listing) exit("❌ Ne mogu dohvatiti HTML listing s API URL-a<br>");

preg_match_all('/href=\"([^\"]+\.zip)\"/i', $listing, $matches);
$zip_list = $matches[1] ?? [];

if (empty($zip_list)) exit("➜ ❌ Nema dostupnih .zip datoteka u listingu<br>");

$zip_info = [];

foreach ($zip_list as $zip) {
    $url = $api_url . $zip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FILETIME, true);
    curl_setopt($ch, CURLOPT_USERPWD, "$auth_user:$auth_pass");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Ako koristiš self-signed certifikat
    curl_exec($ch);
    $filetime = curl_getinfo($ch, CURLINFO_FILETIME);
    curl_close($ch);

    if ($filetime != -1) {
        $zip_info[] = [
            'name' => $zip,
            'date' => $filetime
        ];
    } else {
        // Ako 'Last-Modified' nije dostupan, možemo postaviti datum na null ili preskočiti
        $zip_info[] = [
            'name' => $zip,
            'date' => null
        ];
    }
}

// Sortiraj po datumu silazno
usort($zip_info, function($a, $b) {
    return $b['date'] <=> $a['date'];
});

// Prikaz u HTML formatu
echo "<!DOCTYPE html><html lang='hr'><head><meta charset='UTF-8'><title>Dostupni ZIP-ovi</title>
<style>
body { font-family: sans-serif; margin: 20px; background: #f5f5f5; color: #333; }
h1 { font-size: 24px; margin-bottom: 20px; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
th { background-color: #e9ecef; }
</style>
</head><body>";

echo "<h1>Dostupni ZIP-ovi s API-a</h1>";
echo "<table>";
echo "<tr><th>Datum i vrijeme</th><th>Datoteka</th></tr>";

foreach ($zip_info as $zip) {
    $date_str = $zip['date'] ? date("Y-m-d H:i:s", $zip['date']) : 'N/A';
    $url = $api_url . $zip['name'];
    echo "<tr><td>$date_str</td><td><a href='$url' target='_blank'>{$zip['name']}</a></td></tr>";
}

echo "</table></body></html>";
?>
