<?php

// admin.php
session_start();
$timeout = 1200; // 20 minute

// Timeout sesije
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $timeout)) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit();
}
$_SESSION['last_activity'] = time();

// Dozvola
if (!isset($_SESSION['uloga']) || $_SESSION['uloga'] !== 'admin') {
    exit("Nedozvoljen pristup");
}

// DB
$conn = new mysqli("localhost", "root", "", "upload");
if ($conn->connect_error) { exit("DB greška."); }
$conn->set_charset('utf8mb4');

/* ---------------- Mapiranje ID-eva poslovnica po nazivu ---------------- */
$wantedNames = [
    'Zagreb'     => null,
    'Split'      => null,
    'Šibenik'    => null,
    'Sibenik'    => null,
    'Pula'       => null,
    // ZadarDT/AP i Dubrovnik (najmovi/blagajna) su ručno zadani dolje
];

$found = [];
$res = $conn->query("SELECT id, naziv FROM poslovnice");
if ($res) {
    while ($r = $res->fetch_assoc()) {
        $naz = trim($r['naziv']);
        if (array_key_exists($naz, $wantedNames) && $wantedNames[$naz] === null) {
            $found[$naz] = (int)$r['id'];
        }
        if (!isset($found['Šibenik']) && (strcasecmp($naz, 'Šibenik') === 0 || strcasecmp($naz, 'Sibenik') === 0)) {
            $found['Šibenik'] = (int)$r['id'];
        }
    }
}

// Fiksni ID-evi po zahtjevu
$ZADAR_DT_ID = 11; // read-only najmove
$ZADAR_AP_ID = 12; // read-only najmove

// Dubrovnik: razdvojeni ID-jevi
$DBV_CASH_ID = 2;   // blagajna (transakcije)
$DBV_RENT_ID = 10;  // najmove + izvještaj

$branchId = [
    'zagreb'    => $found['Zagreb']   ?? null,
    'split'     => $found['Split']    ?? null,
    'sibenik'   => $found['Šibenik']  ?? $found['Sibenik'] ?? null,
    'pula'      => $found['Pula']     ?? null,
    'zadardt'   => $ZADAR_DT_ID,
    'zadarap'   => $ZADAR_AP_ID,
];

/* ---------------- Router: sekcije ---------------- */
$section = isset($_GET['section']) ? strtolower($_GET['section']) : 'home';
$validSections = ['home','zagreb','zadardt','zadarap','split','dubrovnik','sibenik','pula','odmori','place'];

if (!in_array($section, $validSections, true)) $section = 'home';

/* -------- HOME: Stanja + zbrojevi najmova + broj ugovora ------- */
$pregled_stanja = $conn->query("
    SELECT 
        p.id, 
        p.naziv, 
        p.uloga,
        IFNULL((
            SELECT SUM(CASE WHEN t.tip='uplata' THEN t.iznos ELSE -t.iznos END)
            FROM transakcije t
            WHERE t.poslovnica_id = p.id
        ), 0) AS stanje,
        IFNULL((
            SELECT SUM(m.iznos)
            FROM najmovi m
            WHERE m.poslovnica_id = p.id
              AND m.vrsta = 'najam'
        ), 0) AS suma_najmova,
        IFNULL((
            SELECT COUNT(*)
            FROM najmovi m2
            WHERE m2.poslovnica_id = p.id
              AND m2.vrsta = 'najam'
        ), 0) AS broj_ugovora
    FROM poslovnice p
    ORDER BY p.naziv
");

/* -------- Blagajne (Zagreb/Split/Šibenik/Pula) ------- */
$selected_id = 0;
if (in_array($section, ['zagreb','split','sibenik','pula'], true)) {
    $selected_id = (int)($branchId[$section] ?? 0);
}

$naziv = '';
$uloga = '';
$stanje = 0.0;
$transakcije = null;

if ($selected_id > 0 && in_array($section, ['zagreb','split','sibenik','pula'], true)) {
    $stmtMeta = $conn->prepare("SELECT naziv, uloga FROM poslovnice WHERE id = ?");
    $stmtMeta->bind_param("i", $selected_id);
    $stmtMeta->execute();
    $stmtMeta->bind_result($naziv, $uloga);
    $stmtMeta->fetch();
    $stmtMeta->close();

    $stmtSt = $conn->prepare("
        SELECT IFNULL(SUM(CASE WHEN tip='uplata' THEN iznos ELSE 0 END),0)
             - IFNULL(SUM(CASE WHEN tip='isplata' THEN iznos ELSE 0 END),0) AS stanje
        FROM transakcije
        WHERE poslovnica_id = ?
    ");
    $stmtSt->bind_param("i", $selected_id);
    $stmtSt->execute();
    $stmtSt->bind_result($stanje);
    $stmtSt->fetch();
    $stmtSt->close();

    $stmtTr = $conn->prepare("
        SELECT id, datum, tip, opis, iznos
        FROM transakcije
        WHERE poslovnica_id = ?
        ORDER BY datum DESC, id DESC
    ");
    $stmtTr->bind_param("i", $selected_id);
    $stmtTr->execute();
    $transakcije = $stmtTr->get_result();
    $stmtTr->close();
}

/* -------- Read-only pregledi najmova za ZadarDT (ID 11) i ZadarAP (ID 12) ------- */
$listMode = in_array($section, ['zadardt','zadarap'], true);
$listId = 0; $listNaziv = ''; $listUloga = ''; $q = ''; $per_page = 50; $page = 1; $offset = 0;
$listTotal = 0; $listSum = 0.0; $listRows = null;

if ($listMode) {
    $listId = ($section === 'zadardt') ? $ZADAR_DT_ID : $ZADAR_AP_ID;

    // Naziv/uloga poslovnice
    $stmtLN = $conn->prepare("SELECT naziv, uloga FROM poslovnice WHERE id=?");
    $stmtLN->bind_param("i", $listId);
    $stmtLN->execute();
    $stmtLN->bind_result($listNaziv, $listUloga);
    $stmtLN->fetch();
    $stmtLN->close();

    // Pretraga + paginacija
    $q = trim((string)($_GET['q'] ?? ''));
    $page = max(1, (int)($_GET['page'] ?? 1));
    $per_page = max(10, (int)($_GET['per_page'] ?? 50));
    $offset = ($page - 1) * $per_page;

    // Count + Sum
    $baseWhere = " poslovnica_id = ? AND vrsta='najam' ";
    $typesAgg = "i";
    $paramsAgg = [$listId];
    if ($q !== '') {
        $baseWhere .= " AND ime_prezime LIKE CONCAT('%', ?, '%') ";
        $typesAgg .= "s";
        $paramsAgg[] = $q;
    }
    $sqlAgg = "SELECT COUNT(*) AS cnt, IFNULL(SUM(iznos),0) AS suma FROM najmovi WHERE $baseWhere";
    $stmtAgg = $conn->prepare($sqlAgg);
    $stmtAgg->bind_param($typesAgg, ...$paramsAgg);
    $stmtAgg->execute();
    $aggRes = $stmtAgg->get_result()->fetch_assoc();
    $stmtAgg->close();
    $listTotal = (int)($aggRes['cnt'] ?? 0);
    $listSum   = (float)($aggRes['suma'] ?? 0.0);

    // List
    $sqlList = "
      SELECT id, ime_prezime, adresar_id, grupa_vozila, tablica_vozila,
             datum_out, datum_in, nacin_placanja, iznos, napomena
      FROM najmovi
      WHERE $baseWhere
      ORDER BY datum_out DESC, id DESC
      LIMIT ? OFFSET ?
    ";
    $typesList = $typesAgg . "ii";
    $paramsList = $paramsAgg;
    $paramsList[] = $per_page;
    $paramsList[] = $offset;

    $stmtList = $conn->prepare($sqlList);
    $stmtList->bind_param($typesList, ...$paramsList);
    $stmtList->execute();
    $listRows = $stmtList->get_result();
    $stmtList->close();
}

/* -------- DUBROVNIK: tri gumba (Blagajna=ID2 / Najmovi+Izvještaj=ID10) -------- */
$dbvtab = ($section === 'dubrovnik') ? ($_GET['dbvtab'] ?? 'blagajna') : '';
$dbvtab = in_array($dbvtab, ['blagajna','najmovi','izvjestaj'], true) ? $dbvtab : 'blagajna';

/* --- Blagajna (ID = $DBV_CASH_ID) --- */
$dbvCashNaziv=''; $dbvCashUloga=''; $dbvCashStanje=0.0; $dbvCashTrans=null;
if ($section === 'dubrovnik' && $dbvtab === 'blagajna') {
    $stmt = $conn->prepare("SELECT naziv, uloga FROM poslovnice WHERE id=?");
    $stmt->bind_param("i", $DBV_CASH_ID);
    $stmt->execute(); $stmt->bind_result($dbvCashNaziv, $dbvCashUloga); $stmt->fetch(); $stmt->close();

    $stmt = $conn->prepare("
        SELECT IFNULL(SUM(CASE WHEN tip='uplata' THEN iznos ELSE 0 END),0)
             - IFNULL(SUM(CASE WHEN tip='isplata' THEN iznos ELSE 0 END),0) AS stanje
        FROM transakcije WHERE poslovnica_id=?");
    $stmt->bind_param("i", $DBV_CASH_ID);
    $stmt->execute(); $stmt->bind_result($dbvCashStanje); $stmt->fetch(); $stmt->close();

    $stmt = $conn->prepare("
        SELECT id, datum, tip, opis, iznos
        FROM transakcije
        WHERE poslovnica_id = ?
        ORDER BY datum DESC, id DESC");
    $stmt->bind_param("i", $DBV_CASH_ID);
    $stmt->execute(); $dbvCashTrans = $stmt->get_result(); $stmt->close();
}

/* --- Najmovi (ID = $DBV_RENT_ID) --- */
$dbvRentNaziv=''; $dbvRentUloga=''; $dbvQ=''; $dbvPage=1; $dbvPP=50; $dbvOff=0; $dbvTotal=0; $dbvSum=0.0; $dbvRows=null;
if ($section === 'dubrovnik' && $dbvtab === 'najmovi') {
    $stmt = $conn->prepare("SELECT naziv, uloga FROM poslovnice WHERE id=?");
    $stmt->bind_param("i", $DBV_RENT_ID);
    $stmt->execute(); $stmt->bind_result($dbvRentNaziv, $dbvRentUloga); $stmt->fetch(); $stmt->close();

    $dbvQ    = trim((string)($_GET['q'] ?? ''));
    $dbvPage = max(1, (int)($_GET['page'] ?? 1));
    $dbvPP   = max(10,(int)($_GET['per_page'] ?? 50));
    $dbvOff  = ($dbvPage - 1) * $dbvPP;

    $baseW   = " poslovnica_id=? AND vrsta='najam' ";
    $tAgg    = "i"; $pAgg = [$DBV_RENT_ID];
    if ($dbvQ !== '') { $baseW .= " AND ime_prezime LIKE CONCAT('%', ?, '%') "; $tAgg.="s"; $pAgg[]=$dbvQ; }

    $sqlA = "SELECT COUNT(*) AS cnt, IFNULL(SUM(iznos),0) AS suma FROM najmovi WHERE $baseW";
    $sA = $conn->prepare($sqlA);
    $sA->bind_param($tAgg, ...$pAgg);
    $sA->execute();
    $aRes = $sA->get_result()->fetch_assoc();
    $sA->close();
    $dbvTotal = (int)($aRes['cnt'] ?? 0);
    $dbvSum   = (float)($aRes['suma'] ?? 0.0);

    $sqlL = "
      SELECT id, ime_prezime, adresar_id, grupa_vozila, tablica_vozila,
             datum_out, datum_in, nacin_placanja, iznos, napomena
      FROM najmovi
      WHERE $baseW
      ORDER BY datum_out DESC, id DESC
      LIMIT ? OFFSET ?";
    $tL = $tAgg . "ii";
    $pL = $pAgg; $pL[]=$dbvPP; $pL[]=$dbvOff;

    $sL = $conn->prepare($sqlL);
    $sL->bind_param($tL, ...$pL);
    $sL->execute();
    $dbvRows = $sL->get_result();
    $sL->close();
}

/* -------- PLAĆE ------- */
$placeRows = null;
$placeGodina = (int)($_GET['godina'] ?? date('Y'));
$placeMjesec = (int)($_GET['mjesec'] ?? date('n'));

if ($section === 'place') {
   $sql = "
    SELECT 
        d.id AS djelatnik_id,
        d.ime,
        d.poslovnica,
        d.dogovorena,
        pl.gotovina, pl.nagrada, pl.bonus, pl.osnova, pl.dodaci, pl.ukupno, pl.napomena,
        (
            SELECT ukupno FROM place pl2 
            WHERE pl2.djelatnik_id = d.id 
              AND pl2.godina = ? 
              AND pl2.mjesec = ?
            LIMIT 1
        ) AS prosli_mj
    FROM djelatnici d
    LEFT JOIN place pl 
      ON pl.djelatnik_id = d.id 
     AND pl.godina=? 
     AND pl.mjesec=?
    ORDER BY d.poslovnica, d.ime
";


    $stmt = $conn->prepare($sql);
    $prosli_god = $placeGodina;
    $prosli_mj  = $placeMjesec - 1;
    if ($prosli_mj <= 0) { $prosli_mj = 12; $prosli_god--; }
    $stmt->bind_param("iiii", $prosli_god, $prosli_mj, $placeGodina, $placeMjesec);
    $stmt->execute();
    $placeRows = $stmt->get_result();
}



?>
<!DOCTYPE html>
<html lang="hr">
<head>
  <meta charset="UTF-8">
  <title>Admin — Početna | Stanja i pregledi</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root {
      --app-bg: #f3f6fb;
      --app-card: #ffffff;
      --app-text: #172033;
      --app-muted: #6b7280;
      --app-border: #e7ebf2;
      --app-primary: #0d6efd;
      --app-primary-dark: #0a58ca;
      --app-radius: 18px;
      --app-shadow: 0 10px 32px rgba(31, 42, 68, .08);
    }

    * { box-sizing: border-box; }
    body {
      min-height: 100vh;
      margin: 0;
      font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
      color: var(--app-text);
      background:
        radial-gradient(circle at top right, rgba(13,110,253,.08), transparent 28rem),
        var(--app-bg) !important;
    }

    .app-container { max-width: 1180px; }
    .app-header {
      background: rgba(255,255,255,.88);
      border: 1px solid rgba(255,255,255,.9);
      box-shadow: var(--app-shadow);
      backdrop-filter: blur(12px);
      border-radius: var(--app-radius);
      padding: 14px 16px;
    }
    .app-brand { display:flex; align-items:center; gap:12px; }
    .app-brand-icon {
      width: 42px; height: 42px; border-radius: 13px;
      display:flex; align-items:center; justify-content:center;
      color:#fff; font-size:1.15rem;
      background: linear-gradient(135deg, var(--app-primary), #5b8def);
      box-shadow: 0 8px 18px rgba(13,110,253,.25);
    }
    .app-brand h1 { font-size: 1.05rem; font-weight: 700; margin:0; }
    .app-brand small { color:var(--app-muted); }

    .main-nav {
      padding: 6px;
      background: rgba(255,255,255,.82);
      border: 1px solid var(--app-border);
      border-radius: 16px;
      box-shadow: 0 6px 20px rgba(31,42,68,.05);
    }
    .main-nav .nav-link {
      color:#4b5563;
      border-radius: 11px;
      padding: .56rem .72rem;
      font-size:.9rem;
      font-weight:600;
      transition: all .18s ease;
    }
    .main-nav .nav-link:hover { color:var(--app-primary); background:#eef5ff; transform:translateY(-1px); }
    .main-nav .nav-link.active {
      color:#fff;
      background: linear-gradient(135deg, var(--app-primary), #447ee8);
      box-shadow: 0 7px 16px rgba(13,110,253,.22);
    }

    .bg-white.rounded, .bg-white.rounded.shadow-sm,
    .bg-white.p-4.rounded, .bg-white.p-4.mb-4.rounded {
      border: 1px solid var(--app-border);
      border-radius: var(--app-radius) !important;
      box-shadow: var(--app-shadow) !important;
    }

    h4, h5, h6 { font-weight: 700; letter-spacing: -.02em; }
    h5 { font-size: 1.05rem; }
    .text-muted { color: var(--app-muted) !important; }

    .btn { border-radius: 10px; font-weight: 600; }
    .btn-sm { border-radius: 9px; }
    .btn-primary, .btn-success, .btn-info {
      box-shadow: 0 5px 12px rgba(13,110,253,.14);
    }
    .btn-outline-secondary { border-color:#d8dee9; color:#4b5563; background:#fff; }
    .btn-outline-secondary:hover { border-color:#b9c3d4; background:#f6f8fb; color:#111827; }
    .btn-outline-danger { background:#fff; }

    .form-control, .form-select {
      border-radius: 10px;
      border-color:#dfe4ec;
      min-height: 40px;
      box-shadow:none !important;
    }
    .form-control:focus, .form-select:focus {
      border-color:#86b7fe;
      box-shadow:0 0 0 .2rem rgba(13,110,253,.10) !important;
    }

    .table-responsive {
      -webkit-overflow-scrolling: touch;
      border: 1px solid var(--app-border);
      border-radius: 14px;
      background:#fff;
    }
    .table { margin-bottom:0; }
    .table-fit { table-layout: fixed; }
    .table-fit th, .table-fit td { word-break: break-word; white-space: normal; }
    .table thead th {
      background:#f6f8fb !important;
      color:#596274;
      border-bottom:1px solid var(--app-border);
      font-size:.75rem;
      text-transform:uppercase;
      letter-spacing:.045em;
      padding:.68rem .62rem;
    }
    .table tbody td { padding:.62rem .62rem; border-color:#edf0f5; vertical-align:middle; }

    /* Kompaktnije tablice transakcija: više prostora za opis */
    .transaction-table th:nth-child(1), .transaction-table td:nth-child(1) { width: 6%; }
    .transaction-table th:nth-child(2), .transaction-table td:nth-child(2) { width: 14%; white-space: nowrap; }
    .transaction-table th:nth-child(3), .transaction-table td:nth-child(3) { width: 12%; }
    .transaction-table th:nth-child(4), .transaction-table td:nth-child(4) { width: 50%; }
    .transaction-table th:nth-child(5), .transaction-table td:nth-child(5) { width: 18%; white-space: nowrap; }

    .table-hover tbody tr:hover > * { background:#f8fbff; }
    .table-bordered > :not(caption) > * { border-width:0; }
    .table-dark > * { background:#202a3d !important; }

    .display-6 { font-weight:700; letter-spacing:-.04em; }
    /* Sažetak blagajne: kompaktniji i manje nametljiv */
    .cash-summary-card {
      max-width: 520px;
      padding: 1.05rem 1.15rem !important;
      text-align: left;
      background: linear-gradient(145deg, #ffffff, #fbfcff);
    }
    .cash-summary-main {
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:1rem;
    }
    .cash-summary-info {
      display:flex;
      align-items:center;
      gap:.8rem;
      min-width:0;
    }
    .cash-summary-icon {
      width:42px;
      height:42px;
      flex:0 0 42px;
      border-radius:12px;
      display:flex;
      align-items:center;
      justify-content:center;
      color:var(--app-primary);
      background:#edf5ff;
      font-size:1.05rem;
    }
    .cash-summary-branch {
      margin:0 0 .1rem;
      font-size:.94rem;
      color:#2f3a4d;
      font-weight:700;
    }
    .cash-summary-label {
      margin:0;
      font-size:.76rem;
      color:var(--app-muted);
    }
    .cash-balance {
      font-size:1.7rem;
      line-height:1;
      font-weight:750;
      letter-spacing:-.035em;
      white-space:nowrap;
    }
    .cash-summary-actions {
      display:flex;
      gap:.45rem;
      margin-top:.85rem;
      padding-top:.8rem;
      border-top:1px solid #edf0f5;
    }
    .cash-summary-actions .btn {
      padding:.34rem .68rem;
      font-size:.78rem;
    }
    @media (max-width: 575.98px) {
      .cash-summary-card { max-width:none; }
      .cash-summary-main { align-items:flex-start; }
      .cash-balance { font-size:1.45rem; }
    }

    .alert { border:0; border-radius:13px; box-shadow:0 5px 14px rgba(31,42,68,.05); }
    .pagination { gap:5px; margin-top:16px; }
    .page-link { border-radius:8px !important; border-color:#e1e6ee; color:#4b5563; }

    #zgModuleWrap iframe { width:100%; height:1200px; border:0; border-radius:12px; }
    .embed-frame { width:100%; border:0; min-height:1200px; }

    @media (max-width: 767.98px) {
      .app-header { padding:14px; }
      .main-nav { flex-wrap:nowrap !important; overflow-x:auto; padding:7px; }
      .main-nav .nav-item { flex:0 0 auto; }
      .main-nav .nav-link { white-space:nowrap; padding:.6rem .78rem; }
      .bg-white.p-4 { padding:1rem !important; }
      .table-fit { table-layout:auto; min-width:720px; }
      .transaction-table { min-width:680px; }
      .w-sm-100 { width:100% !important; }
    }

    @media print {
      body { background:#fff !important; }
      .app-header, .main-nav, .btn { display:none !important; }
      .bg-white.rounded { box-shadow:none !important; border:0 !important; }
    }
  </style>
</head>
<body>
  <div class="container-fluid app-container px-3 px-lg-4 py-4">

    <header class="app-header d-flex justify-content-between align-items-center mb-3">
      <div class="app-brand">
        <div class="app-brand-icon"><i class="bi bi-grid-1x2-fill"></i></div>
        <div>
          <h1>Avia administracija</h1>
          <small>Pregled poslovnica i internih evidencija</small>
        </div>
      </div>
      <a href="logout.php" class="btn btn-outline-danger btn-sm px-3">
        <i class="bi bi-box-arrow-right me-1"></i> Odjava
      </a>
    </header>

    <!-- Glavni meni -->
    <ul class="nav nav-pills main-nav flex-wrap gap-1 mb-4">
      <?php
        $menu = [
          'home'      => '<i class="bi bi-speedometer2 me-1"></i> Stanje svih poslovnica',
          'zagreb'    => '<i class="bi bi-geo-alt me-1"></i> Zagreb',
          'zadardt'   => '<i class="bi bi-building me-1"></i> ZadarDT',
          'zadarap'   => '<i class="bi bi-airplane me-1"></i> ZadarAP',
          'split'     => '<i class="bi bi-geo-alt me-1"></i> Split',
          'dubrovnik' => '<i class="bi bi-geo-alt me-1"></i> Dubrovnik',
          'sibenik'   => '<i class="bi bi-geo-alt me-1"></i> Šibenik',
          'pula'      => '<i class="bi bi-geo-alt me-1"></i> Pula',
          'odmori'    => '<i class="bi bi-calendar2-week me-1"></i> Godišnji odmori',
          'place' => '<i class="bi bi-wallet2 me-1"></i> Plaće',
        ];
        foreach ($menu as $key => $label):
      ?>
        <li class="nav-item">
          <a class="nav-link <?= $section===$key ? 'active' : '' ?>" href="?section=<?= $key ?>">
            <?= $label ?>
          </a>
        </li>
      <?php endforeach; ?>
    </ul>

    <?php if ($section === 'home'): ?>
      <!-- Stanje svih poslovnica -->
      <div class="bg-white p-4 mb-4 rounded shadow-sm">
        <h5 class="mb-3">Stanje svih poslovnica</h5>
        <div class="table-responsive">
          <table class="table table-hover table-bordered table-sm table-fit">
            <thead class="table-secondary">
              <tr>
                <th>Poslovnica</th>
                <th>Uloga</th>
                <th class="text-end">Stanje (EUR)</th>
                <th class="text-end">Najmovi (EUR)</th>
                <th class="text-end">Ugovora</th>
              </tr>
            </thead>
            <tbody>
              <?php
                $ukupno_stanje  = 0.0;
                $ukupno_najmovi = 0.0;
                $ukupno_ugovora = 0;
                if ($pregled_stanja) {
                  $pregled_stanja->data_seek(0);
                  while($ps = $pregled_stanja->fetch_assoc()):
                    $stanjeRow   = (float)$ps['stanje'];
                    $sNajmova    = (float)$ps['suma_najmova'];
                    $brUgovora   = (int)$ps['broj_ugovora'];
                    $ukupno_stanje  += $stanjeRow;
                    $ukupno_najmovi += $sNajmova;
                    $ukupno_ugovora += $brUgovora;
              ?>
                <tr>
                  <td><?= htmlspecialchars($ps['naziv']) ?></td>
                  <td><?= htmlspecialchars($ps['uloga']) ?></td>
                  <td class="text-end <?= $stanjeRow < 0 ? 'text-danger fw-bold' : '' ?>">
                    <?= number_format($stanjeRow, 2) ?>
                  </td>
                  <td class="text-end">
                    <?= number_format($sNajmova, 2) ?>
                  </td>
                  <td class="text-end">
                    <?= number_format($brUgovora, 0) ?>
                  </td>
                </tr>
              <?php endwhile; } ?>
              <tr class="table-dark fw-bold">
                <td colspan="2" class="text-end">Ukupno:</td>
                <td class="text-end <?= $ukupno_stanje < 0 ? 'text-danger' : 'text-success' ?>">
                  <?= number_format($ukupno_stanje, 2) ?> €
                </td>
                <td class="text-end">
                  <?= number_format($ukupno_najmovi, 2) ?> €
                </td>
                <td class="text-end">
                  <?= number_format($ukupno_ugovora, 0) ?>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

    <?php elseif (in_array($section, ['zagreb','split','sibenik','pula'], true)): ?>

      <?php if ($selected_id <= 0): ?>
        <div class="alert alert-warning">ID poslovnice za sekciju <strong><?= htmlspecialchars(ucfirst($section)) ?></strong> nije pronađen u bazi. Provjerite naziv u tablici <code>poslovnice</code>.</div>
      <?php else: ?>

        <?php if ($section === 'zagreb'): ?>
          <!-- ZAGREB: preklopnik + isticanje aktivnog gumba -->
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="m-0">Zagreb</h5>
            <div class="d-flex gap-2">
              <button id="btnZgBlagajna"  type="button" class="btn btn-outline-secondary" onclick="openZgModule('blagajna')">Blagajna</button>
              <button id="btnZgAfterhour" type="button" class="btn btn-outline-secondary" onclick="openZgModule('afterhour')">Afterhour</button>
              <button id="btnZgWalkin"    type="button" class="btn btn-outline-secondary" onclick="openZgModule('walkin')">Walk In</button>
            </div>
          </div>
        <?php else: ?>
          <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="m-0"><?= htmlspecialchars(ucfirst($section)) ?> — pregled blagajne</h5>
          </div>
        <?php endif; ?>

        <?php if ($section === 'zagreb'): ?>
          <!-- ZAGREB: Blagajna (bez mjeseca i bez grafa) -->
          <div id="zgBlagajna" class="d-none">
            <div class="row g-4">
              <div class="col-12 col-md-4">
                <div class="bg-white rounded shadow-sm cash-summary-card">
                  <div class="cash-summary-main">
                    <div class="cash-summary-info">
                      <div class="cash-summary-icon"><i class="bi bi-cash-stack"></i></div>
                      <div>
                        <p class="cash-summary-branch"><?= htmlspecialchars($naziv) ?></p>
                        <p class="cash-summary-label">Stanje blagajne · <?= htmlspecialchars($uloga) ?></p>
                      </div>
                    </div>
                    <div class="cash-balance <?= $stanje < 0 ? 'text-danger' : 'text-success' ?>">
                      <?= number_format((float)$stanje, 2) ?> €
                    </div>
                  </div>
                  <div class="cash-summary-actions">
                    <a href="export_csv.php?id=<?= $selected_id ?>" class="btn btn-outline-primary btn-sm"><i class="bi bi-filetype-csv me-1"></i>CSV</a>
                    <button onclick="window.print()" class="btn btn-outline-secondary btn-sm"><i class="bi bi-printer me-1"></i>Ispis</button>
                  </div>
                </div>
              </div>
              <div class="col-12 col-md-8"></div>
            </div>

            <h6 class="mt-4">Transakcije</h6>
            <div class="table-responsive">
              <table class="table table-bordered table-striped table-sm table-fit transaction-table">
                <thead class="table-light">
                  <tr><th>#</th><th>Datum</th><th>Tip</th><th>Opis</th><th class="text-end">Iznos (EUR)</th></tr>
                </thead>
                <tbody>
                <?php $rb = 1; if ($transakcije) { $transakcije->data_seek(0); while($row = $transakcije->fetch_assoc()): ?>
                  <tr class="<?= $row['tip'] === 'isplata' ? 'table-danger fw-bold' : '' ?>">
                    <td><?= $rb++ ?></td>
                    <td><?= date('d.m.Y', strtotime($row['datum'])) ?></td>
                    <td><?= htmlspecialchars($row['tip']) ?></td>
                    <td><?= htmlspecialchars($row['opis']) ?></td>
                    <td class="text-end <?= $row['tip'] === 'isplata' ? 'text-danger' : 'text-dark' ?>">
                      <?= number_format((float)$row['iznos'], 2) ?>
                    </td>
                  </tr>
                <?php endwhile; } ?>
                </tbody>
              </table>
            </div>
          </div>

          <!-- ZAGREB: ugradnja Afterhour / Walk In -->
          <div id="zgModuleWrap" class="d-none mt-3">
            <div class="bg-white rounded shadow-sm p-2">
              <div class="mb-2"><strong id="zgModuleTitle" class="ms-1"></strong></div>
              <iframe id="zgModuleFrame" src="about:blank"></iframe>
            </div>
          </div>
        <?php else: ?>
          <!-- OSTALI (Split/Šibenik/Pula): blagajna bez mjeseca i bez grafa -->
          <div class="row g-4">
            <div class="col-12 col-md-4">
              <div class="bg-white p-4 rounded shadow-sm text-center">
                <h6 class="text-muted mb-1"><?= htmlspecialchars($naziv) ?> (<?= htmlspecialchars($uloga) ?>)</h6>
                <div class="small text-muted">Stanje blagajne</div>
                <div class="display-6 <?= $stanje < 0 ? 'text-danger' : 'text-success' ?>"><?= number_format((float)$stanje, 2) ?> €</div>
                <div class="d-flex justify-content-center mt-3 gap-2">
                  <a href="export_csv.php?id=<?= $selected_id ?>" class="btn btn-outline-primary btn-sm">CSV</a>
                  <button onclick="window.print()" class="btn btn-outline-secondary btn-sm">Ispis</button>
                </div>
              </div>
            </div>
            <div class="col-12 col-md-8"></div>
          </div>

          <h6 class="mt-4">Transakcije</h6>
          <div class="table-responsive">
            <table class="table table-bordered table-striped table-sm table-fit transaction-table">
              <thead class="table-light">
                <tr><th>#</th><th>Datum</th><th>Tip</th><th>Opis</th><th class="text-end">Iznos (EUR)</th></tr>
              </thead>
              <tbody>
              <?php $rb = 1; if ($transakcije) { while($row = $transakcije->fetch_assoc()): ?>
                <tr class="<?= $row['tip'] === 'isplata' ? 'table-danger fw-bold' : '' ?>">
                  <td><?= $rb++ ?></td>
                  <td><?= date('d.m.Y', strtotime($row['datum'])) ?></td>
                  <td><?= htmlspecialchars($row['tip']) ?></td>
                  <td><?= htmlspecialchars($row['opis']) ?></td>
                  <td class="text-end <?= $row['tip'] === 'isplata' ? 'text-danger' : 'text-dark' ?>">
                    <?= number_format((float)$row['iznos'], 2) ?>
                  </td>
                </tr>
              <?php endwhile; } ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>

      <?php endif; ?>

    <?php elseif ($section === 'dubrovnik'): ?>
      <!-- DUBROVNIK: tri gumba (Blagajna / Najmovi / Izvještaj) -->
      <div class="d-flex justify-content-between align-items-center mb-3">
        <h5 class="m-0">Dubrovnik</h5>
        <div class="d-flex gap-2">
          <a href="?section=dubrovnik&dbvtab=blagajna"  class="btn <?= $dbvtab==='blagajna' ? 'btn-primary active' : 'btn-outline-secondary' ?>">Blagajna</a>
          <a href="?section=dubrovnik&dbvtab=najmovi"   class="btn <?= $dbvtab==='najmovi'  ? 'btn-primary active' : 'btn-outline-secondary' ?>">Najmovi</a>
          <a href="?section=dubrovnik&dbvtab=izvjestaj" class="btn <?= $dbvtab==='izvjestaj'? 'btn-primary active' : 'btn-outline-secondary' ?>">Izvještaj</a>
        </div>
      </div>

      <?php if ($dbvtab === 'blagajna'): ?>
        <!-- Dubrovnik — pregled blagajne (ID2) -->
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h5 class="m-0">Dubrovnik — pregled blagajne</h5>
        </div>

        <div class="row g-4">
          <div class="col-12 col-md-4">
            <div class="bg-white rounded shadow-sm cash-summary-card">
              <div class="cash-summary-main">
                <div class="cash-summary-info">
                  <div class="cash-summary-icon"><i class="bi bi-cash-stack"></i></div>
                  <div>
                    <p class="cash-summary-branch"><?= htmlspecialchars($dbvCashNaziv) ?></p>
                    <p class="cash-summary-label">Stanje blagajne · <?= htmlspecialchars($dbvCashUloga) ?></p>
                  </div>
                </div>
                <div class="cash-balance <?= $dbvCashStanje < 0 ? 'text-danger' : 'text-success' ?>">
                  <?= number_format((float)$dbvCashStanje, 2) ?> €
                </div>
              </div>
              <div class="cash-summary-actions">
                <a href="export_csv.php?id=<?= (int)$DBV_CASH_ID ?>" class="btn btn-outline-primary btn-sm"><i class="bi bi-filetype-csv me-1"></i>CSV</a>
                <button onclick="window.print()" class="btn btn-outline-secondary btn-sm"><i class="bi bi-printer me-1"></i>Ispis</button>
              </div>
            </div>
          </div>
          <div class="col-12 col-md-8"></div>
        </div>

        <h6 class="mt-4">Transakcije</h6>
        <div class="table-responsive">
          <table class="table table-bordered table-striped table-sm table-fit transaction-table">
            <thead class="table-light">
              <tr><th>#</th><th>Datum</th><th>Tip</th><th>Opis</th><th class="text-end">Iznos (EUR)</th></tr>
            </thead>
            <tbody>
              <?php
              $rb=1;
              if ($dbvCashTrans && $dbvCashTrans->num_rows>0) {
                while($row = $dbvCashTrans->fetch_assoc()):
              ?>
                <tr class="<?= $row['tip'] === 'isplata' ? 'table-danger fw-bold' : '' ?>">
                  <td><?= $rb++ ?></td>
                  <td><?= date('d.m.Y', strtotime($row['datum'])) ?></td>
                  <td><?= htmlspecialchars($row['tip']) ?></td>
                  <td><?= htmlspecialchars($row['opis']) ?></td>
                  <td class="text-end <?= $row['tip'] === 'isplata' ? 'text-danger' : 'text-dark' ?>">
                    <?= number_format((float)$row['iznos'], 2) ?>
                  </td>
                </tr>
              <?php endwhile; } else { ?>
                <tr><td colspan="5" class="text-center text-muted">Nema transakcija za ovu poslovnicu.</td></tr>
              <?php } ?>
            </tbody>
          </table>
        </div>

      <?php elseif ($dbvtab === 'najmovi'): ?>
        <!-- Dubrovnik — Najmovi (read-only, ID10) -->
        <div class="bg-white p-4 rounded shadow-sm">
          <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
            <div class="small text-muted">
              <?php
                $dbvRentNazivEsc = htmlspecialchars($dbvRentNaziv ?: 'Dubrovnik');
                $dbvRentUlogaEsc = htmlspecialchars($dbvRentUloga);
              ?>
              Poslovnica: <strong><?= $dbvRentNazivEsc ?></strong>
              <span class="text-muted">(<?= $dbvRentUlogaEsc ?>)</span>
              <?= $dbvQ !== '' ? ' &middot; Filtrirano na: “'.htmlspecialchars($dbvQ).'”' : '' ?>
            </div>
            <form method="GET" class="d-flex gap-2" autocomplete="off">
              <input type="hidden" name="section" value="dubrovnik">
              <input type="hidden" name="dbvtab" value="najmovi">
              <input type="text" name="q" class="form-control form-control-sm" placeholder="Pretraži ime i prezime" value="<?= htmlspecialchars($dbvQ) ?>">
              <button class="btn btn-sm btn-primary">Traži</button>
              <?php if ($dbvQ !== ''): ?>
                <a class="btn btn-sm btn-outline-secondary" href="?section=dubrovnik&dbvtab=najmovi">Očisti</a>
              <?php endif; ?>
            </form>
          </div>

          <div class="d-flex justify-content-between flex-wrap gap-2 mb-2">
            <div></div>
            <div class="fw-semibold">
              Ugovora: <?= number_format($dbvTotal, 0) ?> &nbsp;|&nbsp;
              Suma najmova: <?= number_format($dbvSum, 2) ?> €
            </div>
          </div>

          <div class="table-responsive">
            <table class="table table-bordered table-striped table-sm table-fit align-middle">
              <thead class="table-light">
                <tr>
                  <th>#</th>
                  <th>Ime i prezime</th>
                  <th>Adresar ID</th>
                  <th>Grupa</th>
                  <th>Tablica</th>
                  <th>Datum OUT</th>
                  <th>Datum IN</th>
                  <th class="text-end">Iznos (€)</th>
                  <th>Plaćeno</th>
                  <th>Napomena</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $rb = $dbvOff + 1;
                if ($dbvRows) {
                  while ($row = $dbvRows->fetch_assoc()):
                    $iznosFmt = number_format((float)$row['iznos'], 2);
                ?>
                  <tr>
                    <td><?= $rb++ ?></td>
                    <td><?= htmlspecialchars($row['ime_prezime']) ?></td>
                    <td><?= htmlspecialchars($row['adresar_id']) ?></td>
                    <td><?= htmlspecialchars($row['grupa_vozila']) ?></td>
                    <td><?= htmlspecialchars($row['tablica_vozila']) ?></td>
                    <td><?= htmlspecialchars($row['datum_out']) ?></td>
                    <td><?= htmlspecialchars($row['datum_in']) ?></td>
                    <td class="text-end"><?= $iznosFmt ?></td>
                    <td><?= htmlspecialchars($row['nacin_placanja']) ?></td>
                    <td><?= htmlspecialchars($row['napomena']) ?></td>
                  </tr>
                <?php
                  endwhile;
                } else {
                ?>
                  <tr><td colspan="10" class="text-center text-muted">Nema zapisa.</td></tr>
                <?php } ?>
              </tbody>
            </table>
          </div>

          <?php
            $totPages = max(1, (int)ceil($dbvTotal / $dbvPP));
            if ($totPages > 1):
              $base = '?section=dubrovnik&dbvtab=najmovi' . ($dbvQ!=='' ? '&q='.urlencode($dbvQ) : '');
              $prev = max(1, $dbvPage-1);
              $next = min($totPages, $dbvPage+1);
          ?>
          <nav aria-label="Paginacija">
            <ul class="pagination pagination-sm">
              <li class="page-item <?= $dbvPage<=1?'disabled':'' ?>"><a class="page-link" href="<?= $base.'&page='.$prev.'&per_page='.$dbvPP ?>">«</a></li>
              <?php for($p=max(1,$dbvPage-2); $p<=min($totPages,$dbvPage+2); $p++): ?>
                <li class="page-item <?= $p===$dbvPage?'active':'' ?>"><a class="page-link" href="<?= $base.'&page='.$p.'&per_page='.$dbvPP ?>"><?= $p ?></a></li>
              <?php endfor; ?>
              <li class="page-item <?= $dbvPage>=$totPages?'disabled':'' ?>"><a class="page-link" href="<?= $base.'&page='.$next.'&per_page='.$dbvPP ?>">»</a></li>
            </ul>
          </nav>
          <?php endif; ?>
        </div>

           <?php else: /* izvještaj */ ?>
        <!-- Dubrovnik — Izvještaj (ID10; isti report kao u najmovi_izvjestaj.php) -->
        <div class="bg-white p-4 rounded shadow-sm">
          <div class="d-flex align-items-end gap-2 flex-wrap mb-3">
            <div>
              <label for="dbvMj" class="form-label m-0">Mjesec:</label>
              <input type="month" id="dbvMj" class="form-control">
            </div>
            <button class="btn btn-info" onclick="dbvLoadReport()">Prikaži izvještaj</button>
          </div>

          <div id="dbvReport" class="small text-muted">Odaberite mjesec i prikažite izvještaj.</div>
        </div>

        <script>
        async function dbvLoadReport(){
          const mjesec = document.getElementById('dbvMj').value;
          const u = new URL('najmovi_izvjestaj.php', window.location.href);
          u.searchParams.set('poslovnica_id', '<?= (int)$DBV_RENT_ID ?>'); // ID 10
          if (mjesec) u.searchParams.set('mjesec', mjesec);

          const out = document.getElementById('dbvReport');
          out.innerHTML = 'Učitavanje...';

          try {
            const res = await fetch(u.toString(), { credentials: 'same-origin' });
            const ct = res.headers.get('content-type') || '';

            if (!res.ok) throw new Error('Greška ' + res.status);
            if (!ct.includes('application/json')) throw new Error('Neispravan odgovor (nije JSON).');

            const data = await res.json();

            if (data.error) {
              throw new Error(data.error);
            }

            const gotovina     = Number(data.gotovina || 0);
            const kartica      = Number(data.kartica || 0);
            const ukupno       = Number(data.ukupno || 0);
            const osnova       = Number(data.osnova_za_proviziju || 0);
            const provizija    = Number(data.provizija || 0);
            const ukupnoZaAvia = Number(data.ukupno_za_avia || 0);
            const netoUplate   = Number(data.neto_uplate || 0);
            const stanje       = Number(data.stanje || 0);

            const brojUplata   = Number(data.broj_uplata || 0);
            const brojIsplata  = Number(data.broj_isplata || 0);
            const sumaUplata   = Number(data.suma_uplata || 0);
            const sumaIsplata  = Number(data.suma_isplata || 0);

            let mjBlock = '';
            if (Array.isArray(data.provizije_po_mjesecima) && data.provizije_po_mjesecima.length) {
              mjBlock = '<h6 class="mt-3">Provizije po mjesecima</h6><ul class="mb-0">';
              data.provizije_po_mjesecima.forEach(r => {
                mjBlock += `<li><strong>${r.mjesec}:</strong> ${Number(r.osnova || 0).toFixed(2)} €</li>`;
              });
              mjBlock += '</ul>';
            } else if (Array.isArray(data.promet_po_mjesecima) && data.promet_po_mjesecima.length) {
              mjBlock = '<h6 class="mt-3">Promet po mjesecima</h6><ul class="mb-0">';
              data.promet_po_mjesecima.forEach(r => {
                mjBlock += `<li><strong>${r.mjesec}:</strong> ${Number(r.ukupno || 0).toFixed(2)} €</li>`;
              });
              mjBlock += '</ul>';
            }

            out.innerHTML = `
              <div class="row g-3">
                <div class="col-12 col-md-7">
                  <p><strong>Total gotovina (samo najam):</strong> ${gotovina.toFixed(2)} €</p>
                  <p><strong>Total kartice (samo najam):</strong> ${kartica.toFixed(2)} €</p>
                  <p><strong>Ukupno saldo (samo najam):</strong> ${ukupno.toFixed(2)} €</p>
                  <hr>
                  <p><strong>Osnova za proviziju:</strong> ${osnova.toFixed(2)} €</p>
                  <p><strong>Provizija (15%):</strong> ${provizija.toFixed(2)} €</p>
                  <p><strong>Ukupno za Avia:</strong> ${ukupnoZaAvia.toFixed(2)} €</p>
                  <p><strong>Neto uplate/isplate:</strong> ${netoUplate.toFixed(2)} €</p>
                  <p><strong>Stanje za Avia d.o.o.:</strong> ${stanje.toFixed(2)} €</p>
                  <hr>
                  <p><strong>Broj uplata:</strong> ${brojUplata}</p>
                  <p><strong>Iznos uplata:</strong> ${sumaUplata.toFixed(2)} €</p>
                  <p><strong>Broj isplata:</strong> ${brojIsplata}</p>
                  <p><strong>Iznos isplata:</strong> ${sumaIsplata.toFixed(2)} €</p>
                </div>
                <div class="col-12 col-md-5">
                  ${mjBlock || '<div class="text-muted">Nema podataka po mjesecima.</div>'}
                </div>
              </div>
            `;
          } catch (e) {
            console.error(e);
            out.innerHTML = '<span class="text-danger">' + (e.message || 'Greška pri dohvaćanju podataka.') + '</span>';
          }
        }
        </script>
      <?php endif; ?>

    <?php elseif ($section === 'zadardt' || $section === 'zadarap'): ?>
      <!-- READ-ONLY PREGLED najmova unutar admin.php (bez unosa) -->
      <div class="bg-white p-4 rounded shadow-sm">
        <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
          <h5 class="m-0">
            <?= $section==='zadardt' ? 'Zadar Grad' : 'Zadar Airport' ?>
          </h5>

          <form method="GET" class="d-flex gap-2" autocomplete="off">
            <input type="hidden" name="section" value="<?= htmlspecialchars($section) ?>">
            <input type="text" name="q" class="form-control form-control-sm" placeholder="Pretraži ime i prezime" value="<?= htmlspecialchars($q) ?>">
            <button class="btn btn-sm btn-primary">Traži</button>
            <?php if ($q !== ''): ?>
              <a class="btn btn-sm btn-outline-secondary" href="?section=<?= htmlspecialchars($section) ?>">Očisti</a>
            <?php endif; ?>
          </form>
        </div>

        <div class="d-flex justify-content-between flex-wrap gap-2 mb-2">
          <div class="small text-muted">
            Poslovnica: <strong><?= htmlspecialchars($listNaziv ?: ($section==='zadardt'?'Zadar Grad':'Zadar Airport')) ?></strong>
            <span class="text-muted">(<?= htmlspecialchars($listUloga) ?>)</span>
            <?= $q !== '' ? ' &middot; Filtrirano na: “'.htmlspecialchars($q).'”' : '' ?>
          </div>
          <div class="fw-semibold">
            Ugovora: <?= number_format($listTotal, 0) ?> &nbsp;|&nbsp;
            Suma najmova: <?= number_format($listSum, 2) ?> €
          </div>
        </div>

        <div class="table-responsive">
          <table class="table table-bordered table-striped table-sm table-fit align-middle">
            <thead class="table-light">
              <tr>
                <th>#</th>
                <th>Ime i prezime</th>
                <th>Adresar ID</th>
                <th>Grupa</th>
                <th>Tablica</th>
                <th>Datum OUT</th>
                <th>Datum IN</th>
                <th class="text-end">Iznos (€)</th>
                <th>Plaćeno</th>
                <th>Napomena</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $rb = $offset + 1;
              if ($listRows) {
                while ($row = $listRows->fetch_assoc()):
                  $iznosFmt = number_format((float)$row['iznos'], 2);
              ?>
                <tr>
                  <td><?= $rb++ ?></td>
                  <td><?= htmlspecialchars($row['ime_prezime']) ?></td>
                  <td><?= htmlspecialchars($row['adresar_id']) ?></td>
                  <td><?= htmlspecialchars($row['grupa_vozila']) ?></td>
                  <td><?= htmlspecialchars($row['tablica_vozila']) ?></td>
                  <td><?= htmlspecialchars($row['datum_out']) ?></td>
                  <td><?= htmlspecialchars($row['datum_in']) ?></td>
                  <td class="text-end"><?= $iznosFmt ?></td>
                  <td><?= htmlspecialchars($row['nacin_placanja']) ?></td>
                  <td><?= htmlspecialchars($row['napomena']) ?></td>
                </tr>
              <?php
                endwhile;
              } else {
              ?>
                <tr><td colspan="10" class="text-center text-muted">Nema zapisa.</td></tr>
              <?php } ?>
            </tbody>
          </table>
        </div>

        <?php
          $total_pages = max(1, (int)ceil($listTotal / $per_page));
          if ($total_pages > 1):
        ?>
        <nav aria-label="Paginacija">
          <ul class="pagination pagination-sm">
            <?php
              $base = '?section='.$section . ($q!=='' ? '&q='.urlencode($q) : '');
              $prev = max(1, $page-1);
              $next = min($total_pages, $page+1);
            ?>
            <li class="page-item <?= $page<=1?'disabled':'' ?>"><a class="page-link" href="<?= $base.'&page='.$prev.'&per_page='.$per_page ?>">«</a></li>
            <?php for($p=max(1,$page-2); $p<=min($total_pages,$page+2); $p++): ?>
              <li class="page-item <?= $p===$page?'active':'' ?>"><a class="page-link" href="<?= $base.'&page='.$p.'&per_page='.$per_page ?>"><?= $p ?></a></li>
            <?php endfor; ?>
            <li class="page-item <?= $page>=$total_pages?'disabled':'' ?>"><a class="page-link" href="<?= $base.'&page='.$next.'&per_page='.$per_page ?>">»</a></li>
          </ul>
        </nav>
        <?php endif; ?>
      </div>
      
      
      
    <?php elseif ($section === 'place'): ?>
  <div class="bg-white p-4 rounded shadow-sm">
    <h5 class="mb-3">Plaće</h5>

    <!-- dva gumba za izbor moda -->
    <div class="mb-3">
      <a href="?section=place&mode=unos" class="btn btn-sm <?= ($_GET['mode'] ?? 'unos')==='unos' ? 'btn-primary' : 'btn-outline-secondary' ?>">Unos plaća</a>
      <a href="?section=place&mode=izvjestaj" class="btn btn-sm <?= ($_GET['mode'] ?? 'unos')==='izvjestaj' ? 'btn-primary' : 'btn-outline-secondary' ?>">Izvještaj</a>
    </div>

    <?php
    $mode = $_GET['mode'] ?? 'unos';

    /* ==========================
       MODE: UNOS PLAĆA
    ========================== */
    if ($mode === 'unos'):
        $placeGodina = (int)($_GET['godina'] ?? date('Y'));
        $placeMjesec = (int)($_GET['mjesec'] ?? date('n'));

        $sql = "
            SELECT 
                d.id AS djelatnik_id,
                d.ime,
                d.poslovnica,
                d.dogovorena,
                pl.gotovina, pl.nagrada, pl.bonus, pl.osnova, pl.dodaci, pl.ukupno, pl.napomena,
                (
                    SELECT ukupno FROM place pl2
                    WHERE pl2.djelatnik_id = d.id
                      AND pl2.godina = ?
                      AND pl2.mjesec = ?
                    LIMIT 1
                ) AS prosli_mj
            FROM djelatnici d
            LEFT JOIN place pl 
              ON pl.djelatnik_id = d.id 
             AND pl.godina=? 
             AND pl.mjesec=?
            ORDER BY d.poslovnica, d.ime
        ";
        $stmt = $conn->prepare($sql);
        $prosli_god = $placeGodina;
        $prosli_mj  = $placeMjesec - 1;
        if ($prosli_mj <= 0) { $prosli_mj = 12; $prosli_god--; }
        $stmt->bind_param("iiii", $prosli_god, $prosli_mj, $placeGodina, $placeMjesec);
        $stmt->execute();
        $placeRows = $stmt->get_result();
        ?>

        <h6 class="mb-3">
          Unos plaća — <?= (new DateTime("$placeGodina-$placeMjesec-01"))->format('F Y') ?>
        </h6>

        <!-- Filter forma -->
        <form method="get" class="row g-2 mb-3">
          <input type="hidden" name="section" value="place">
          <input type="hidden" name="mode" value="unos">
          <div class="col-auto">
            <select name="godina" class="form-select">
              <?php for($y = date('Y')-1; $y <= date('Y')+1; $y++): ?>
                <option value="<?= $y ?>" <?= $y==$placeGodina ? 'selected' : '' ?>><?= $y ?></option>
              <?php endfor; ?>
            </select>
          </div>
          <div class="col-auto">
            <select name="mjesec" class="form-select">
              <?php for($m=1; $m<=12; $m++): ?>
                <option value="<?= $m ?>" <?= $m==$placeMjesec ? 'selected' : '' ?>>
                  <?= (new DateTime("2025-$m-01"))->format('F') ?>
                </option>
              <?php endfor; ?>
            </select>
          </div>
          <div class="col-auto">
            <button class="btn btn-primary">Prikaži</button>
          </div>
        </form>

        <!-- Forma za spremanje -->
        <form method="post" action="place_save.php">
          <input type="hidden" name="godina" value="<?= $placeGodina ?>">
          <input type="hidden" name="mjesec" value="<?= $placeMjesec ?>">

          <div class="table-responsive">
            <table class="table table-bordered table-sm align-middle">
              <thead class="table-secondary">
                <tr>
                  <th>Poslovnica</th>
                  <th>Djelatnik</th>
                  <th>Dogovorena (€)</th>
                  <th>Gotovina</th>
                  <th>Nagrada</th>
                  <th>Bonus</th>
                  <th>Osnova</th>
                  <th>Dodaci</th>
                  <th>Ukupno</th>
                  <th>Prošli mj.</th>
                  <th>Δ</th>
                  <th>Napomena</th>
                </tr>
              </thead>
              <tbody>
                <?php if ($placeRows && $placeRows->num_rows > 0): ?>
                  <?php while($r = $placeRows->fetch_assoc()): 
                    $ukupno = (float)($r['ukupno'] ?? 0);
                    $prosli = (float)($r['prosli_mj'] ?? 0);
                    $delta  = $ukupno - $prosli;
                  ?>
                    <tr>
                      <td><?= htmlspecialchars($r['poslovnica']) ?></td>
                      <td><?= htmlspecialchars($r['ime']) ?></td>
                      <td><input type="number" step="0.01" name="dogovorena[<?= $r['djelatnik_id'] ?>]" value="<?= $r['dogovorena'] ?? '' ?>" class="form-control form-control-sm" style="max-width:90px"></td>
                      <td><input type="number" step="0.01" name="gotovina[<?= $r['djelatnik_id'] ?>]" value="<?= $r['gotovina'] ?? '' ?>" class="form-control form-control-sm" style="max-width:90px"></td>
                      <td><input type="number" step="0.01" name="nagrada[<?= $r['djelatnik_id'] ?>]" value="<?= $r['nagrada'] ?? '' ?>" class="form-control form-control-sm" style="max-width:90px"></td>
                      <td><input type="number" step="0.01" name="bonus[<?= $r['djelatnik_id'] ?>]" value="<?= $r['bonus'] ?? '' ?>" class="form-control form-control-sm" style="max-width:90px"></td>
                      <td><input type="number" step="0.01" name="osnova[<?= $r['djelatnik_id'] ?>]" value="<?= $r['osnova'] ?? '' ?>" class="form-control form-control-sm" style="max-width:90px"></td>
                      <td><input type="number" step="0.01" name="dodaci[<?= $r['djelatnik_id'] ?>]" value="<?= $r['dodaci'] ?? '' ?>" class="form-control form-control-sm" style="max-width:90px"></td>
                      <td><?= number_format($ukupno, 2) ?></td>
                      <td><?= $prosli ? number_format($prosli, 2) : '—' ?></td>
                      <td class="<?= $delta>0 ? 'text-success' : ($delta<0 ? 'text-danger' : '') ?>">
                        <?= $delta==0 ? '—' : number_format($delta, 2) ?>
                      </td>
                      <td><input type="text" name="napomena[<?= $r['djelatnik_id'] ?>]" value="<?= htmlspecialchars($r['napomena'] ?? '') ?>" class="form-control form-control-sm"></td>
                    </tr>
                  <?php endwhile; ?>
                <?php else: ?>
                  <tr><td colspan="12" class="text-center text-muted">Nema podataka za odabrani mjesec.</td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <button class="btn btn-success mt-2">Spremi plaće</button>
        </form>

    <?php 
    /* ==========================
       MODE: IZVJEŠTAJ
    ========================== */
    elseif ($mode === 'izvjestaj'):
        $pregledGodina = (int)($_GET['godina'] ?? date('Y'));

        $sql = "
            SELECT 
                d.id AS djelatnik_id,
                d.ime,
                d.dogovorena,
                pl.mjesec,
                COALESCE(pl.ukupno,0) AS ukupno
            FROM djelatnici d
            LEFT JOIN place pl 
              ON pl.djelatnik_id = d.id 
             AND pl.godina = ?
            ORDER BY d.ime, pl.mjesec
        ";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $pregledGodina);
        $stmt->execute();
        $pregledRows = $stmt->get_result();
        ?>

        <h6 class="mb-3">Izvještaj plaća — <?= $pregledGodina ?></h6>

        <!-- Filter po godini -->
        <form method="get" class="mb-3">
          <input type="hidden" name="section" value="place">
          <input type="hidden" name="mode" value="izvjestaj">
          <select name="godina" class="form-select w-auto d-inline">
            <?php for($y=date('Y')-2; $y<=date('Y')+1; $y++): ?>
              <option value="<?= $y ?>" <?= $y==$pregledGodina ? 'selected':'' ?>><?= $y ?></option>
            <?php endfor; ?>
          </select>
          <button class="btn btn-primary">Prikaži</button>
        </form>

        <div class="table-responsive">
          <table class="table table-bordered table-sm align-middle text-end">
            <thead class="table-secondary">
              <tr>
                <th class="text-start">Djelatnik</th>
                
                <?php
$mjeseci = ['Sij','Velj','Ožu','Tra','Svi','Lip','Srp','Kol','Ruj','Lis','Stu','Pro'];
foreach ($mjeseci as $mj):
?>
  <th><?= $mj ?></th>
<?php endforeach; ?>

                <th>Ukupno</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $podaci = [];
              if ($pregledRows) {
                  while($r=$pregledRows->fetch_assoc()){
                      $id = $r['djelatnik_id'];
                      if (!isset($podaci[$id])) {
                          $podaci[$id] = [
                              'ime'=>$r['ime'],
                              'mjeseci'=>array_fill(1,12,0)
                          ];
                      }
                      if ($r['mjesec']) {
                          $podaci[$id]['mjeseci'][(int)$r['mjesec']] = (float)$r['ukupno'];
                      }
                  }
                  foreach($podaci as $d){
                      $suma=array_sum($d['mjeseci']);
                      echo "<tr>";
                      echo "<td class='text-start'>".htmlspecialchars($d['ime'])."</td>";
                      
                     $mjeseci = ['Sij','Velj','Ožu','Tra','Svi','Lip','Srp','Kol','Ruj','Lis','Stu','Pro'];
for($m=1;$m<=12;$m++){
    $iznos = $d['mjeseci'][$m];
    $prev  = $m > 1 ? $d['mjeseci'][$m-1] : null;

    $strelica = '';
    if ($prev !== null && $prev > 0 && $iznos > 0) {
        if ($iznos > $prev) {
            $strelica = ' <span style="color:green;">&#9650;</span>'; // ▲ gore
        } elseif ($iznos < $prev) {
            $strelica = ' <span style="color:red;">&#9660;</span>';  // ▼ dolje
        }
    }

    echo "<td>".($iznos ? number_format($iznos,2).$strelica : '—')."</td>";
}


                      echo "<td><strong>".number_format($suma,2)."</strong></td>";
                      echo "</tr>";
                  }
              } else {
                  echo "<tr><td colspan='15' class='text-center text-muted'>Nema podataka.</td></tr>";
              }
              ?>
            </tbody>
          </table>
        </div>

    <?php endif; ?>
  </div>




      
      
      
      
   
   <?php elseif ($section === 'odmori'): ?>
  <!-- Godišnji odmori — inline na admin.php (bez iFrame) -->
  <div class="bg-white p-4 rounded shadow-sm">

    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
      <h5 class="m-0">Godišnji odmori djelatnika</h5>
      <div class="d-flex gap-2">
        <button id="odmSummaryBtn" class="btn btn-success btn-sm">Pokaži sve (status)</button>
        <button id="odmExportBtn" class="btn btn-primary btn-sm">Izvezi PDF</button>
      </div>
    </div>

    <div class="mb-3">
      <input type="text" id="odmSearch" class="form-control" placeholder="Pretraži djelatnika...">
    </div>

    <div class="border rounded p-3 mb-3">
      <h6 class="mb-2">Dodaj djelatnika</h6>
      <div class="row g-2">
        <div class="col-md-6 col-lg-5">
          <input type="text" id="odmIme" class="form-control" placeholder="Ime djelatnika">
        </div>
        <div class="col-md-4 col-lg-3">
          <input type="number" id="odmUkupno" class="form-control" placeholder="Ukupno dana godišnjeg">
        </div>
        <div class="col-md-2 col-lg-2">
          <button id="odmAddBtn" class="btn btn-primary w-100">Dodaj</button>
        </div>
      </div>
    </div>

    <div id="odmDjelatnici"></div>

  </div>

  <!-- PDF biblioteke -->
 <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>

<script>
// ===============================================
// GODIŠNJI ODMORI – kompletan JS (puni kod)
// ===============================================

// API putanja
const OD_API = 'godisnji/api.php';

// -------------------- PRAZNICI --------------------
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}-${String(month).padStart(2,'0')}-${String(day).padStart(2,'0')}`;
}
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 `${dt.getFullYear()}-${String(dt.getMonth()+1).padStart(2,'0')}-${String(dt.getDate()).padStart(2,'0')}`;
}
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`, // Dan sjećanja
    `${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=+odYMD.slice(0,4), y2=+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;
}

// -------------------- DATUM FUNKCIJE --------------------
function toYMD(str){
  if(!str) return '';
  if(/^\d{4}-\d{2}-\d{2}$/.test(str)) return str;
  const m=str.match(/^(\d{2})[\/.\-](\d{2})[\/.\-](\d{4})/);
  if(m){ const [,dd,mm,yyyy]=m; return `${yyyy}-${mm}-${dd}`; }
  const t=new Date(str);
  return isNaN(t)?str:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,'0')}-${String(t.getDate()).padStart(2,'0')}`;
}
function newLocalDateFromAny(str){
  const [y,m,d]=toYMD(str).split('-').map(Number);
  return new Date(y,(m||1)-1,d||1);
}
function ymdFromDate(d){
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

// -------------------- RAČUNANJE RADNIH DANA --------------------
function izracunajRadneDane(od, doDat){
  const odY=toYMD(od), doY=toYMD(doDat);
  if(!odY||!doY) return 0;
  const praznici=holidaysForRange(odY, doY);
  let s=newLocalDateFromAny(odY), e=newLocalDateFromAny(doY);
  if(isNaN(s)||isNaN(e)||s>e) return 0;
  let cnt=0;
  while(s<=e){
    const isSunday = s.getDay()===0; // nedjelja
    const isHoliday = praznici.has(ymdFromDate(s));
    if(!isSunday && !isHoliday) cnt++; // subota se računa
    s.setDate(s.getDate()+1);
  }
  return cnt;
}

// -------------------- GLOBALNE VAR --------------------
let odm_djelatnici = [];

// -------------------- API FUNKCIJE --------------------
async function odm_ucitaj(){
  const res = await fetch(OD_API, { credentials: 'same-origin' });
  if(!res.ok){ document.getElementById('odmDjelatnici').innerHTML='<div class="alert alert-danger">Greška pri dohvaćanju podataka.</div>'; return; }
  odm_djelatnici = await res.json();
  odm_prikazi();
}

function odm_prikazi(lista=odm_djelatnici){
  const kont=document.getElementById('odmDjelatnici');
  kont.innerHTML='';
  if(!Array.isArray(lista)||!lista.length){ kont.innerHTML='<div class="text-muted">Nema djelatnika.</div>'; return; }

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

    const card=document.createElement('div');
    card.className='border rounded p-3 mb-3';
    card.innerHTML=`
      <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
        <h6 class="m-0 ${exhausted}">${escapeHtml(d.ime)}</h6>
        <div class="small text-muted">
          Ukupno: <strong>${ukupno}</strong> | Iskorišteno: <strong>${isk}</strong> | Preostalo:
          <strong class="${exhausted}">${pre}</strong>
        </div>
      </div>
      <div class="row g-2 mb-2">
        <div class="col-6 col-md-3"><input type="date" id="odm-od-${d.id}" class="form-control"></div>
        <div class="col-6 col-md-3"><input type="date" id="odm-do-${d.id}" class="form-control"></div>
        <div class="col-12 col-md-2"><button class="btn btn-outline-primary w-100" onclick="odm_dodajGodisnji(${d.id})">Dodaj</button></div>
      </div>
      <div id="odm-lista-${d.id}"></div>
    `;
    kont.appendChild(card);
    odm_prikaziUnose(d);
  });
}

function odm_prikaziUnose(d){
  const el=document.getElementById(`odm-lista-${d.id}`); el.innerHTML='';
  (d.godisnji||[]).forEach(g=>{
    const brojDana=izracunajRadneDane(g.datum_od,g.datum_do);
    const row=document.createElement('div');
    row.className='d-flex flex-wrap align-items-center gap-2 mb-2';
    row.innerHTML=`
      <input type="date" value="${toYMD(g.datum_od)}" id="odm-edit-od-${g.id}" class="form-control" style="max-width:160px;">
      <input type="date" value="${toYMD(g.datum_do)}" id="odm-edit-do-${g.id}" class="form-control" style="max-width:160px;">
      <span class="small text-muted">(${brojDana} dana)</span>
      <button class="btn btn-sm btn-outline-success" onclick="odm_spremiGodisnji(${g.id})">Spremi</button>
      <button class="btn btn-sm btn-outline-danger" onclick="odm_obrisiGodisnji(${g.id})">Obriši</button>
    `;
    el.appendChild(row);
  });
}

async function odm_dodajDjelatnika(){
  const ime=(document.getElementById('odmIme').value||'').trim();
  const ukupno=parseInt(document.getElementById('odmUkupno').value,10);
  if(!ime||isNaN(ukupno)){ alert('Unesi ime i ukupan broj dana!'); return; }
  await fetch(OD_API,{method:'POST',body:JSON.stringify({type:'djelatnik',ime,ukupno})});
  document.getElementById('odmIme').value=''; document.getElementById('odmUkupno').value='';
  odm_ucitaj();
}
async function odm_dodajGodisnji(id){
  const od=document.getElementById(`odm-od-${id}`).value;
  const doDat=document.getElementById(`odm-do-${id}`).value;
  if(!od||!doDat){ alert('Unesi datume!'); return; }
  await fetch(OD_API,{method:'POST',body:JSON.stringify({type:'godisnji',djelatnik_id:id,datum_od:od,datum_do:doDat})});
  odm_ucitaj();
}
async function odm_spremiGodisnji(id){
  const od=document.getElementById(`odm-edit-od-${id}`).value;
  const doDat=document.getElementById(`odm-edit-do-${id}`).value;
  if(!od||!doDat){ alert('Unesi datume!'); return; }
  await fetch(OD_API,{method:'PUT',body:JSON.stringify({id,datum_od:od,datum_do:doDat})});
  odm_ucitaj();
}
async function odm_obrisiGodisnji(id) {
  if (!Number.isInteger(id) || id <= 0) {
    alert('Nevažeći ID za brisanje: ' + id);
    return;
  }
  if (!confirm('Brisati ovaj unos?')) return;

  console.log('[OBRISI] OD_API:', OD_API, 'ID:', id);

  // Helper za čitanje odgovora
  const readJson = async (res) => {
    const text = await res.text();
    let json = null;
    try { json = JSON.parse(text); } catch(e) {}
    return { status: res.status, ok: res.ok, text, json };
  };

  // 1) POST (preporučeno)
  try {
    const r1 = await fetch(OD_API, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify({ type: 'delete_godisnji', id })
    });
    const d1 = await readJson(r1);
    console.log('[DELETE-POST] status:', d1.status, 'body:', d1.text);
    if (d1.json && d1.json.success) { await odm_ucitaj(); return; }
  } catch (e) {
    console.warn('[DELETE-POST] exception:', e);
  }

  // 2) DELETE (ako hosting dozvoli)
  try {
    const r2 = await fetch(`${OD_API}?id=${encodeURIComponent(id)}`, {
      method: 'DELETE',
      credentials: 'same-origin'
    });
    const d2 = await readJson(r2);
    console.log('[DELETE-HTTP] status:', d2.status, 'body:', d2.text);
    if (d2.json && d2.json.success) { await odm_ucitaj(); return; }
  } catch (e) {
    console.warn('[DELETE-HTTP] exception:', e);
  }

  // 3) GET fallback (najkonzervativnije)
  try {
    const r3 = await fetch(`${OD_API}?action=delete&id=${encodeURIComponent(id)}`, {
      method: 'GET',
      credentials: 'same-origin'
    });
    const d3 = await readJson(r3);
    console.log('[DELETE-GET] status:', d3.status, 'body:', d3.text);
    if (d3.json && d3.json.success) { await odm_ucitaj(); return; }
  } catch (e) {
    console.warn('[DELETE-GET] exception:', e);
  }

  alert('Brisanje nije uspjelo. Pogledaj Console/Network logove (točno piše što je došlo natrag).');
}



// -------------------- PDF & FILTAR --------------------
function odm_generirajListu(){
  let txt="Ime | Ukupno | Iskorišteno | Preostalo\n\n";
  (odm_djelatnici||[]).forEach(d=>{
    const isk=(d.godisnji||[]).reduce((s,g)=>s+izracunajRadneDane(g.datum_od,g.datum_do),0);
    const ukupno=parseInt(d.ukupno,10)||0;
    const pre=ukupno-isk;
    txt+=`${d.ime} | ${ukupno} | ${isk} | ${pre}\n`;
  });
  alert(txt);
}
function odm_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=(odm_djelatnici||[]).map(d=>{
    const isk=(d.godisnji||[]).reduce((s,g)=>s+izracunajRadneDane(g.datum_od,g.datum_do),0);
    const ukupno=parseInt(d.ukupno,10)||0;
    const pre=ukupno-isk;
    return [d.ime,String(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 odm_filtriraj(){
  const q=(document.getElementById('odmSearch').value||'').toLowerCase();
  if(!q){ odm_prikazi(); return; }
  odm_prikazi((odm_djelatnici||[]).filter(d=>(d.ime||'').toLowerCase().includes(q)));
}

// -------------------- HELPERI --------------------
function escapeHtml(s){return (s??'').replace(/[&<>"']/g,m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));}

// -------------------- INIT --------------------
document.getElementById('odmAddBtn').addEventListener('click',odm_dodajDjelatnika);
document.getElementById('odmSearch').addEventListener('input',odm_filtriraj);
document.getElementById('odmSummaryBtn').addEventListener('click',odm_generirajListu);
document.getElementById('odmExportBtn').addEventListener('click',odm_exportPDF);
odm_ucitaj();

</script>

  
<?php else: ?>

      <div class="alert alert-info">Odaberite stavku iz menija iznad.</div>
    <?php endif; ?>

  </div><!-- /.container -->

<script>
// --- Zagreb embedded modules (Blagajna & Afterhour & Walk In) + isticanje aktivnog gumba ---
(function(){
  const saved = sessionStorage.getItem('zgModule') || 'blagajna';
  if (new URLSearchParams(location.search).get('section') === 'zagreb') {
    openZgModule(saved);
  }
})();

function setActiveZgButton(kind) {
  const btns = {
    blagajna:  document.getElementById('btnZgBlagajna'),
    afterhour: document.getElementById('btnZgAfterhour'),
    walkin:    document.getElementById('btnZgWalkin'),
  };
  Object.values(btns).forEach(btn => {
    if (!btn) return;
    btn.classList.remove('btn-primary', 'active');
    if (!btn.classList.contains('btn-outline-secondary')) btn.classList.add('btn-outline-secondary');
  });
  const active = btns[kind];
  if (active) {
    active.classList.remove('btn-outline-secondary');
    active.classList.add('btn-primary', 'active');
  }
}

function openZgModule(kind) {
  const blagajna = document.getElementById('zgBlagajna');
  const wrap  = document.getElementById('zgModuleWrap');
  const frame = document.getElementById('zgModuleFrame');
  const title = document.getElementById('zgModuleTitle');

  if (blagajna) blagajna.classList.add('d-none');
  if (wrap) wrap.classList.add('d-none');

  setActiveZgButton(kind);

  const ZG_ID = <?= (int)($branchId['zagreb'] ?? 0) ?>;

  if (kind === 'blagajna') {
    if (blagajna) blagajna.classList.remove('d-none');
    sessionStorage.setItem('zgModule', kind);
    if (title) title.textContent = '';
    if (frame) frame.src = 'about:blank';
    return;
  }

  let url='', label='';
  if (kind === 'afterhour') {
    label = 'Afterhour — Zagreb';
    url   = 'afterhour.php' + (ZG_ID ? ('?poslovnica=' + ZG_ID + '&embed=1') : '?embed=1');
  } else if (kind === 'walkin') {
    label = 'Walk In — Zagreb';
    url   = 'walkin.php' + (ZG_ID ? ('?poslovnica=' + ZG_ID + '&embed=1') : '?embed=1');
  }

  if (url) {
    if (title) title.textContent = label;
    if (frame) frame.src = url;
    if (wrap) wrap.classList.remove('d-none');
    sessionStorage.setItem('zgModule', kind);
  }
}
</script>
</body>
</html>