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



$stmt5 = $pdo->query("SELECT * FROM info_podaci ORDER BY azurirano_at DESC LIMIT 1");
$info = $stmt5->fetch();

$mjeseci = [
  1 => 'siječnja', 2 => 'veljače', 3 => 'ožujka', 4 => 'travnja',
  5 => 'svibnja', 6 => 'lipnja', 7 => 'srpnja', 8 => 'kolovoza',
  9 => 'rujna', 10 => 'listopada', 11 => 'studenoga', 12 => 'prosinca'
];
$datum = strtotime($info['datum']);
$dan = date('j', $datum);
$mjesec = $mjeseci[(int)date('n', $datum)];
$godina = date('Y', $datum);

// Dohvati zupane
$stmt_zupani = $pdo->query("SELECT * FROM zupani ORDER BY broj_glasova DESC");
$zupani = $stmt_zupani->fetchAll();



// Dohvati gradove
$stmt_gradovi = $pdo->query("SELECT * FROM gradovi ORDER BY grad ASC, broj_glasova DESC");
$gradovi_raw = $stmt_gradovi->fetchAll(PDO::FETCH_ASSOC);

// Dohvati opcine
$stmt_opcine = $pdo->query("SELECT * FROM opcine ORDER BY opcina ASC, broj_glasova DESC");
$opcine_raw = $stmt_opcine->fetchAll(PDO::FETCH_ASSOC);

// Grupiraj po gradu/opcini
$slider_data = [];
foreach ($gradovi_raw as $row) {
  $grad = $row['grad'];
  $row['tip'] = 'Grad';

  if (!isset($slider_data[$grad])) $slider_data[$grad] = [];
  $slider_data[$grad][] = $row;
}
foreach ($opcine_raw as $row) {
  $opcina = $row['opcina'];
  $row['tip'] = 'Općina';
  if (!isset($slider_data[$opcina])) $slider_data[$opcina] = [];
  $slider_data[$opcina][] = $row;
}

// Pomoćna funkcija za generiranje boje
function getStrankaKlasa($stranka) {
  if (str_contains($stranka, 'SDP')) return 'red';
  if (str_contains($stranka, 'HDZ')) return 'blue';
  if (str_contains($stranka, 'IDS')) return 'green';
  if (str_contains($stranka, 'Možemo')) return 'purple';
  if (str_contains($stranka, 'Nezavisn')) return 'grey';
  return 'grey';
}


?>

<!DOCTYPE html>
<html lang="hr">
<head>
  <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
  body {
    margin: 0;
    font-family: 'Open Sans', sans-serif;
    max-width: 100%;
    overflow-x: hidden;
  }

  .mainWrapper {
    width: 100%;
    max-width: 1320px;
    height: 265px;
    display: flex;
    flex-direction: row;
    background-color: #fff;
    box-shadow: 0 1px 5px rgba(0,0,0,0.2);
    overflow: hidden;
    box-sizing: border-box;
    padding: 20px;
  }

  .leftPane {
    flex: 1 1 25%;
    padding-right: 0px;
    font-size: 16px;
    color: #222;
    display: flex;
    align-items: center;
    overflow: hidden;
  }

  .rightPane {
    flex: 3 1 75%;
    overflow: hidden;
    border-left: 1px solid #ccc;
    padding-left: 10px;
  }

  .party-summary ul {
    list-style: none;
    padding: 0;
    margin: 0;
    font-size: 16px;
    color: #333;
  }

  .party-summary li {
    margin-bottom: 14px;
  }

  .chart-bar-container {
    width: 545px;
    background-color: #ddd;
    border-radius: 2px;
    position: relative;
    height: 16px;
    display: flex;
    align-items: center;
    padding-left: 10px;
    box-sizing: border-box;
    margin-bottom: 3px;
    margin-top: 3px;
  }

  .chart-label {
    position: absolute;
    z-index: 2;
    font-weight: bold;
    font-size: 13px;
    color: #FFF;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding-left: 0px;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.6);
  }

  .chart-bar-fill {
    height: 100%;
    border-radius: 2px 0 0 2px;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
  }

  .chart-bar-red { background-color: #e03131; }
  .chart-bar-blue { background-color: #2b50a1; }
  .chart-bar-green { background-color: #9dd292; }
  .chart-bar-purple { background-color: #6b4fa1; }
  .chart-bar-grey { background-color: #999; }
  .chart-bar-akcijamladih { background-color: #ff9800; }
  .chart-bar-nlborisamiletića { background-color: #607d8b; }

  .left-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 12px;
  }

  .election-year {
    font-size: 65px;
    font-weight: 800;
    line-height: 1;
    color: #000;
  }

  .election-title {
    font-size: 16px;
    font-weight: 700;
    text-transform: uppercase;
    line-height: 1.2;
    letter-spacing: 0.5px;
    color: #000;
  }

  .election-type {
    font-size: 16px;
    font-weight: 400;
    color: #222;
  }

  .election-main {
    font-size: 20px;
    font-weight: 800;
    color: #111;
  }

  .election-status .processed {
    margin-top: 5px;
    font-size: 13px;
    font-weight: bold;
    color: #000;
  }

  .election-status .updated {
    font-size: 12px;
    color: #333;
  }

  .live-wrapper {
    margin-top: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-left: 5px;
  }

  .live-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background-color: #e03131;
    animation: pulse 1.2s infinite;
    box-shadow: 0 0 6px rgba(224, 49, 49, 0.6);
  }

  @keyframes pulse {
    0% { transform: scale(1); opacity: 1; }
    50% { transform: scale(1.4); opacity: 0.4; }
    100% { transform: scale(1); opacity: 1; }
  }

  .live-text .live {
    font-size: 13px;
    font-weight: bold;
    color: #000;
    line-height: 1.1;
  }

  .live-text .source {
    font-size: 11px;
    color: #555;
    line-height: 1.1;
  }

  .live-text-link {
    text-decoration: none;
    color: inherit;
    display: flex;
    flex-direction: column;
  }

  .live-text-link:hover .live {
    text-decoration: none;
  }

  .chart-percentage, .chart-votes {
    font-size: 13px;
    font-weight: bold;
    margin-top: 4px;
    color: #333;
  }

  .InnerResultsWrapper {
    display: flex;
    gap: 30px;
    margin-bottom: 40px;
  }

  .InnerLeft {
    width: 40%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .InnerRight {
    width: 60%;
    position: relative;
  }

  .CandidateRow {
    width: 100%;
    display: flex;
    justify-content: center;
    gap: 15px;
  }

  .Candidate {
    width: 48%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .CandidateCard {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .CandidatePhoto {
    width: 94px;
    height: 94px;
    background-size: cover;
    background-position: center;
    border-radius: 50%;
    border: 3px solid white;
    box-shadow: 0 0 5px rgba(0,0,0,0.4);
    margin-bottom: 11px;
  }

  .CandidateName {
    font-weight: bold;
    font-size: 15px;
    margin-bottom: 2px;
  }

  .CandidatePartyName {
    font-size: 12px;
    color: #666;
    margin-bottom: 6px;
  }

  .CandidateBar {
    width: 100%;
    height: 8px;
    background-color: #eee;
    border-radius: 3px;
    overflow: hidden;
    margin-bottom: 6px;
  }

  .CandidateBarFill {
    height: 100%;
    background-color: #888;
    transition: width 0.6s ease;
  }

  .CandidatePercentageTotal {
    font-weight: 600;
    color: #333;
  }

  h4.section-title {
    text-transform: uppercase;
    margin-top: 0px;
    margin-bottom: 13px;
    font-size: 18px;
  }

  .CitySliderWrapper {
    position: relative;
    overflow: hidden;
  }

  .CitySlider {
    display: flex;
    transition: transform 0.5s ease-in-out;
    width: 300%;
  }

  .CitySlide {
    width: 100%;
    flex: 0 0 100%;
    display: none;
    flex-direction: column;
    gap: 14px;
  }

  .CitySlide.active {
    display: flex;
  }

  .CitySliderControls {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 15px;
    position: absolute;
    right: 0;
    padding: 0 10px 10px 10px;
    background: #fff;
    z-index: 2;
  }

  .CitySliderControls button {
    padding: 6px 12px;
    font-size: 16px;
    cursor: pointer;
    background-color: #f2f2f2;
    border: 1px solid #ccc;
    border-radius: 4px;
  }

  .city-label {
    font-weight: bold;
    font-size: 22px;
    text-transform: uppercase;
    margin-bottom: 0px;
    margin-top: 0px;
  }

  .candidate .name {
    font-weight: bold;
    font-size: 15px;
    margin-bottom: 2px;
  }

  .candidate .affiliation {
    font-size: 12px;
    color: #666;
  }

  @media (max-width: 768px) {
    .mainWrapper {
      flex-direction: column;
      height: auto;
      padding: 15px;
    }

    .leftPane, .rightPane {
      flex: 1 1 100%;
      padding: 0;
      margin-bottom: 20px;
    }

    .rightPane {
border-left: 0px!important;
    }


    .InnerResultsWrapper {
      flex-direction: column;
    }

    .InnerLeft, .InnerRight {
      width: 100%;
      text-align: center;
    }

    .leftPane {
      justify-content: center;
      align-items: center;
      text-align: center;
    }

    .election-year {
      font-size: 42px;
      text-align: center;
    }

    .election-title {
      text-align: center;
    }

    .election-type {
      font-size: 16px;
    }

    .election-main {
      font-size: 18px;
    }

    .election-status {
      text-align: center;
    }

    .election-status .processed,
    .election-status .updated {
      font-size: 12px;
    }

    .live-wrapper {
      justify-content: center;
      margin-top: 12px;
    }


    .chart-label {
      position: relative;
      font-size: 12px;
      white-space: normal;
      overflow: visible;
      text-overflow: initial;
      padding-left: 0;
      margin-bottom: 4px;
      color: #111;
      text-shadow: none;
      z-index: auto;
    }

    .chart-bar-fill {
      position: relative;
      height: 8px;
      border-radius: 4px;
      width: 100%;
    }

    .party-summary ul {
      padding: 0 5px;
    }

    .party-summary li {
      margin-bottom: 12px;
    }

    .CandidateRow {
        flex-wrap: wrap;
        justify-content: center;
        gap: 30px;
        max-width: 95%;
    }

.CitySlider {
  width: 100%;
}

.CitySlide {
  width: 100% !important;
  flex: 0 0 100%;
  display: none;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.CitySlide.active {
  display: flex !important;
}


.CitySliderControls {
  position: static;
  justify-content: center;
  margin-top: 15px;
  background: none;
}

.CitySliderControls button {
  padding: 6px 10px;
}

.candidate {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}



.chart-result-line {
  display: flex;
  gap: 5px;
  font-size: 14px;
}

 .CandidateCard {
    width: 100%;
    max-width: 300px;
  }
  .chart-bar-container {
    width: 100%;
    max-width: 90%;
    box-sizing: border-box;
  }

  }

  .chart-bar-green { background-color: #9dd292; }
.chart-bar-blue { background-color: #2b50a1; }
.chart-bar-red { background-color: #e03131; }
.chart-bar-purple { background-color: #6b4fa1; }
.chart-bar-grey { background-color: #999; }
</style>



</head>
<body>

<div class="mainWrapper">



<div class="leftPane">
  <div class="left-content">
    <div class="election-year">2025.</div>
    <div class="election-title">
      <span class="election-type">LOKALNI IZBORI - ISTARSKA ŽUPANIJA</span><br>
      <span class="election-main">II. KRUG - Rezultata izbora</span>
    </div>
    <div class="election-status">
      <div class="processed">Obrađeno <?= number_format($info['obradeno'], 2, ',', '') ?>% glasačkih listića.</div>
      <div class="updated">POSLJEDNJA IZMJENA: <?= date('H:i', strtotime($info['vrijeme'])) ?> sati, 
    dana <?= date('d.m.Y.', strtotime($info['datum'])) ?></div>
    </div>

 <div class="live-wrapper">
      <div class="live-dot"></div>
     <a href="https://istrain.hr/lokalni-izbori/vijesti/683c8f49b5702/miletic-i-dalje-u-vodstvu-razlika-se-zadrzava-obradeno-gotovo-99-posto-birackih-mjesta/vijest" target="_blank" class="live-text-link">
  <div class="live-text">
    <div class="live">REZULTATI UŽIVO</div>
    <div class="source">PODATKE OSIGURAVA: APIS IT D.O.O.</div>
  </div>
</a>
    </div>


  </div>
</div>











  <div class="rightPane">

  


<div class="InnerResultsWrapper">
  <div class="InnerLeft">
    <h4 class="section-title">Rezultati županije</h4>

    <div class="CandidateRow">

        <?php foreach ($zupani as $red): ?>
      <?php
        $ime = htmlspecialchars($red['kandidat']);
        $stranka = htmlspecialchars($red['stranka']);

        $glasova = intval($red['broj_glasova'] ?? 0);
$postotak_raw = floatval($red['postotak'] ?? 0);

// ako je postotak 0 i imamo glasove, pokušaj izračun
if ($postotak_raw === 0.0 && $glasova > 0) {
  $total_glasova = array_sum(array_map(fn($z) => intval($z['broj_glasova'] ?? 0), $zupani));
  $postotak_raw = $total_glasova > 0 ? ($glasova / $total_glasova * 100) : 0;
}

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

        
        // mapa za CSS boje
        $boje = [
          'SDP' => 'red',
          'HDZ' => 'blue',
          'IDS' => 'green',
          'Možemo!' => 'purple',
          'Nezavisni' => 'grey',
        ];
        // uklanjanje nepotrebnih znakova kod usporedbe
        $kljuc = preg_replace('/[^a-zA-Z0-9]/', '', $stranka);
    // automatski odabir boje po sadržaju stranke
$klasa = 'grey'; // default
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, 'Nezavisni')) {
    $klasa = 'grey';
}

if (str_contains($ime, 'BORIS')) {
    $imgShow = 'images/boris.png';
}else if (str_contains($ime, 'SANJA')) {
$imgShow = 'images/sanja.png';
}
      ?>


      <div class="CandidateCard">
        <div class="CandidatePhoto" style="background-image: url('<?= $imgShow ?>');"></div>
        <div class="CandidateName"><?= $ime ?></div>
        <div class="CandidatePartyName"><?= $stranka ?></div>
        <div class="CandidateBar">
          <div class="CandidateBarFill chart-bar-<?= $klasa ?>" style="width: <?= $width ?>%;"></div>
        </div>
        <div class="CandidatePercentageTotal"><?= $postotak ?>%</div>
      </div>


      <?php endforeach; ?>


      
    </div>
  </div>

<!-- Unutar InnerRight -->
<div class="InnerRight">
  <h4 class="section-title">Rezultati gradova i općina</h4>

  
    <div class="CitySliderControls">
      <button class="city-prev">&#8592;</button>
      <button class="city-next">&#8594;</button>
    </div>


  <div class="CitySliderWrapper">
    <div class="CitySlider" id="citySlider">


 <?php foreach ($slider_data as $naziv => $kandidati): ?>
    <div class="CitySlide">
      <h5 class="city-label"><?= htmlspecialchars($kandidati[0]['tip']) ?> <?= htmlspecialchars($naziv) ?></h5>
      <?php foreach ($kandidati as $k): 
        $postotak = floatval($k['postotak']);
        $glasova = intval($k['broj_glasova']);
        $klasa = getStrankaKlasa($k['stranka']);
      ?>
        <div class="candidate">
          <span class="name"><?= htmlspecialchars($k['kandidat']) ?></span>
          <span class="affiliation"> (<?= htmlspecialchars($k['stranka']) ?>)</span>
          <div class="chart-bar-container">
            <div class="chart-bar-fill chart-bar-<?= $klasa ?>" style="width: <?= $postotak ?>%"></div>
          </div>
          <div class="chart-result-line">
            <span class="chart-percentage"><?= number_format($postotak, 1, ',', '') ?>%</span>
            <span class="chart-votes"> – <?= number_format($glasova, 0, ',', '.') ?> glasova</span>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endforeach; ?>
     

      
    
      </div>

    </div>
    
  </div>
</div>


</div>

















    </div>
  </div>
</div>

</body>
</html>


<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');

    // Dohvati izvorni % iz style atributa
    const style = $bar.attr('style');
    const match = style.match(/width:\s*([\d.]+)%/);
    if (!match) return;

    const targetPercent = parseFloat(match[1]);

    // Resetiraj početno stanje
    $bar.css('width', '0%');
    $percentageLabel.text('0%');

    // Pokreni animaciju
    $({ 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>


<script>
$(document).ready(function() {
  const slides = $('.CitySlide');
  let current = 0;
  let timer;

  function showSlide(index) {
    slides.removeClass('active');
    slides.eq(index).addClass('active');
  }

  function nextSlide() {
    current = (current + 1) % slides.length;
    showSlide(current);
  }

  function prevSlide() {
    current = (current - 1 + slides.length) % slides.length;
    showSlide(current);
  }

  $('.city-next').click(function() {
    nextSlide();
    resetTimer();
  });

  $('.city-prev').click(function() {
    prevSlide();
    resetTimer();
  });

  function startTimer() {
    timer = setInterval(nextSlide, 3000);
  }

  function resetTimer() {
    clearInterval(timer);
    startTimer();
  }

  showSlide(current);
  startTimer();
});
</script>