<?php
session_start();

if (!isset($_SESSION['poslovnica_id'])) {
    exit("Nedostaje poslovnica u sesiji.");
}
$SESSION_POSL_ID = (int)$_SESSION['poslovnica_id'];
$SESSION_ULOGA = (string)($_SESSION['uloga'] ?? '');

/*
 * Zadar i Zadar AP mogu se prebacivati bez ponovne prijave.
 * Pretpostavljeni ID-evi prema postojećoj konfiguraciji:
 *   11 = Zadar
 *   12 = Zadar AP
 * Ne mijenjamo osnovni poslovnica_id korisnika u sesiji, nego samo aktivnu
 * poslovnicu za modul Najmovi.
 */
$ZADAR_BRANCH_IDS = [11, 12];
$CAN_SWITCH_ZADAR = in_array($SESSION_POSL_ID, $ZADAR_BRANCH_IDS, true)
    && $SESSION_ULOGA !== 'admin';

if ($CAN_SWITCH_ZADAR) {
    $switchId = isset($_GET['switch_poslovnica']) ? (int)$_GET['switch_poslovnica'] : 0;
    if (in_array($switchId, $ZADAR_BRANCH_IDS, true)) {
        $_SESSION['aktivna_najmovi_poslovnica'] = $switchId;

        // Ukloni parametar za prebacivanje iz URL-a nakon spremanja u sesiju.
        $redirectParams = $_GET;
        unset($redirectParams['switch_poslovnica'], $redirectParams['poslovnica_id'], $redirectParams['search'], $redirectParams['page']);
        $redirectParams['poslovnica_id'] = $switchId;
        $redirectUrl = 'najmovi.php';
        if ($redirectParams) $redirectUrl .= '?' . http_build_query($redirectParams);
        header('Location: ' . $redirectUrl);
        exit();
    }

    $activeZadarId = (int)($_SESSION['aktivna_najmovi_poslovnica'] ?? $SESSION_POSL_ID);
    if (!in_array($activeZadarId, $ZADAR_BRANCH_IDS, true)) {
        $activeZadarId = $SESSION_POSL_ID;
    }
    $_SESSION['aktivna_najmovi_poslovnica'] = $activeZadarId;
} else {
    unset($_SESSION['aktivna_najmovi_poslovnica']);
    $activeZadarId = 0;
}

// Najmove mogu koristiti admin, posebna poslovnica Najmovi i redovne poslovnice.
$RENT_BRANCH_IDS = [2, 3, 4, 5, 6, 11, 12];
if (!($SESSION_ULOGA === 'admin' || strncmp($SESSION_ULOGA, 'najmovi', 7) === 0 || in_array($SESSION_POSL_ID, $RENT_BRANCH_IDS, true))) {
    exit("Pristup nije dozvoljen.");
}

$EMBED = isset($_GET['embed']) && $_GET['embed'] === '1';
$READONLY = ($SESSION_ULOGA === 'admin' && isset($_GET['readonly']) && $_GET['readonly'] === '1');

// Administrator može otvoriti Najmove za određenu poslovnicu, npr.
// najmovi.php?poslovnica_id=10 za Dubrovnik.
// Ostali korisnici uvijek ostaju zaključani na svoju poslovnicu iz sesije.
$requestedPoslId = (int)($_GET['poslovnica_id'] ?? $_POST['poslovnica_id'] ?? 0);
if ($SESSION_ULOGA === 'admin' && $requestedPoslId > 0) {
    $POSL_ID = $requestedPoslId;
} elseif ($CAN_SWITCH_ZADAR) {
    $POSL_ID = $activeZadarId;
} else {
    $POSL_ID = $SESSION_POSL_ID;
}

$ACTIVE_BRANCH_LABEL = match ($POSL_ID) {
    11 => 'Zadar',
    12 => 'Zadar AP',
    default => (string)($_SESSION['naziv'] ?? 'Poslovnica')
};

/** Poslovnice s ograničenjima (isto pravilo kao za ID 11) */
$LIMITED_IDS = [2, 3, 4, 5, 6, 11, 12];
$IS_LIMITED = in_array($POSL_ID, $LIMITED_IDS, true);

// GET search parametar (pretraga po imenu i prezimenu)
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

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

// Evidencija naknadnih izmjena zapisa.
// Tablica se automatski kreira pri prvom pokretanju ove verzije.
$conn->query("CREATE TABLE IF NOT EXISTS najmovi_promjene (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    najam_id INT NOT NULL,
    poslovnica_id INT NOT NULL,
    korisnik_id INT NULL,
    korisnik_naziv VARCHAR(190) NOT NULL DEFAULT '',
    promjene_json LONGTEXT NOT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_najam_id (najam_id),
    INDEX idx_poslovnica_id (poslovnica_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

function audit_value($value): string {
    if ($value === null || $value === '') return '—';
    return (string)$value;
}



/**
 * Sinkronizira gotovinski najam s blagajnom poslovnice.
 * Poslovnica Najmovi (ID 10) namjerno se preskače.
 */
function sync_cash_rental(mysqli $conn, int $najamId, int $poslovnicaId, string $vrsta, string $placanje, float $iznos, string $ime, string $tablica): void {
    if ($poslovnicaId === 10) return;

    $marker = '[NAJAM #' . $najamId . ']';
    $stmtFind = $conn->prepare("SELECT id FROM transakcije WHERE poslovnica_id=? AND opis LIKE CONCAT(?, '%') ORDER BY id DESC LIMIT 1");
    $stmtFind->bind_param('is', $poslovnicaId, $marker);
    $stmtFind->execute();
    $existing = $stmtFind->get_result()->fetch_assoc();
    $stmtFind->close();

    $shouldExist = ($vrsta === 'najam' && $placanje === 'gotovina' && $iznos > 0);
    if (!$shouldExist) {
        if ($existing) {
            $id = (int)$existing['id'];
            $stmtDel = $conn->prepare("DELETE FROM transakcije WHERE id=? AND poslovnica_id=?");
            $stmtDel->bind_param('ii', $id, $poslovnicaId);
            $stmtDel->execute();
            $stmtDel->close();
        }
        return;
    }

    $opis = $marker . ' Gotovinski najam - ' . trim($ime);
    if (trim($tablica) !== '') $opis .= ' - ' . trim($tablica);

    if ($existing) {
        $id = (int)$existing['id'];
        $stmtUp = $conn->prepare("UPDATE transakcije SET tip='uplata', opis=?, iznos=? WHERE id=? AND poslovnica_id=?");
        $stmtUp->bind_param('sdii', $opis, $iznos, $id, $poslovnicaId);
        $stmtUp->execute();
        $stmtUp->close();
    } else {
        $stmtIn = $conn->prepare("INSERT INTO transakcije (poslovnica_id, tip, opis, iznos) VALUES (?, 'uplata', ?, ?)");
        $stmtIn->bind_param('isd', $poslovnicaId, $opis, $iznos);
        $stmtIn->execute();
        $stmtIn->close();
    }
}

/* -----------------------------
   CREATE (spremi novi unos)
--------------------------------*/
if (!$READONLY && $_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['spremi'])) {

    // Vrsta: za LIMITED poslovnice uvijek je 'najam'
    if ($IS_LIMITED) {
        $vrsta = 'najam';
    } else {
        $vrsta = $_POST['vrsta'] ?? null;
        if (empty($vrsta) || !in_array($vrsta, ['najam', 'uplata', 'isplata'], true)) {
            die("Molimo odaberite vrstu transakcije.");
        }
    }

    // Način plaćanja
    $nacin_placanja = $_POST['nacin_placanja'] ?? '';
    if ($IS_LIMITED) {
        $allowedPay = ['gotovina','free'];
    } else {
        $allowedPay = ['gotovina','kartica'];
    }
    if (!in_array($nacin_placanja, $allowedPay, true)) {
        $nacin_placanja = 'gotovina';
    }

    // Iznos
    $iznos = isset($_POST['iznos']) ? floatval($_POST['iznos']) : 0.0;

    // Free najam -> iznos 0.00
    if ($nacin_placanja === 'free') {
        $iznos = 0.0;
    }

    // Isplata ide u minus (ali LIMITED poslovnice ne mogu imati isplatu)
    if (!$IS_LIMITED && $vrsta === 'isplata') {
        $iznos = -abs($iznos);
    } else {
        $iznos = abs($iznos);
    }

    // Provizija samo za najam koji NIJE free
    $obracun_provizije = ($vrsta === 'najam' && $nacin_placanja !== 'free') ? 1 : 0;

    $stmt = $conn->prepare("INSERT INTO najmovi 
        (ime_prezime, adresar_id, grupa_vozila, tablica_vozila, datum_out, datum_in, napomena, nacin_placanja, iznos, vrsta, obracun_provizije, poslovnica_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $stmt->bind_param(
        "ssssssssdsii",
        $_POST['ime_prezime'],
        $_POST['adresar_id'],
        $_POST['grupa_vozila'],
        $_POST['tablica_vozila'],
        $_POST['datum_out'],
        $_POST['datum_in'],
        $_POST['napomena'],
        $nacin_placanja,
        $iznos,               // d
        $vrsta,               // s
        $obracun_provizije,   // i
        $POSL_ID              // i
    );

    $stmt->execute();
    if ($stmt->error) { error_log('SQL greška INSERT: ' . $stmt->error); die("Greška pri spremanju."); }
    $newNajamId = (int)$conn->insert_id;
    sync_cash_rental(
        $conn, $newNajamId, $POSL_ID, $vrsta, $nacin_placanja, $iznos,
        (string)($_POST['ime_prezime'] ?? ''), (string)($_POST['tablica_vozila'] ?? '')
    );

    header("Location: najmovi.php?poslovnica_id=" . $POSL_ID . ($EMBED ? "&embed=1" : "")); exit();
}

/* -----------------------------
   UPDATE (ažuriraj postojeći unos)
--------------------------------*/
if (!$READONLY && $_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['azuriraj'])) {
    $id    = isset($_POST['id']) ? intval($_POST['id']) : 0;
    if ($id <= 0) { die("Neispravan ID zapisa."); }

    // Vrsta
    if ($IS_LIMITED) {
        $vrsta = 'najam';
    } else {
        $vrsta = $_POST['vrsta'] ?? null;
        if (empty($vrsta) || !in_array($vrsta, ['najam', 'uplata', 'isplata'], true)) {
            die("Molimo odaberite ispravnu vrstu transakcije.");
        }
    }

    // Način plaćanja
    $nacin_placanja = $_POST['nacin_placanja'] ?? '';
    if ($IS_LIMITED) {
        $allowedPay = ['gotovina','free'];
    } else {
        $allowedPay = ['gotovina','kartica'];
    }
    if (!in_array($nacin_placanja, $allowedPay, true)) {
        $nacin_placanja = 'gotovina';
    }

    // Iznos
    $iznos = isset($_POST['iznos']) ? floatval($_POST['iznos']) : 0.0;
    if ($nacin_placanja === 'free') {
        $iznos = 0.0;
    }
    if (!$IS_LIMITED && $vrsta === 'isplata') {
        $iznos = -abs($iznos);
    } else {
        $iznos = abs($iznos);
    }

    $obracun_provizije = ($vrsta === 'najam' && $nacin_placanja !== 'free') ? 1 : 0;

    // Dohvati staro stanje prije izmjene kako bismo mogli evidentirati razlike.
    $stmtOld = $conn->prepare("SELECT ime_prezime, adresar_id, grupa_vozila, tablica_vozila,
                                     datum_out, datum_in, napomena, nacin_placanja, iznos, vrsta,
                                     obracun_provizije
                              FROM najmovi
                              WHERE id = ? AND poslovnica_id = ?");
    $stmtOld->bind_param("ii", $id, $POSL_ID);
    $stmtOld->execute();
    $oldData = $stmtOld->get_result()->fetch_assoc();
    $stmtOld->close();
    if (!$oldData) { die("Zapis nije pronađen ili ne pripada odabranoj poslovnici."); }

    $newData = [
        'ime_prezime'       => (string)($_POST['ime_prezime'] ?? ''),
        'adresar_id'        => (string)($_POST['adresar_id'] ?? ''),
        'grupa_vozila'      => (string)($_POST['grupa_vozila'] ?? ''),
        'tablica_vozila'    => (string)($_POST['tablica_vozila'] ?? ''),
        'datum_out'         => (string)($_POST['datum_out'] ?? ''),
        'datum_in'          => (string)($_POST['datum_in'] ?? ''),
        'napomena'          => (string)($_POST['napomena'] ?? ''),
        'nacin_placanja'    => (string)$nacin_placanja,
        'iznos'             => (float)$iznos,
        'vrsta'             => (string)$vrsta,
        'obracun_provizije' => (int)$obracun_provizije,
    ];

    $fieldLabels = [
        'ime_prezime' => 'Ime i prezime', 'adresar_id' => 'Adresar ID',
        'grupa_vozila' => 'Grupa vozila', 'tablica_vozila' => 'Tablica',
        'datum_out' => 'Datum OUT', 'datum_in' => 'Datum IN',
        'napomena' => 'Napomena', 'nacin_placanja' => 'Način plaćanja',
        'iznos' => 'Iznos', 'vrsta' => 'Vrsta',
        'obracun_provizije' => 'Obračun provizije'
    ];
    $changes = [];
    foreach ($newData as $field => $newValue) {
        $oldValue = $oldData[$field] ?? '';
        $same = ($field === 'iznos')
            ? abs((float)$oldValue - (float)$newValue) < 0.005
            : (string)$oldValue === (string)$newValue;
        if (!$same) {
            $changes[] = [
                'polje' => $fieldLabels[$field] ?? $field,
                'staro' => audit_value($oldValue),
                'novo'  => audit_value($newValue),
            ];
        }
    }

    $stmt = $conn->prepare("UPDATE najmovi SET
        ime_prezime = ?, 
        adresar_id = ?, 
        grupa_vozila = ?, 
        tablica_vozila = ?, 
        datum_out = ?, 
        datum_in = ?, 
        napomena = ?, 
        nacin_placanja = ?, 
        iznos = ?, 
        vrsta = ?, 
        obracun_provizije = ?
        WHERE id = ? AND poslovnica_id = ?");

    $stmt->bind_param(
        "ssssssssdsiii",
        $_POST['ime_prezime'],
        $_POST['adresar_id'],
        $_POST['grupa_vozila'],
        $_POST['tablica_vozila'],
        $_POST['datum_out'],
        $_POST['datum_in'],
        $_POST['napomena'],
        $nacin_placanja,
        $iznos,                // d
        $vrsta,                // s
        $obracun_provizije,    // i
        $id,                   // i
        $POSL_ID               // i
    );

    $stmt->execute();
    if ($stmt->error) { error_log('SQL greška UPDATE: ' . $stmt->error); die("Greška pri ažuriranju."); }
    sync_cash_rental(
        $conn, $id, $POSL_ID, $vrsta, $nacin_placanja, $iznos,
        (string)($_POST['ime_prezime'] ?? ''), (string)($_POST['tablica_vozila'] ?? '')
    );

    if ($changes) {
        $json = json_encode($changes, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $korisnikId = isset($_SESSION['poslovnica_id']) ? (int)$_SESSION['poslovnica_id'] : null;
        $korisnikNaziv = trim((string)($_SESSION['naziv'] ?? $_SESSION['uloga'] ?? 'Nepoznati korisnik'));
        $stmtAudit = $conn->prepare("INSERT INTO najmovi_promjene
            (najam_id, poslovnica_id, korisnik_id, korisnik_naziv, promjene_json)
            VALUES (?, ?, ?, ?, ?)");
        $stmtAudit->bind_param("iiiss", $id, $POSL_ID, $korisnikId, $korisnikNaziv, $json);
        $stmtAudit->execute();
        if ($stmtAudit->error) { error_log('SQL greška AUDIT: ' . $stmtAudit->error); }
        $stmtAudit->close();
    }

    header("Location: najmovi.php?poslovnica_id=" . $POSL_ID . ($EMBED ? "&embed=1" : "")); exit();
}

/* -----------------------------
   READ (lista) — samo za svoju poslovnicu + opcionalna pretraga
   - LIMITED (11,12): bez pretrage -> samo 20 najnovijih
   - sa pretragom -> svi koji odgovaraju
--------------------------------*/
if ($search !== '') {
    // PRETRAGA: uvijek bez limita (i za LIMITED)
    $like = '%' . $search . '%';
    $stmtList = $conn->prepare(
        "SELECT n.*,
                (SELECT COUNT(*) FROM najmovi_promjene np WHERE np.najam_id = n.id) AS promjena_count,
                (SELECT np.promjene_json FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_json,
                (SELECT np.created_at FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_at,
                (SELECT np.korisnik_naziv FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_user
         FROM najmovi n
         WHERE n.poslovnica_id = ?
           AND n.ime_prezime LIKE ?
         ORDER BY n.id DESC"
    );
    $stmtList->bind_param("is", $POSL_ID, $like);
} else {
    if ($IS_LIMITED) {
        // BEZ PRETRAGE i LIMITED: limitiraj na 20
        $stmtList = $conn->prepare(
            "SELECT n.*,
                (SELECT COUNT(*) FROM najmovi_promjene np WHERE np.najam_id = n.id) AS promjena_count,
                (SELECT np.promjene_json FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_json,
                (SELECT np.created_at FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_at,
                (SELECT np.korisnik_naziv FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_user
         FROM najmovi n
             WHERE n.poslovnica_id = ?
             ORDER BY n.id DESC
             LIMIT 20"
        );
        $stmtList->bind_param("i", $POSL_ID);
    } else {
        // Ostale poslovnice: puni popis
        $stmtList = $conn->prepare(
            "SELECT n.*,
                (SELECT COUNT(*) FROM najmovi_promjene np WHERE np.najam_id = n.id) AS promjena_count,
                (SELECT np.promjene_json FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_json,
                (SELECT np.created_at FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_at,
                (SELECT np.korisnik_naziv FROM najmovi_promjene np WHERE np.najam_id = n.id ORDER BY np.id DESC LIMIT 1) AS zadnja_promjena_user
         FROM najmovi n
             WHERE n.poslovnica_id = ?
             ORDER BY n.id DESC"
        );
        $stmtList->bind_param("i", $POSL_ID);
    }
}
$stmtList->execute();
$result = $stmtList->get_result();
function fmt_hr_date(?string $iso): string {
    if (!$iso || $iso === '0000-00-00') return '';
    $dt = DateTime::createFromFormat('Y-m-d', $iso);
    return $dt ? $dt->format('d/m/Y') : htmlspecialchars($iso, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Najmovi</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">
    <style>
      :root {
        --app-bg: #f3f6fb;
        --card: #ffffff;
        --text: #172033;
        --muted: #6b7485;
        --line: #e2e8f0;
        --primary: #1769e0;
        --primary-dark: #0d56c5;
        --success: #128a58;
        --danger: #dc3545;
        --shadow: 0 10px 28px rgba(21, 37, 63, .07);
      }
      * { box-sizing: border-box; }
      body {
        margin: 0;
        background: var(--app-bg);
        color: var(--text);
        font-family: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
        font-size: 14px;
      }
      .app-shell { max-width: 1280px; margin: 0 auto; padding: 18px 22px 34px; }
      .app-header {
        display: flex; align-items: center; justify-content: space-between; gap: 16px;
        background: var(--card); border: 1px solid var(--line); border-radius: 16px;
        padding: 14px 18px; box-shadow: var(--shadow); margin-bottom: 18px;
      }
      .brand { display: flex; align-items: center; gap: 12px; }
      .brand-mark {
        width: 42px; height: 42px; border-radius: 12px; display: grid; place-items: center;
        background: linear-gradient(135deg, #2b7cff, #1259d5); color: #fff; font-weight: 800;
        box-shadow: 0 8px 18px rgba(23,105,224,.24);
      }
      .brand-title { font-size: 18px; font-weight: 750; line-height: 1.15; }
      .brand-subtitle { color: var(--muted); font-size: 12.5px; margin-top: 2px; }
      .page-toolbar {
        display: flex; align-items: center; justify-content: space-between; gap: 14px;
        flex-wrap: wrap; margin-bottom: 16px;
      }
      .page-title { margin: 0; font-size: 22px; font-weight: 750; letter-spacing: -.02em; }
      .report-controls, .search-card {
        display: flex; align-items: end; gap: 8px; flex-wrap: wrap;
      }
      .section-card {
        background: var(--card); border: 1px solid var(--line); border-radius: 16px;
        box-shadow: var(--shadow); padding: 18px; margin-bottom: 18px;
      }
      .section-heading { font-size: 14px; font-weight: 750; margin: 0 0 14px; }
      .form-label { font-size: 12px; font-weight: 700; color: #485269; margin-bottom: 6px; }
      .form-control, .form-select {
        min-height: 38px; border-color: #d7deea; border-radius: 9px; font-size: 13px;
        padding: .48rem .68rem; background-color: #fff;
      }
      textarea.form-control { min-height: 64px; }
      .form-control:focus, .form-select:focus {
        border-color: #80aff4; box-shadow: 0 0 0 .2rem rgba(23,105,224,.12);
      }
      .form-text { font-size: 11px; color: #8790a0; }
      .btn { border-radius: 9px; font-size: 13px; font-weight: 650; padding: .48rem .78rem; }
      .btn-primary { background: var(--primary); border-color: var(--primary); }
      .btn-primary:hover { background: var(--primary-dark); border-color: var(--primary-dark); }
      .btn-success { background: var(--success); border-color: var(--success); }
      .search-panel {
        display: flex; justify-content: space-between; align-items: end; gap: 12px;
        flex-wrap: wrap; background: var(--card); border: 1px solid var(--line);
        border-radius: 14px; padding: 13px 15px; margin-bottom: 16px;
      }
      .table-card {
        background: var(--card); border: 1px solid var(--line); border-radius: 16px;
        box-shadow: var(--shadow); overflow: hidden;
      }
      .table-card-header {
        display:flex; justify-content:space-between; align-items:center; gap:12px;
        padding: 14px 16px; border-bottom: 1px solid var(--line);
      }
      .table-card-title { font-size: 14px; font-weight: 750; margin: 0; }
      .table-count { font-size: 12px; color: var(--muted); }
      .table-responsive { margin: 0; }
      .rentals-table { margin: 0; min-width: 1100px; table-layout: auto; }
      .rentals-table thead th {
        background: #f7f9fc; color: #58637a; text-transform: uppercase;
        letter-spacing: .035em; font-size: 10.5px; font-weight: 800;
        border-color: var(--line); padding: 10px 9px; white-space: nowrap;
      }
      .rentals-table tbody td {
        font-size: 12.5px; padding: 9px; border-color: #edf1f6;
        vertical-align: middle; line-height: 1.35;
      }
      .rentals-table tbody tr:nth-child(even) td { background: #fbfcfe; }
      .rentals-table tbody tr:hover td { background: #f1f6ff; }
      .rentals-table th:nth-child(1), .rentals-table td:nth-child(1) { width: 42px; text-align:center; }
      .rentals-table th:nth-child(2), .rentals-table td:nth-child(2) { width: 76px; }
      .rentals-table th:nth-child(3), .rentals-table td:nth-child(3) { min-width: 170px; max-width: 220px; }
      .rentals-table th:nth-child(4), .rentals-table td:nth-child(4) { width: 92px; }
      .rentals-table th:nth-child(5), .rentals-table td:nth-child(5) { width: 76px; }
      .rentals-table th:nth-child(6), .rentals-table td:nth-child(6) { width: 90px; white-space: nowrap; }
      .rentals-table th:nth-child(7), .rentals-table td:nth-child(7),
      .rentals-table th:nth-child(8), .rentals-table td:nth-child(8) { width: 94px; white-space: nowrap; }
      .rentals-table th:nth-child(9), .rentals-table td:nth-child(9) { width: 95px; white-space: nowrap; text-align:right; font-weight:700; }
      .rentals-table th:nth-child(10), .rentals-table td:nth-child(10) { width: 90px; }
      .rentals-table th:nth-child(11), .rentals-table td:nth-child(11) { min-width: 160px; max-width: 260px; }
      .rentals-table th:nth-child(12), .rentals-table td:nth-child(12) { width: 76px; text-align:center; }
      .badge { border-radius: 999px; font-size: 10px; font-weight: 750; padding: 5px 8px; }
      .payment-label { display:inline-flex; align-items:center; gap:5px; font-size:12px; font-weight:650; }
      .payment-dot { width:7px; height:7px; border-radius:50%; background:#1769e0; }
      .payment-dot.cash { background:#e59b20; }
      .payment-dot.free { background:#7b8799; }
      .change-alert {
        width: 25px; height: 25px; border-radius: 50%; border: 1px solid #f0ad2c;
        background: #fff8e6; color: #b56b00; display:inline-flex; align-items:center;
        justify-content:center; font-weight:900; font-size:13px; cursor:pointer;
        box-shadow: 0 2px 8px rgba(181,107,0,.12);
      }
      .change-alert:hover { background:#ffefbf; transform:translateY(-1px); }
      .audit-row { display:grid; grid-template-columns:140px 1fr 26px 1fr; gap:8px; align-items:start;
        padding:9px 0; border-bottom:1px solid #edf1f6; font-size:12.5px; }
      .audit-row:last-child { border-bottom:0; }
      .audit-field { font-weight:750; color:#344054; }
      .audit-old { color:#b42318; background:#fff1f0; border-radius:7px; padding:5px 7px; overflow-wrap:anywhere; }
      .audit-new { color:#067647; background:#ecfdf3; border-radius:7px; padding:5px 7px; overflow-wrap:anywhere; }
      .audit-arrow { color:#98a2b3; text-align:center; padding-top:5px; }
      .modal-modern {
        background: var(--card); border: 1px solid var(--line); border-radius: 16px !important;
        box-shadow: 0 24px 70px rgba(15, 28, 50, .22) !important;
      }
      .branch-switcher {
        display: inline-flex; align-items: center; gap: 4px; padding: 4px;
        background: #eef3fb; border: 1px solid #d9e2ef; border-radius: 11px;
      }
      .branch-switcher-label {
        color: var(--muted); font-size: 11px; font-weight: 700; margin-right: 4px;
        padding-left: 5px;
      }
      .branch-switch-btn {
        display: inline-flex; align-items: center; justify-content: center;
        min-height: 34px; padding: 7px 13px; border-radius: 8px;
        color: #41506a; text-decoration: none; font-size: 12.5px; font-weight: 750;
        border: 1px solid transparent; transition: .16s ease;
      }
      .branch-switch-btn:hover { color: var(--primary); background: #fff; }
      .branch-switch-btn.active {
        background: var(--primary); color: #fff; border-color: var(--primary);
        box-shadow: 0 3px 9px rgba(23,105,224,.22);
      }
      .header-actions { display:flex; align-items:center; gap:10px; flex-wrap:wrap; justify-content:flex-end; }
      @media (max-width: 768px) {
        .app-shell { padding: 10px; }
        .app-header { border-radius: 12px; padding: 12px; }
        .brand-subtitle { display:none; }
        .page-title { font-size: 19px; }
        .section-card { padding: 14px; border-radius: 13px; }
        .search-panel { align-items: stretch; }
      }
    </style>

    <style>
      body.embed-mode .container { max-width: 100% !important; }
      body.embed-mode > .container { margin-top: .75rem !important; padding-left: .75rem; padding-right: .75rem; }
      body.embed-mode h3 { font-size: 1.15rem; }
    </style>
</head>
<body class="<?= $EMBED ? 'embed-mode' : '' ?>">
  <div class="app-shell">
    <header class="app-header">
      <div class="brand">
        <div class="brand-mark">AV</div>
        <div>
          <div class="brand-title">Najmovi vozila</div>
          <div class="brand-subtitle">Poslovnica: <?= htmlspecialchars($ACTIVE_BRANCH_LABEL, ENT_QUOTES, 'UTF-8') ?> · evidencija najmova</div>
        </div>
      </div>
      <div class="header-actions">
        <?php if ($CAN_SWITCH_ZADAR): ?>
          <div class="branch-switcher" aria-label="Odabir poslovnice">
            <span class="branch-switcher-label">Poslovnica</span>
            <a href="najmovi.php?switch_poslovnica=11"
               class="branch-switch-btn <?= $POSL_ID === 11 ? 'active' : '' ?>">Zadar</a>
            <a href="najmovi.php?switch_poslovnica=12"
               class="branch-switch-btn <?= $POSL_ID === 12 ? 'active' : '' ?>">Zadar AP</a>
          </div>
        <?php endif; ?>
        <?php if (!$EMBED): ?>
          <?php if ($POSL_ID === 3 || mb_strtolower($ACTIVE_BRANCH_LABEL, 'UTF-8') === 'šibenik' || mb_strtolower($ACTIVE_BRANCH_LABEL, 'UTF-8') === 'sibenik'): ?>
            <a href="dashboard.php" class="btn btn-outline-primary">Početna</a>
          <?php endif; ?>
          <a href="logout.php" class="btn btn-outline-danger">Odjava</a>
        <?php endif; ?>
      </div>
    </header>

    <div class="page-toolbar">
      <h1 class="page-title">Pregled i unos najmova</h1>
      <?php if (!$IS_LIMITED): // LIMITED (11,12) nemaju izvještaj ?>
      <div class="report-controls">
          <div>
            <label for="mjesecIzvjestaja" class="form-label">Mjesec izvještaja</label>
            <input type="month" id="mjesecIzvjestaja" class="form-control" style="width: 165px;">
          </div>
          <button class="btn btn-primary" onclick="prikaziIzvjestaj()">Izvještaj</button>
      </div>
      <?php endif; ?>
    </div>

    <!-- SEARCH forma -->
    <form method="GET" class="search-panel">
        <input type="hidden" name="poslovnica_id" value="<?= (int)$POSL_ID ?>">
        <?php if ($EMBED): ?><input type="hidden" name="embed" value="1"><?php endif; ?>
      <div style="min-width:260px; flex:1; max-width:460px;">
        <label class="form-label">Pretraži po imenu i prezimenu</label>
        <input type="text" name="search" class="form-control"
               placeholder="Upišite ime ili prezime"
               value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>">
      </div>
      <div class="d-flex gap-2">
        <button class="btn btn-primary">Traži</button>
        <?php if ($search !== ''): ?>
          <a href="najmovi.php?poslovnica_id=<?= (int)$POSL_ID ?>" class="btn btn-outline-secondary">Očisti</a>
        <?php endif; ?>
      </div>
    </form>

    <!-- CREATE forma -->
    <?php if (!$READONLY): ?>
    <div class="section-card">
      <h2 class="section-heading">Novi unos</h2>
      <form method="POST" class="row g-3" autocomplete="off">
        <input type="hidden" name="spremi" value="1">
        <input type="hidden" name="poslovnica_id" value="<?= (int)$POSL_ID ?>">
        <?php if ($EMBED): ?><input type="hidden" name="embed" value="1"><?php endif; ?>
        <input type="hidden" name="poslovnica_id" value="<?= (int)$POSL_ID ?>">

        <div class="col-md-3">
          <label class="form-label">Vrsta</label>

          <?php if ($IS_LIMITED): ?>
            <!-- Za LIMITED poslovnice, samo najam -->
            <input type="hidden" name="vrsta" value="najam">
            <input type="text" class="form-control" value="Najam (obračunava proviziju)" disabled>
          <?php else: ?>
            <select name="vrsta" id="vrsta" class="form-select" required>
              <option value="" disabled selected>Odaberite vrstu transakcije</option>
              <option value="najam">Najam (obračunava proviziju)</option>
              <option value="uplata">Uplata bez provizije</option>
              <option value="isplata">Isplata bez provizije</option>
            </select>
          <?php endif; ?>
        </div>

        <div class="col-md-4">
          <label class="form-label">Ime i prezime</label>
          <input name="ime_prezime" class="form-control" required>
        </div>

        <div class="col-md-2">
          <label class="form-label">Adresar ID</label>
          <input name="adresar_id" class="form-control">
        </div>

        <div class="col-md-4">
          <label for="grupa_vozila" class="form-label">Grupa vozila</label>
          <select name="grupa_vozila" id="grupa_vozila" class="form-select">
            <option value="">-- Odaberi --</option>
            <option value="MBMV">MBMV - Fiat 500</option>
            <option value="MCMR">MCMR - Fiat Panda</option>
            <option value="EDMR">EDMR - Škoda Fabia</option>
            <option value="EDMM">EDMM - Volkswagen Polo</option>
            <option value="IDMR">IDMR - Škoda Scala</option>
            <option value="CDMR">CDMR - VW Golf VIII</option>
            <option value="CFMR">CFMR - VW T-Cross</option>
            <option value="EWMR">EWMR - Škoda Fabia Combi</option>
            <option value="CWMR">CWMR - Kia Ceed SW</option>
            <option value="CWAR">CWAR - Peugeot 308 SW AUT.</option>
            <option value="IDMD">IDMD - Škoda Octavia</option>
            <option value="SFMR">SFMR - Peugeot 3008 Manual</option>
            <option value="MDBE">MDBE - Škoda CITIGO-e iV</option>
            <option value="EDAR">EDAR - Volkswagen Polo DSG</option>
            <option value="CDAR">CDAR - Volkswagen Golf VIII DSG</option>
            <option value="CFAR">CFAR - Peugeot 2008 Aut.</option>
            <option value="IDAD">IDAD - Škoda Octavia Automatic</option>
            <option value="SFAR">SFAR - Peugeot 3008 automatic</option>
            <option value="SLAR">SLAR - Volkswagen Passat DSG</option>
            <option value="LLAD">LLAD - Audi A6</option>
            <option value="FVMR">FVMR - Peugeot Rifter</option>
            <option value="CVAR">CVAR - Škoda Kodiaq</option>
            <option value="FVAR">FVAR - Opel Zafira 7+1</option>
            <option value="SVAR">SVAR - Opel Combo Aut.</option>
            <option value="FVMD">FVMD - Peugeot Traveller</option>
            <option value="FVAD">FVAD - Peugeot Traveller Aut.</option>
            <option value="FKMR">FKMR - Peugeot Boxer Furgon</option>
            <option value="FDAE">FDAE - Peugeot Expert</option>
            <option value="FKMD">FKMD - Opel Combo</option>
            <option value="SLAD">SLAD - WV Passat DSG Variant</option>
            <option value="XYAZ">XYAZ - Aprilia</option>
            <option value="PYAV">PYAV - Piaggio Liberty 125ccm</option>
            <option value="UXAV">UXAV - Beverly MP3 300 HPE</option>
            <option value="UYAV">UYAV - Beverly 300</option>
            <option value="UYDV">UYDV - Beverly 400 HPE</option>
          </select>
          <div class="form-text">Za uplate/isplate možeš ostaviti grupu/tablicu prazno ako nije primjenjivo.</div>
        </div>

        <div class="col-md-2">
          <label class="form-label">Tablica</label>
          <input name="tablica_vozila" class="form-control">
        </div>

        <div class="col-md-3">
          <label class="form-label">Datum OUT</label>
          <input name="datum_out" type="date" class="form-control" required>
        </div>

        <div class="col-md-3">
          <label class="form-label">Datum IN</label>
          <input name="datum_in" type="date" class="form-control">
        </div>

        <div class="col-md-3">
          <label class="form-label">Način plaćanja</label>
          <select name="nacin_placanja" id="nacin_placanja" class="form-select" required>
              <?php if ($IS_LIMITED): ?>
                <option value="gotovina">Gotovina</option>
                <option value="free">Free najam</option>
              <?php else: ?>
                <option value="gotovina">Gotovina</option>
                <option value="kartica">Kartica</option>
              <?php endif; ?>
          </select>
        </div>

        <div class="col-md-2">
          <label class="form-label">Iznos (€)</label>
          <input name="iznos" id="iznos" type="number" step="0.01" class="form-control" required>
          <div class="form-text"><?php if ($IS_LIMITED): ?>Ako odabereš "Free najam", iznos će biti 0.00.<?php endif; ?></div>
        </div>

        <div class="col-md-12">
          <label class="form-label">Napomena</label>
          <textarea name="napomena" class="form-control" rows="2"></textarea>
        </div>

        <div class="col-12 text-end">
          <button class="btn btn-success">Spremi unos</button>
        </div>
      </form>
    </div>
    <?php endif; ?>

    <!-- Tablica -->
    <div class="table-card">
      <div class="table-card-header">
        <h2 class="table-card-title">Evidencija</h2>
        <div class="table-count"><?= (int)$result->num_rows ?> zapisa<?= $search !== '' ? ' u rezultatima pretrage' : '' ?></div>
      </div>
      <div class="table-responsive">
      <table class="table rentals-table align-middle">
        <thead class="table-light">
          <tr>
            <th>#</th><th>Vrsta</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>Iznos</th><th>Plaćeno</th><th>Napomena</th><?php if (!$READONLY): ?><th style="width:110px">Akcije</th><?php endif; ?>
          </tr>
        </thead>
        <tbody>
          <?php $rb = 1; while ($row = $result->fetch_assoc()):
              if ($row['vrsta'] === 'najam') { $badgeClass = 'primary'; $badgeText = 'Najam'; }
              elseif ($row['vrsta'] === 'uplata') { $badgeClass = 'success'; $badgeText = 'Uplata'; }
              elseif ($row['vrsta'] === 'isplata') { $badgeClass = 'danger'; $badgeText = 'Isplata'; }
              else { $badgeClass = 'secondary'; $badgeText = ucfirst((string)$row['vrsta']); }

              $iznosFmt = number_format((float)$row['iznos'], 2);
              if ((float)$row['iznos'] < 0) { $iznosFmt = "- " . number_format(abs((float)$row['iznos']), 2); }

              $paidLabel = ($row['nacin_placanja'] === 'free') ? 'Free najam' : $row['nacin_placanja'];

              $h = fn($v) => htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
          ?>
            <tr>
              <td><?= $rb++ ?></td>
              <td><span class="badge bg-<?= $badgeClass ?>"><?= $badgeText ?></span></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><?= fmt_hr_date($row['datum_out']) ?></td>
              <td><?= fmt_hr_date($row['datum_in']) ?></td>
              <td><?= $iznosFmt ?> €</td>
              <td>
                <?php
                  $payClass = $row['nacin_placanja'] === 'gotovina' ? 'cash' : ($row['nacin_placanja'] === 'free' ? 'free' : '');
                ?>
                <span class="payment-label"><span class="payment-dot <?= $payClass ?>"></span><?= htmlspecialchars(ucfirst($paidLabel)) ?></span>
              </td>
              <td><?= htmlspecialchars($row['napomena']) ?></td>
              <td>
                <div class="d-inline-flex align-items-center gap-1">
                <?php if ((int)($row['promjena_count'] ?? 0) > 0):
                    $auditPayload = htmlspecialchars((string)$row['zadnja_promjena_json'], ENT_QUOTES, 'UTF-8');
                ?>
                  <button type="button" class="change-alert" title="Prikaži zadnju izmjenu"
                    data-history="<?= $auditPayload ?>"
                    data-time="<?= $h($row['zadnja_promjena_at']) ?>"
                    data-user="<?= $h($row['zadnja_promjena_user']) ?>"
                    data-count="<?= (int)$row['promjena_count'] ?>"
                    onclick="otvoriPromjene(this)">!</button>
                <?php endif; ?>
                <button 
                  class="btn btn-sm btn-outline-primary"
                  onclick="otvoriUredi(this)"
                  data-id="<?= (int)$row['id'] ?>"
                  data-vrsta="<?= $h($row['vrsta']) ?>"
                  data-ime_prezime="<?= $h($row['ime_prezime']) ?>"
                  data-adresar_id="<?= $h($row['adresar_id']) ?>"
                  data-grupa_vozila="<?= $h($row['grupa_vozila']) ?>"
                  data-tablica_vozila="<?= $h($row['tablica_vozila']) ?>"
                  data-datum_out="<?= $h($row['datum_out']) ?>"
                  data-datum_in="<?= $h($row['datum_in']) ?>"
                  data-nacin_placanja="<?= $h($row['nacin_placanja']) ?>"
                  data-iznos="<?= $h(abs((float)$row['iznos'])) ?>" 
                  data-napomena="<?= $h($row['napomena']) ?>"
                >Uredi</button>
                </div>
              </td>
            </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
      </div>
    </div>

  </div>

    <?php if (!$IS_LIMITED): // modal izvještaja uopće ne prikazujemo za LIMITED ?>
    <!-- Izvještaj modal -->
    <div id="modal" class="position-fixed top-0 start-0 w-100 h-100 bg-dark bg-opacity-50 d-none justify-content-center align-items-center">
      <div class="modal-modern p-4 d-flex gap-4" style="max-width: 700px; width: 100%;">
        <div class="flex-grow-1">
          <h5 class="mb-3">📊 Izvještaj</h5>
          <div id="izvjestajText"></div>
          <button onclick="document.getElementById('modal').classList.add('d-none')" class="btn btn-secondary mt-3">Zatvori</button>
        </div>
        <div class="border-start ps-3" style="min-width: 220px;">
          <h6 class="text-muted" id="mjHeader">Provizija po mjesecima</h6>
          <ul class="list-unstyled small" id="provizijeMj">
            <li class="text-muted">Učitavanje...</li>
          </ul>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- Pregled zadnje izmjene -->
    <div id="auditModal" class="position-fixed top-0 start-0 w-100 h-100 bg-dark bg-opacity-50 d-none justify-content-center align-items-center" style="z-index:1080; padding:12px;">
      <div class="modal-modern p-4" style="max-width:760px; width:100%; max-height:88vh; overflow:auto;">
        <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
          <div>
            <h5 class="m-0">Izmjene zapisa</h5>
            <div id="auditMeta" class="small text-muted mt-1"></div>
          </div>
          <button type="button" class="btn btn-sm btn-outline-secondary" onclick="zatvoriPromjene()">Zatvori</button>
        </div>
        <div id="auditBody"></div>
      </div>
    </div>

    <?php if (!$READONLY): ?>
    <!-- Uredi modal -->
    <div id="editModal" class="position-fixed top-0 start-0 w-100 h-100 bg-dark bg-opacity-50 d-none justify-content-center align-items-start" style="padding-top:5vh;">
      <div class="modal-modern p-4" style="max-width: 900px; width: calc(100% - 24px); max-height:90vh; overflow:auto;">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <h5 class="m-0">✏️ Uredi unos</h5>
          <button class="btn btn-sm btn-outline-secondary" onclick="zatvoriUredi()">Zatvori</button>
        </div>
        <form method="POST" class="row g-3" id="editForm">
          <input type="hidden" name="azuriraj" value="1">
          <input type="hidden" name="poslovnica_id" value="<?= (int)$POSL_ID ?>">
          <?php if ($EMBED): ?><input type="hidden" name="embed" value="1"><?php endif; ?>
          <input type="hidden" name="poslovnica_id" value="<?= (int)$POSL_ID ?>">
          <input type="hidden" name="id" id="e_id">

          <div class="col-md-3">
            <label class="form-label">Vrsta</label>
            <?php if ($IS_LIMITED): ?>
              <!-- LIMITED: uvijek najam -->
              <input type="hidden" name="vrsta" id="e_vrsta" value="najam">
              <input type="text" class="form-control" value="Najam (obračunava proviziju)" disabled>
            <?php else: ?>
              <select name="vrsta" id="e_vrsta" class="form-select" required>
                <option value="najam">Najam (obračunava proviziju)</option>
                <option value="uplata">Uplata bez provizije</option>
                <option value="isplata">Isplata bez provizije</option>
              </select>
            <?php endif; ?>
          </div>

          <div class="col-md-4">
            <label class="form-label">Ime i prezime</label>
            <input name="ime_prezime" id="e_ime_prezime" class="form-control" required>
          </div>

          <div class="col-md-2">
            <label class="form-label">Adresar ID</label>
            <input name="adresar_id" id="e_adresar_id" class="form-control">
          </div>

          <div class="col-md-4">
            <label class="form-label">Grupa vozila</label>
            <select name="grupa_vozila" id="e_grupa_vozila" class="form-select">
              <option value="">-- Odaberi --</option>
              <option value="MBMV">MBMV - Fiat 500</option>
              <option value="MCMR">MCMR - Fiat Panda</option>
              <option value="EDMR">EDMR - Škoda Fabia</option>
              <option value="EDMM">EDMM - Volkswagen Polo</option>
              <option value="IDMR">IDMR - Škoda Scala</option>
              <option value="CDMR">CDMR - VW Golf VIII</option>
              <option value="CFMR">CFMR - VW T-Cross</option>
              <option value="EWMR">EWMR - Škoda Fabia Combi</option>
              <option value="CWMR">CWMR - Kia Ceed SW</option>
              <option value="CWAR">CWAR - Peugeot 308 SW AUT.</option>
              <option value="IDMD">IDMD - Škoda Octavia</option>
              <option value="SFMR">SFMR - Peugeot 3008 Manual</option>
              <option value="MDBE">MDBE - Škoda CITIGO-e iV</option>
              <option value="EDAR">EDAR - Volkswagen Polo DSG</option>
              <option value="CDAR">CDAR - Volkswagen Golf VIII DSG</option>
              <option value="CFAR">CFAR - Peugeot 2008 Aut.</option>
              <option value="IDAD">IDAD - Škoda Octavia Automatic</option>
              <option value="SFAR">SFAR - Peugeot 3008 automatic</option>
              <option value="SLAR">SLAR - Volkswagen Passat DSG</option>
              <option value="LLAD">LLAD - Audi A6</option>
              <option value="FVMR">FVMR - Peugeot Rifter</option>
              <option value="CVAR">CVAR - Škoda Kodiaq</option>
              <option value="FVAR">FVAR - Opel Zafira 7+1</option>
              <option value="SVAR">SVAR - Opel Combo Aut.</option>
              <option value="FVMD">FVMD - Peugeot Traveller</option>
              <option value="FVAD">FVAD - Peugeot Traveller Aut.</option>
              <option value="FKMR">FKMR - Peugeot Boxer Furgon</option>
              <option value="FDAE">FDAE - Peugeot Expert</option>
              <option value="FKMD">FKMD - Opel Combo</option>
              <option value="SLAD">SLAD - WV Passat DSG Variant</option>
              <option value="XYAZ">XYAZ - Aprilia</option>
              <option value="PYAV">PYAV - Piaggio Liberty 125ccm</option>
              <option value="UXAV">UXAV - Beverly MP3 300 HPE</option>
              <option value="UYAV">UYAV - Beverly 300</option>
              <option value="UYDV">UYDV - Beverly 400 HPE</option>
            </select>
          </div>

          <div class="col-md-2">
            <label class="form-label">Tablica</label>
            <input name="tablica_vozila" id="e_tablica_vozila" class="form-control">
          </div>

          <div class="col-md-3">
            <label class="form-label">Datum OUT</label>
            <input name="datum_out" id="e_datum_out" type="date" class="form-control" required>
          </div>

          <div class="col-md-3">
            <label class="form-label">Datum IN</label>
            <input name="datum_in" id="e_datum_in" type="date" class="form-control">
          </div>

          <div class="col-md-3">
            <label class="form-label">Način plaćanja</label>
            <select name="nacin_placanja" id="e_nacin_placanja" class="form-select" required>
              <?php if ($IS_LIMITED): ?>
                <option value="gotovina">Gotovina</option>
                <option value="free">Free najam</option>
              <?php else: ?>
                <option value="gotovina">Gotovina</option>
                <option value="kartica">Kartica</option>
              <?php endif; ?>
            </select>
          </div>

          <div class="col-md-2">
            <label class="form-label">Iznos (€)</label>
            <input name="iznos" id="e_iznos" type="number" step="0.01" class="form-control" required>
            <div class="form-text"><?php if ($IS_LIMITED): ?>Ako odabereš "Free najam", iznos će biti 0.00.<?php else: ?>Za <strong>isplatu</strong> spremit će se s minusom.<?php endif; ?></div>
          </div>

          <div class="col-md-12">
            <label class="form-label">Napomena</label>
            <textarea name="napomena" id="e_napomena" class="form-control" rows="2"></textarea>
          </div>

          <div class="col-12 text-end">
            <button class="btn btn-primary">💾 Spremi izmjene</button>
          </div>
        </form>
      </div>
    </div>
    <?php endif; ?>

<script>
function escapeAudit(value) {
  return String(value ?? '—').replace(/[&<>"']/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]));
}
function otvoriPromjene(btn) {
  let changes = [];
  try { changes = JSON.parse(btn.dataset.history || '[]'); } catch (e) {}
  const count = Number(btn.dataset.count || 1);
  const user = btn.dataset.user || 'Nepoznati korisnik';
  const rawTime = btn.dataset.time || '';
  const time = rawTime ? new Date(rawTime.replace(' ', 'T')).toLocaleString('hr-HR') : '—';
  document.getElementById('auditMeta').textContent = `Zadnja izmjena: ${time} · Korisnik: ${user}${count > 1 ? ` · Ukupno izmjena: ${count}` : ''}`;
  document.getElementById('auditBody').innerHTML = changes.length
    ? changes.map(c => `<div class="audit-row"><div class="audit-field">${escapeAudit(c.polje)}</div><div class="audit-old">${escapeAudit(c.staro)}</div><div class="audit-arrow">→</div><div class="audit-new">${escapeAudit(c.novo)}</div></div>`).join('')
    : '<div class="text-muted">Detalji izmjene nisu dostupni.</div>';
  const modal = document.getElementById('auditModal');
  modal.classList.remove('d-none'); modal.classList.add('d-flex');
}
function zatvoriPromjene() {
  const modal = document.getElementById('auditModal');
  modal.classList.add('d-none'); modal.classList.remove('d-flex');
}

// --- Modal UREDI ---
function otvoriUredi(btn) {
  const g = (name) => btn.getAttribute('data-' + name) || '';

  document.getElementById('e_id').value            = g('id');

  // LIMITED: vrsta je uvijek najam (polje je hidden/disabled u UI)
  const eVrsta = document.getElementById('e_vrsta');
  if (eVrsta) eVrsta.value = 'najam';

  document.getElementById('e_ime_prezime').value   = g('ime_prezime');
  document.getElementById('e_adresar_id').value    = g('adresar_id');
  document.getElementById('e_grupa_vozila').value  = g('grupa_vozila');
  document.getElementById('e_tablica_vozila').value= g('tablica_vozila');
  document.getElementById('e_datum_out').value     = g('datum_out');
  document.getElementById('e_datum_in').value      = g('datum_in');

  const paid = g('nacin_placanja');
  const ePay = document.getElementById('e_nacin_placanja');
  if (ePay) ePay.value = paid === 'free' ? 'free' : paid;

  document.getElementById('e_iznos').value         = g('iznos');
  document.getElementById('e_napomena').value      = g('napomena');

  document.getElementById('editModal').classList.remove('d-none');
}
function zatvoriUredi() {
  document.getElementById('editModal').classList.add('d-none');
}

<?php if (!$IS_LIMITED): ?>
// --- Izvještaj (onemogućen za LIMITED) ---
function prikaziIzvjestaj() {
  const mjesec = document.getElementById('mjesecIzvjestaja').value;
  const params = new URLSearchParams();
  params.set('poslovnica_id', '<?= (int)$POSL_ID ?>');
  if (mjesec) params.set('mjesec', mjesec);
  const qs = '?' + params.toString();

  // helperi za formatiranje
  const fmtEUR = (n) => Number(n || 0).toLocaleString('hr-HR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

  fetch('najmovi_izvjestaj.php' + qs)
    .then(res => { if(!res.ok) throw new Error('HTTP ' + res.status); return res.json(); })
    .then(data => {
      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   = (data.provizija !== undefined && data.provizija !== null)
                            ? Number(data.provizija) : (0.15 * osnova);
      const avia        = (data.ukupno_za_avia !== undefined && data.ukupno_za_avia !== null)
                            ? Number(data.ukupno_za_avia) : (gotovina - provizija);

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

      const netoUplate  = (data.neto_uplate !== undefined && data.neto_uplate !== null)
                            ? Number(data.neto_uplate) : (sumaUplata - sumaIsplata);

      const stanje      = (data.stanje !== undefined && data.stanje !== null)
                            ? Number(data.stanje) : (avia + netoUplate);

      const stanjeClass = stanje >= 0 ? 'text-success' : 'text-danger';
      const stanjeBadge = stanje >= 0 ? 'bg-success' : 'bg-danger';

      document.getElementById('izvjestajText').innerHTML = `
          <p><strong>Total gotovina (samo najam):</strong> ${fmtEUR(gotovina)} €</p>
          <p><strong>Total kartice (samo najam):</strong> ${fmtEUR(kartica)} €</p>
          <p><strong>Ukupno saldo (samo najam):</strong> ${fmtEUR(ukupno)} €</p>
          <hr/>
          <p><strong>Osnova za proviziju (najam):</strong> ${fmtEUR(osnova)} €</p>
          <p><strong>Provizija (15%):</strong> ${fmtEUR(provizija)} €</p>
          <p><strong>Ukupno za Avia (gotovina - provizija):</strong> ${fmtEUR(avia)} €</p>
          <hr/>
          <p><strong>Broj uplata:</strong> ${brojUplata}</p>
          <p><strong>Iznos uplata:</strong> ${fmtEUR(sumaUplata)} €</p>
          <p><strong>Broj isplata:</strong> ${brojIsplata}</p>
          <p><strong>Iznos isplata:</strong> ${fmtEUR(sumaIsplata)} €</p>
          <hr/>
          <p><strong>Neto uplate (uplata − isplata):</strong> ${fmtEUR(netoUplate)} €</p>
          <hr/>
          <p class="fs-5 ${stanjeClass}">
            <strong>Ukupno stanje = (Ukupno za Avia) + (Neto uplate):</strong>
            <span class="badge ${stanjeBadge} ms-2">${fmtEUR(stanje)} €</span>
          </p>
      `;

      const header = document.getElementById('mjHeader');
      const lista  = document.getElementById('provizijeMj');
      lista.innerHTML = '';

      if (Array.isArray(data.promet_po_mjesecima) && data.promet_po_mjesecima.length) {
          header.textContent = 'Promet po mjesecima';
          data.promet_po_mjesecima.forEach(r => {
              lista.innerHTML += `<li><strong>${r.mjesec}:</strong> ${fmtEUR(r.ukupno)} €</li>`;
          });
      } else {
          header.textContent = 'Provizija po mjesecima';
          (data.provizije_po_mjesecima || []).forEach(r => {
              lista.innerHTML += `<li><strong>${r.mjesec}:</strong> ${fmtEUR(r.osnova)} €</li>`;
          });
      }

      document.getElementById('modal').classList.remove('d-none');
    })
    .catch(e => {
      console.error(e);
      alert('Greška: ' + e.message);
      document.getElementById('izvjestajText').innerHTML = 'Greška pri dohvaćanju podataka.';
      document.getElementById('modal').classList.remove('d-none');
    });
}
<?php endif; ?>

<?php if ($IS_LIMITED): ?>
// --- AUTO 0.00 i readOnly za "Free najam" (LIMITED: 11, 12) ---
(function () {
  function wireFreeToggle(selectId, amountInputId) {
    const sel = document.getElementById(selectId);
    const amt = document.getElementById(amountInputId);
    if (!sel || !amt) return;

    const apply = () => {
      if (sel.value === 'free') {
        amt.value = '0.00';
        amt.readOnly = true;
        amt.classList.add('bg-light');
      } else {
        amt.readOnly = false;
        amt.classList.remove('bg-light');
      }
    };

    apply(); // inicijalno stanje (bitno za EDIT)
    sel.addEventListener('change', apply);
  }

  // CREATE forma
  wireFreeToggle('nacin_placanja', 'iznos');
  // EDIT forma
  wireFreeToggle('e_nacin_placanja', 'e_iznos');
})();
<?php endif; ?>
</script>

</body>
</html>