<?php 
error_reporting(error_reporting() & ~E_DEPRECATED);
include 'db-conn.php'; 

// Grad iz GET parametra
$grad_param = isset($_GET['city']) ? trim($_GET['city']) : '';
if (empty($grad_param)) {
    die('Grad nije specificiran.');
}

// Pretvori u veliko slovo za usporedbu s bazom
$grad_ime = strtoupper($grad_param);

// Dohvati sve kandidate za zadani grad
$stmt = $pdo->prepare("SELECT * FROM gradovi WHERE grad = :grad ORDER BY postotak DESC");
$stmt->execute(['grad' => $grad_ime]);
$kandidati = $stmt->fetchAll();

// Ako nema kandidata, prikaži poruku
if (empty($kandidati)) {
    die("Nema podataka za grad: " . htmlspecialchars($grad_ime));
}

// Dohvati zadnje ažuriranje
$info = $pdo->query("SELECT * FROM info_podaci ORDER BY azurirano_at DESC LIMIT 1")->fetch();
if (!$info) {
    $info = ['vrijeme' => '00:00:00', 'datum' => date('Y-m-d'), 'obradeno' => 0];
}
?>

<!DOCTYPE html>
<html lang="hr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rezultati – <?= htmlspecialchars($grad_ime) ?></title>
  <link rel="stylesheet" href="styles.css?v=4">
  <link rel="stylesheet" href="responsive.css?v=4" media="screen and (max-width: 991px)">
</head>
<body>
  <div class="main-wrapper">
    <div class="city-group">
      <div class="city">
        <p class="city-name"><?= htmlspecialchars($grad_ime) ?></p>

        <?php
        // Ukupno glasova za izračun postotka ako fali
        $total_glasova = array_sum(array_map(fn($k) => intval($k['broj_glasova'] ?? 0), $kandidati));

        foreach ($kandidati as $kandidat):
          $ime = htmlspecialchars($kandidat['kandidat']);
          $stranka = htmlspecialchars($kandidat['stranka']);
          $glasova = intval($kandidat['broj_glasova'] ?? 0);
          $postotak = floatval($kandidat['postotak'] ?? 0);

          if (empty($postotak) && $glasova > 0 && $total_glasova > 0) {
              $postotak = ($glasova / $total_glasova) * 100;
          }

          $prikazani_postotak = number_format($postotak, 1, ',', '');
          $width = str_replace(',', '.', $prikazani_postotak);

          // Klasa boje
          $klasa = 'grey';
          if (str_contains($stranka, 'SDP')) $klasa = 'red';
          elseif (str_contains($stranka, 'HDZ')) $klasa = 'blue';
          elseif (str_contains($stranka, 'IDS')) $klasa = 'green';
          elseif (str_contains($stranka, 'Možemo')) $klasa = 'purple';
          elseif (str_contains($stranka, 'Nezavisn')) $klasa = 'grey';
        ?>
          <div class="candidate">
            <span class="name"><?= $ime ?></span>
            <span class="affiliation">(<?= $stranka ?>)</span>
            <div class="chart-bar-container">
              <div class="chart-bar-fill chart-bar-<?= $klasa ?>" style="width: <?= $width ?>%"></div>
            </div>
            <span class="chart-percentage"><?= $prikazani_postotak ?>%</span>
          </div>
        <?php endforeach; ?>
      </div>
    </div>

    <footer class="footer">
      <p>
        Zadnji podaci ažurirani u <?= date('H:i', strtotime($info['vrijeme'])) ?> sati, 
        dana <?= date('d.m.Y.', strtotime($info['datum'])) ?>, obrađeno 
        <?= number_format($info['obradeno'], 2, ',', '') ?>% glasačkih listića.
      </p>
    </footer>
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function () {
      $('.chart-bar-fill').each(function () {
        const $bar = $(this);
        const $percentageLabel = $bar.closest('.candidate').find('.chart-percentage');
        const style = $bar.attr('style');
        const match = style.match(/width:\s*([\d.]+)%/);
        if (!match) return;
        const targetPercent = parseFloat(match[1]);

        $bar.css('width', '0%');
        $percentageLabel.text('0%');

        $({ percent: 0 }).animate({ percent: targetPercent }, {
          duration: 1500,
          step: function (now) {
            const rounded = now.toFixed(1);
            $bar.css('width', `${rounded}%`);
            $percentageLabel.text(`${rounded}%`);
          },
          complete: function () {
            $bar.css('width', `${targetPercent}%`);
            $percentageLabel.text(`${targetPercent}%`);
          }
        });
      });
    });
  </script>
</body>
</html>
