<?php
session_start();
// Provjera da li je korisnik ulogiran i da li je admin
if (!isset($_SESSION['uloga']) || $_SESSION['uloga'] !== 'admin') {
    exit("Nedozvoljen pristup. Samo administratori imaju pristup ovoj stranici.");
}
?>
<!DOCTYPE html>
<html lang="hr">
<head>
  <meta charset="UTF-8" />
  <title>Godišnji odmori djelatnika</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.28/jspdf.plugin.autotable.min.js"></script>
  <style>
    body { font-family: 'Segoe UI', sans-serif; background: #f4f6f8; padding: 20px; }
    .card { background: #fff; border-radius: 8px; padding: 15px; margin-bottom: 20px; box-shadow: 0 0 6px rgba(0,0,0,0.1); }
    h1 { color: #2c3e50; }
    input, button { margin: 5px; padding: 6px 10px; border-radius: 5px; border: 1px solid #ccc; }
    button { background-color: #3498db; color: white; cursor: pointer; }
    button:hover { background-color: #2980b9; }
    .vacation-entry { display: flex; align-items: center; gap: 5px; margin-bottom: 5px; flex-wrap: wrap; }
    .delete-btn { background-color: #e74c3c; }
    .delete-btn:hover { background-color: #c0392b; }
    .exhausted { color: red !important; }
    #summaryBtn { background-color: #27ae60; }
    #summaryBtn:hover { background-color: #1e8449; }
    .used-date {
      border: 1px solid #3498db;
      background-color: #eaf4fb;
      color: #2c3e50;
    }
  </style>
</head>
<body>
<div class="container mt-4">
  <div class="d-flex justify-content-end mb-3">
    <a href="./admin.php" class="btn btn-outline-primary me-2">← Povratak </a>
    <a href="./logout.php" class="btn btn-outline-danger">Odjava</a>
  </div>
</div>

  <h1>Godišnji odmori djelatnika</h1>

  <input type="text" id="pretraga" placeholder="Pretraži djelatnika..." oninput="filtrirajDjelatnike()" style="margin-bottom: 20px; width: 300px;" />
  <br />
  <button id="summaryBtn" onclick="generirajListu()">Pokaži sve djelatnike (status godišnjeg)</button>
  <button onclick="exportPDF()">Izvezi PDF</button>

  <div class="card">
    <h2>Dodaj djelatnika</h2>
    <input type="text" id="ime" placeholder="Ime djelatnika" />
    <input type="number" id="ukupno" placeholder="Ukupno dana godišnjeg" />
    <button onclick="dodajDjelatnika()">Dodaj</button>
  </div>

  <div id="djelatnici"></div>

<script>
  /* =============== Lokalni format Y-M-D (bez UTC pomaka) =============== */
  function pad2(n){ return String(n).padStart(2,'0'); }
  function toYMD(str){
    if(!str) return '';
    if(/^\d{4}-\d{2}-\d{2}$/.test(str)) return str;                // yyyy-mm-dd
    const m=str.match(/^(\d{2})[\/.\-](\d{2})[\/.\-](\d{4})/);     // dd.mm.yyyy itd.
    if(m){ const [,dd,mm,yyyy]=m; return `${yyyy}-${mm}-${dd}`; }
    const d=new Date(str);
    if (isNaN(d)) return '';
    return `${d.getFullYear()}-${pad2(d.getMonth()+1)}-${pad2(d.getDate())}`;
  }
  function ymdFromDate(d){
    return `${d.getFullYear()}-${pad2(d.getMonth()+1)}-${pad2(d.getDate())}`;
  }
  function newLocalDateFromAny(str){
    const ymd = toYMD(str);
    const [y,m,d] = ymd.split('-').map(Number);
    return new Date(y,(m||1)-1,(d||1));
  }

  /* ===================== HR PRAZNICI (auto po godini) ===================== */
  function easterSundayYMD(year){
    const a=year%19,b=Math.floor(year/100),c=year%100,d=Math.floor(b/4),e=b%4;
    const f=Math.floor((b+8)/25),g=Math.floor((b-f+1)/3);
    const h=(19*a+b-d-g+15)%30,i=Math.floor(c/4),k=c%4;
    const l=(32+2*e+2*i-h-k)%7,m=Math.floor((a+11*h+22*l)/451);
    const month=Math.floor((h+l-7*m+114)/31),day=((h+l-7*m+114)%31)+1;
    return `${year}-${pad2(month)}-${pad2(day)}`;
  }
  function addDaysYMD(ymd, days){
    const [y,m,d]=ymd.split('-').map(Number);
    const dt=new Date(y,m-1,d); dt.setDate(dt.getDate()+days);
    return ymdFromDate(dt);
  }
  function croatianHolidaysSet(year){
    const s=new Set([
      `${year}-01-01`, `${year}-01-06`, `${year}-05-01`,
      `${year}-05-30`, `${year}-06-22`, `${year}-08-05`,
      `${year}-08-15`, `${year}-11-01`, `${year}-11-18`,
      `${year}-12-25`, `${year}-12-26`
    ]);
    const easter=easterSundayYMD(year);
    s.add(addDaysYMD(easter,1));   // Uskrsni ponedjeljak
    s.add(addDaysYMD(easter,60));  // Tijelovo
    return s;
  }
  function holidaysForRange(odYMD, doYMD){
    const y1=Number(odYMD.slice(0,4)), y2=Number(doYMD.slice(0,4));
    const out=new Set();
    for(let y=y1;y<=y2;y++){ for(const d of croatianHolidaysSet(y)) out.add(d); }
    return out;
  }

  /* ===================== IZRAČUN RADNIH DANA ===================== */
  // subota se računa, nedjelja i praznici NE
  function izracunajRadneDane(od, doDat){
    const odYMD = toYMD(od);
    const doYMD = toYMD(doDat);
    if (!odYMD || !doYMD) return 0;

    const prazniciSet = holidaysForRange(odYMD, doYMD);
    let s = newLocalDateFromAny(odYMD);
    let e = newLocalDateFromAny(doYMD);
    if (isNaN(s) || isNaN(e) || s > e) return 0;

    let cnt = 0;
    while (s <= e) {
      const day = s.getDay(); // 0=nedjelja, 6=subota
      const isSunday = day === 0;
      const isHoliday = prazniciSet.has(ymdFromDate(s));
      if (!isSunday && !isHoliday) cnt++; // subota se broji
      s.setDate(s.getDate() + 1);
    }
    return cnt;
  }

  /* ===================== GLAVNA LOGIKA ===================== */
  let djelatnici = [];

  async function ucitajDjelatnike() {
    const res = await fetch('api.php');
    djelatnici = await res.json();
    prikaziDjelatnike();
  }

  function prikaziDjelatnike(lista = djelatnici) {
    const kont = document.getElementById('djelatnici');
    kont.innerHTML = '';

    lista.forEach(d => {
      const iskoristeno = (d.godisnji||[]).reduce((s,g)=> s + izracunajRadneDane(g.datum_od, g.datum_do), 0);
      const preostalo = (parseInt(d.ukupno,10)||0) - iskoristeno;
      const exhausted = preostalo <= 0 ? 'exhausted' : '';

      const div = document.createElement('div');
      div.className = 'card';
      div.innerHTML = `
        <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;">
          <h2 class="${exhausted}" style="margin:0;">${d.ime}</h2>
          <p style="margin:0;">Ukupno: <b>${d.ukupno}</b> | Iskorišteno: <b>${iskoristeno}</b> | Preostalo: <b>${preostalo}</b></p>
        </div>
        <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:8px;">
          <input type="date" id="od-${d.id}" />
          <input type="date" id="do-${d.id}" />
          <span id="preview-${d.id}" style="font-weight:600;">Radnih dana: 0</span>
          <button onclick="dodajGodisnji(${d.id})">Dodaj</button>
        </div>
        <div id="lista-${d.id}" style="margin-top:10px;"></div>
      `;
      kont.appendChild(div);

      // Live preview
      const odEl = div.querySelector(`#od-${d.id}`);
      const doEl = div.querySelector(`#do-${d.id}`);
      const prevEl = div.querySelector(`#preview-${d.id}`);
      const updatePreview = () => {
        prevEl.textContent = `Radnih dana: ${izracunajRadneDane(odEl.value, doEl.value)}`;
      };
      odEl.addEventListener('change', updatePreview);
      doEl.addEventListener('change', updatePreview);

      prikaziGodisnje(d);
    });
  }

  function prikaziGodisnje(d) {
    const lista = document.getElementById(`lista-${d.id}`);
    lista.innerHTML = '';
    (d.godisnji||[]).forEach(g => {
      const brojDana = izracunajRadneDane(g.datum_od, g.datum_do);
      const row = document.createElement('div');
      row.className = 'vacation-entry';
      row.innerHTML = `
        <input type="date" value="${toYMD(g.datum_od)}" id="edit-od-${g.id}" class="used-date" />
        <input type="date" value="${toYMD(g.datum_do)}" id="edit-do-${g.id}" class="used-date" />
        <span id="edit-broj-${g.id}" style="margin-left:5px;">(${brojDana} dana)</span>
        <button onclick="spremiGodisnji(${g.id})">Spremi</button>
        <button class="delete-btn" onclick="obrisiGodisnji(${g.id})">Obriši</button>
      `;
      lista.appendChild(row);

      const odEl = row.querySelector(`#edit-od-${g.id}`);
      const doEl = row.querySelector(`#edit-do-${g.id}`);
      const brojEl = row.querySelector(`#edit-broj-${g.id}`);
      const update = () => brojEl.textContent = `(${izracunajRadneDane(odEl.value, doEl.value)} dana)`;
      odEl.addEventListener('change', update);
      doEl.addEventListener('change', update);
    });
  }

  async function dodajDjelatnika() {
    const ime = document.getElementById('ime').value.trim();
    const ukupno = parseInt(document.getElementById('ukupno').value,10);
    if (!ime || isNaN(ukupno)) return alert("Unesi ime i dane!");

    await fetch('api.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({type: 'djelatnik', ime, ukupno})
    });

    document.getElementById('ime').value = '';
    document.getElementById('ukupno').value = '';
    await ucitajDjelatnike();
  }

  async function dodajGodisnji(id) {
    const od = document.getElementById(`od-${id}`).value;
    const doDat = document.getElementById(`do-${id}`).value;
    if (!od || !doDat) return alert("Unesi datume!");

    const n = izracunajRadneDane(od, doDat);
    if (n === 0 && !confirm("U rasponu nema radnih dana (samo nedjelje/praznici). Svejedno spremiti?")) return;

    await fetch('api.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({type: 'godisnji', djelatnik_id: id, datum_od: toYMD(od), datum_do: toYMD(doDat)})
    });
    await ucitajDjelatnike();
  }

  async function spremiGodisnji(id) {
    const od = document.getElementById(`edit-od-${id}`).value;
    const doDat = document.getElementById(`edit-do-${id}`).value;
    if (!od || !doDat) return alert("Unesi datume!");

    await fetch('api.php', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({id, datum_od: toYMD(od), datum_do: toYMD(doDat)})
    });
    await ucitajDjelatnike();
  }

  // ✅ BRISANJE — naziv funkcije usklađen s gumbom (onclick="obrisiGodisnji(...)")
  async function obrisiGodisnji(id) {
    if (!confirm("Brisati ovaj unos?")) return;
    const res = await fetch('api.php', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({ type:'delete_godisnji', id })
    });
    const out = await res.json().catch(()=>({}));
    if (out && out.success) {
      await ucitajDjelatnike();
    } else {
      alert('Greška pri brisanju!');
    }
  }

  function generirajListu() {
    let txt = "Ime | Ukupno | Iskorišteno | Preostalo\n\n";
    (djelatnici||[]).forEach(d => {
      const isk = (d.godisnji||[]).reduce((s, g) => s + izracunajRadneDane(g.datum_od, g.datum_do), 0);
      const pre = (parseInt(d.ukupno,10)||0) - isk;
      txt += `${d.ime} | ${d.ukupno} | ${isk} | ${pre}\n`;
    });
    alert(txt);
  }

  function exportPDF() {
    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();

    doc.setFontSize(16);
    doc.text("Godišnji odmori djelatnika", 20, 15);

    const head = [['Ime djelatnika', 'Ukupno dana', 'Iskorišteno', 'Preostalo']];
    const body = (djelatnici||[]).map(d => {
      const isk = (d.godisnji||[]).reduce((s, g) => s + izracunajRadneDane(g.datum_od, g.datum_do), 0);
      const pre = (parseInt(d.ukupno,10)||0) - isk;
      return [d.ime, String(d.ukupno), String(isk), String(pre)];
    });

    doc.autoTable({
      startY: 25,
      head,
      body,
      theme: 'striped',
      headStyles: { fillColor: [52,152,219] },
      styles: { fontSize: 12 }
    });

    doc.save("godisnji_tablica.pdf");
  }

  function filtrirajDjelatnike() {
    const query = (document.getElementById('pretraga').value || '').toLowerCase();
    if (!query) return prikaziDjelatnike();
    prikaziDjelatnike((djelatnici||[]).filter(d => (d.ime||'').toLowerCase().includes(query)));
  }

  ucitajDjelatnike();
</script>

</body>
</html>
