<?php
// afterhour_zagreb.php
session_start();
$embed = isset($_GET['embed']) ? 1 : 0;

/* ----------------------------------------------------
   Timeout (30 minuta)
-----------------------------------------------------*/
$timeout = 1800;
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();

/* ----------------------------------------------------
   DB konekcija
-----------------------------------------------------*/
$conn = new mysqli("localhost", "carsfory_locis", "8QYP2!S?ONk1HQ5_", "carsfory_locis");
if ($conn->connect_error) {
    exit("DB greška.");
}
$conn->set_charset('utf8mb4');

/* ----------------------------------------------------
   Dozvole: admin uvijek smije ući.
   Ne-admin smije samo za poslovnicu Zagreb.
-----------------------------------------------------*/
if (!isset($_SESSION['uloga'])) {
    exit("Pristup nije dozvoljen.");
}
$is_admin = ($_SESSION['uloga'] === 'admin');

$zagreb_id = null;
$res = $conn->query("SELECT id FROM poslovnice WHERE naziv='Zagreb' LIMIT 1");
if ($res && $row = $res->fetch_assoc()) {
    $zagreb_id = (int)$row['id'];
}

if ($is_admin && isset($_GET['poslovnica'])) {
    $_SESSION['poslovnica_id'] = (int)$_GET['poslovnica'];
    if ($zagreb_id && (int)$_GET['poslovnica'] === $zagreb_id) {
        $_SESSION['naziv'] = 'Zagreb';
    }
}

if (!$is_admin) {
    $ok_zagreb = false;

    if (isset($_SESSION['naziv']) && strcasecmp((string)$_SESSION['naziv'], 'Zagreb') === 0) {
        $ok_zagreb = true;
    }

    if (!$ok_zagreb && $zagreb_id && isset($_SESSION['poslovnica_id']) && (int)$_SESSION['poslovnica_id'] === $zagreb_id) {
        $ok_zagreb = true;
    }

    if (!$ok_zagreb) {
        exit("Pristup dozvoljen samo za poslovnicu Zagreb.");
    }
}

/* CSRF */
if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(16));
}

/* Parametri */
$edit_id = isset($_GET['edit_id']) ? (int)$_GET['edit_id'] : 0;
$msg = (string)($_GET['msg'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));

// Filter je dostupan samo administratoru i filtrira isključivo po datumu povrata.
$mjesec_povrata = $is_admin ? trim((string)($_GET['mjesec_povrata'] ?? '')) : '';
if ($mjesec_povrata !== '' && !preg_match('/^\d{4}-\d{2}$/', $mjesec_povrata)) {
    $mjesec_povrata = '';
}

$dozvoljeni_tipovi = ['Najam', 'Povrat'];
$dozvoljene_usluge = ['Dan', 'Noc'];

function h($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function format_date_hr(?string $date): string
{
    if (!$date || $date === '0000-00-00') {
        return '—';
    }
    $ts = strtotime($date);
    return $ts ? date('d.m.Y.', $ts) : '—';
}

function redirect_with_filters(string $message = ''): void
{
    global $embed, $is_admin, $zagreb_id, $mjesec_povrata;
    $qs = ['page' => 1];
    if ($embed) {
        $qs['embed'] = 1;
    }
    if ($is_admin && $zagreb_id) {
        $qs['poslovnica'] = $zagreb_id;
    }
    if ($is_admin && $mjesec_povrata !== '') {
        $qs['mjesec_povrata'] = $mjesec_povrata;
    }
    if ($message !== '') {
        $qs['msg'] = $message;
    }
    header('Location: ?' . http_build_query($qs));
    exit();
}

function page_link(int $p): string
{
    global $embed, $is_admin, $zagreb_id, $mjesec_povrata;
    $qs = [
        'page' => $p,
    ];
    if ($embed) {
        $qs['embed'] = 1;
    }
    if ($is_admin && $zagreb_id) {
        $qs['poslovnica'] = $zagreb_id;
    }
    if ($is_admin && $mjesec_povrata !== '') {
        $qs['mjesec_povrata'] = $mjesec_povrata;
    }
    return '?' . http_build_query($qs);
}

/* ----------------------------------------------------
   POST: insert / update / delete / restore
-----------------------------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf']) || !hash_equals($_SESSION['csrf'], (string)$_POST['csrf'])) {
        exit("Nevažeći CSRF token.");
    }

    $akcija = (string)($_POST['akcija'] ?? 'save');
    $id = (int)($_POST['id'] ?? 0);

    if ($akcija === 'delete') {
        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE afterhour SET deleted_at=NOW() WHERE id=? AND deleted_at IS NULL");
            $stmt->bind_param('i', $id);
            $ok = $stmt->execute();
            $stmt->close();
            redirect_with_filters($ok ? "Stavka je obrisana." : "Greška pri brisanju.");
        }
        redirect_with_filters("Neispravan ID.");
    }

    if ($akcija === 'restore') {
        if ($id > 0) {
            $stmt = $conn->prepare("UPDATE afterhour SET deleted_at=NULL WHERE id=? AND deleted_at IS NOT NULL");
            $stmt->bind_param('i', $id);
            $ok = $stmt->execute();
            $stmt->close();
            redirect_with_filters($ok ? "Stavka je vraćena." : "Greška pri vraćanju.");
        }
        redirect_with_filters("Neispravan ID.");
    }

    $datum = trim((string)($_POST['datum'] ?? ''));
    $datum_povrata = trim((string)($_POST['datum_povrata'] ?? ''));
    $djelatnik = trim((string)($_POST['djelatnik'] ?? ''));
    $ugovor = trim((string)($_POST['broj_ugovora'] ?? ''));
    $tip = in_array($_POST['tip'] ?? '', $dozvoljeni_tipovi, true) ? (string)$_POST['tip'] : 'Najam';
    $usluga = in_array($_POST['usluga'] ?? '', $dozvoljene_usluge, true) ? (string)$_POST['usluga'] : 'Dan';
    $iznos = ($usluga === 'Dan') ? 10.00 : 20.00;

    if ($datum === '' || $djelatnik === '' || $ugovor === '') {
        redirect_with_filters("Datum, djelatnik i broj ugovora su obavezni.");
    }

    if ($tip === 'Povrat' && $datum_povrata === '') {
        redirect_with_filters("Za tip Povrat potrebno je upisati datum povrata.");
    }

    // Za najam je datum povrata opcionalan; prazna vrijednost sprema se kao NULL.
    $datum_povrata_db = ($datum_povrata !== '') ? $datum_povrata : null;

    if ($id > 0) {
        $stmt = $conn->prepare(
            "UPDATE afterhour
             SET datum=?, datum_povrata=?, djelatnik=?, broj_ugovora=?, tip=?, usluga=?, iznos=?
             WHERE id=?"
        );
        $stmt->bind_param('ssssssdi', $datum, $datum_povrata_db, $djelatnik, $ugovor, $tip, $usluga, $iznos, $id);
        $ok = $stmt->execute();
        $stmt->close();
        redirect_with_filters($ok ? "Stavka je ažurirana." : "Greška pri spremanju.");
    }

    $stmt = $conn->prepare(
        "INSERT INTO afterhour (datum, datum_povrata, djelatnik, broj_ugovora, tip, usluga, iznos)
         VALUES (?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->bind_param('ssssssd', $datum, $datum_povrata_db, $djelatnik, $ugovor, $tip, $usluga, $iznos);
    $ok = $stmt->execute();
    $stmt->close();
    redirect_with_filters($ok ? "Stavka je dodana." : "Greška pri spremanju.");
}

/* ----------------------------------------------------
   Prikaz zapisa. Administrator može filtrirati prema
   mjesecu iz polja datum_povrata. Korisnik Zagreba vidi sve.
-----------------------------------------------------*/
$where = ["deleted_at IS NULL"];
if ($is_admin && $mjesec_povrata !== '') {
    $safe_month = $conn->real_escape_string($mjesec_povrata);
    $where[] = "DATE_FORMAT(datum_povrata, '%Y-%m') = '{$safe_month}'";
}
$whereSQL = "WHERE " . implode(" AND ", $where);

/* ----------------------------------------------------
   EDIT prefill
-----------------------------------------------------*/
$edit_row = [
    'datum' => date('Y-m-d'),
    'datum_povrata' => '',
    'djelatnik' => '',
    'broj_ugovora' => '',
    'tip' => 'Najam',
    'usluga' => 'Dan',
];

if ($edit_id > 0) {
    $stmt = $conn->prepare("SELECT * FROM afterhour WHERE id=? AND deleted_at IS NULL");
    $stmt->bind_param('i', $edit_id);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res && $res->num_rows === 1) {
        $edit_row = $res->fetch_assoc();
    } else {
        $edit_id = 0;
    }
    $stmt->close();
}

/* ----------------------------------------------------
   Paginacija i lista
-----------------------------------------------------*/
$per_page = 20;
$offset = ($page - 1) * $per_page;

$total_row = $conn->query("SELECT COUNT(*) AS c FROM afterhour {$whereSQL}");
$total = (int)($total_row ? ($total_row->fetch_assoc()['c'] ?? 0) : 0);
$total_pages = max(1, (int)ceil($total / $per_page));
if ($page > $total_pages) {
    $page = $total_pages;
    $offset = ($page - 1) * $per_page;
}

$rez = $conn->query(
    "SELECT * FROM afterhour {$whereSQL}
     ORDER BY
       COALESCE(datum_povrata, datum) DESC,
       id DESC
     LIMIT {$per_page} OFFSET {$offset}"
);

/* ----------------------------------------------------
   Statistike
-----------------------------------------------------*/
$stats = [
    'najmovi' => 0,
    'povrati' => 0,
    'dan' => 0,
    'noc' => 0,
    'ukupno' => 0.0,
];

$stats_res = $conn->query(
    "SELECT
        SUM(CASE WHEN tip='Najam' THEN 1 ELSE 0 END) AS najmovi,
        SUM(CASE WHEN tip='Povrat' THEN 1 ELSE 0 END) AS povrati,
        SUM(CASE WHEN usluga='Dan' THEN 1 ELSE 0 END) AS dan,
        SUM(CASE WHEN usluga='Noc' THEN 1 ELSE 0 END) AS noc,
        COALESCE(SUM(iznos), 0) AS ukupno
     FROM afterhour {$whereSQL}"
);
if ($stats_res && $s = $stats_res->fetch_assoc()) {
    $stats['najmovi'] = (int)($s['najmovi'] ?? 0);
    $stats['povrati'] = (int)($s['povrati'] ?? 0);
    $stats['dan'] = (int)($s['dan'] ?? 0);
    $stats['noc'] = (int)($s['noc'] ?? 0);
    $stats['ukupno'] = (float)($s['ukupno'] ?? 0);
}

$povrati_u_mjesecu = $stats['povrati'];

$zbroj_po_djelatniku = [];
$sve = $conn->query(
    "SELECT djelatnik, COUNT(*) AS broj, SUM(iznos) AS total
     FROM afterhour {$whereSQL}
     GROUP BY djelatnik
     ORDER BY total DESC, djelatnik ASC"
);
if ($sve) {
    while ($r = $sve->fetch_assoc()) {
        $zbroj_po_djelatniku[] = $r;
    }
}
?>
<!DOCTYPE html>
<html lang="hr">
<head>
    <title>Afterhour — Zagreb</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <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;800&display=swap" rel="stylesheet">
    <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">
    <style>
        :root {
            --bg: #f4f7fb;
            --card: #ffffff;
            --line: #dfe6f1;
            --muted: #64748b;
            --text: #0f172a;
            --blue: #0d6efd;
            --blue-soft: #eef5ff;
            --amber-soft: #fff5df;
            --amber: #b66a00;
            --violet-soft: #f2efff;
            --violet: #6554c0;
            --green-soft: #eaf8f0;
            --green: #11864b;
        }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            background: var(--bg);
            color: var(--text);
            font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
            font-size: 14px;
        }
        .page-shell {
            width: min(1500px, calc(100% - 32px));
            margin: 22px auto 42px;
        }
        .topbar,
        .panel,
        .stat-card,
        .table-card {
            background: var(--card);
            border: 1px solid var(--line);
            box-shadow: 0 8px 24px rgba(15, 23, 42, .045);
        }
        .topbar {
            border-radius: 18px;
            padding: 16px 18px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            margin-bottom: 18px;
        }
        .brand {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .brand-icon {
            width: 44px;
            height: 44px;
            border-radius: 13px;
            background: linear-gradient(135deg, #0d6efd, #2f80ed);
            color: #fff;
            display: grid;
            place-items: center;
            font-size: 20px;
            box-shadow: 0 8px 16px rgba(13, 110, 253, .22);
        }
        .brand h1 {
            font-size: 18px;
            font-weight: 800;
            margin: 0;
        }
        .brand p {
            color: var(--muted);
            font-size: 12px;
            margin: 3px 0 0;
        }
        .top-actions { display: flex; gap: 8px; flex-wrap: wrap; }
        .btn { border-radius: 10px; font-weight: 600; }
        .panel {
            border-radius: 16px;
            padding: 18px;
            margin-bottom: 16px;
        }
        .panel-title {
            font-size: 15px;
            font-weight: 800;
            margin: 0 0 14px;
        }
        .field-label {
            display: block;
            font-size: 11px;
            color: #475569;
            font-weight: 700;
            margin: 0 0 6px;
            text-transform: uppercase;
            letter-spacing: .035em;
        }
        .form-control,
        .form-select {
            min-height: 42px;
            border-color: #d6deea;
            border-radius: 10px;
            font-size: 13px;
        }
        .form-control:focus,
        .form-select:focus {
            border-color: #8db8ff;
            box-shadow: 0 0 0 .2rem rgba(13, 110, 253, .10);
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(5, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 16px;
        }
        .stat-card {
            border-radius: 14px;
            padding: 13px 14px;
            display: flex;
            align-items: center;
            gap: 11px;
            min-height: 76px;
        }
        .stat-icon {
            width: 38px;
            height: 38px;
            border-radius: 11px;
            display: grid;
            place-items: center;
            background: var(--blue-soft);
            color: var(--blue);
            font-size: 17px;
            flex: 0 0 auto;
        }
        .stat-card:nth-child(2) .stat-icon { background: var(--violet-soft); color: var(--violet); }
        .stat-card:nth-child(3) .stat-icon { background: var(--amber-soft); color: var(--amber); }
        .stat-card:nth-child(4) .stat-icon { background: #edf7ff; color: #1874a9; }
        .stat-card:nth-child(5) .stat-icon { background: var(--green-soft); color: var(--green); }
        .stat-label { color: var(--muted); font-size: 11px; margin-bottom: 2px; }
        .stat-value { font-size: 17px; font-weight: 800; line-height: 1.1; }
        .table-card {
            border-radius: 16px;
            overflow: hidden;
            margin-bottom: 16px;
        }
        .table-head {
            padding: 14px 16px;
            border-bottom: 1px solid var(--line);
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
        }
        .table-head h2 { font-size: 14px; font-weight: 800; margin: 0; }
        .table-head span { color: var(--muted); font-size: 12px; }
        .table-responsive { overflow-x: auto; }
        .data-table {
            width: 100%;
            min-width: 1060px;
            border-collapse: collapse;
            margin: 0;
        }
        .data-table thead th {
            background: #f4f7fb;
            color: #52617a;
            font-size: 10px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: .035em;
            padding: 11px 12px;
            border-bottom: 1px solid var(--line);
            white-space: nowrap;
        }
        .data-table tbody td {
            padding: 10px 12px;
            border-bottom: 1px solid #e8edf5;
            font-size: 12px;
            vertical-align: middle;
        }
        .data-table tbody tr:hover { background: #f8fbff; }
        .data-table tbody tr:last-child td { border-bottom: 0; }
        .badge-soft {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 5px 8px;
            border-radius: 999px;
            font-size: 10px;
            font-weight: 800;
            white-space: nowrap;
        }
        .badge-najam { background: #eaf3ff; color: #0866d6; }
        .badge-povrat { background: #f1edff; color: #6548c4; }
        .badge-dan { background: #fff3d7; color: #a86200; }
        .badge-noc { background: #edf0f8; color: #4a5872; }
        .amount { font-weight: 800; text-align: right; white-space: nowrap; }
        .action-cell { display: flex; gap: 6px; align-items: center; white-space: nowrap; }
        .action-cell .btn { padding: 5px 8px; font-size: 11px; border-radius: 8px; }
        .empty-state { padding: 42px 20px !important; color: var(--muted); text-align: center; }
        .pagination { margin: 0; }
        .pagination .page-link { font-size: 12px; border-radius: 8px; margin: 0 2px; color: #334155; }
        .worker-list { display: grid; grid-template-columns: repeat(3, minmax(180px, 1fr)); gap: 8px; }
        .worker-row {
            border: 1px solid var(--line);
            border-radius: 11px;
            padding: 10px 12px;
            display: flex;
            justify-content: space-between;
            gap: 12px;
            background: #fbfcfe;
        }
        .worker-row small { color: var(--muted); display: block; }
        .worker-total { font-weight: 800; white-space: nowrap; }
        @media (max-width: 1080px) {
            .stats-grid { grid-template-columns: repeat(3, 1fr); }
            .worker-list { grid-template-columns: repeat(2, 1fr); }
        }
        @media (max-width: 720px) {
            .page-shell { width: min(100% - 18px, 1500px); margin-top: 10px; }
            .topbar { align-items: flex-start; flex-direction: column; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
            .worker-list { grid-template-columns: 1fr; }
        }
        @media (max-width: 480px) {
            .stats-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
<div class="page-shell">

<?php if (!$embed): ?>
    <header class="topbar">
        <div class="brand">
            <div class="brand-icon"><i class="bi bi-clock-history"></i></div>
            <div>
                <h1>Afterhour — Zagreb</h1>
                <p>Evidencija najmova i povrata izvan radnog vremena</p>
            </div>
        </div>
        <div class="top-actions">
            <a href="dashboard.php" class="btn btn-outline-primary">
                <i class="bi bi-house-door me-1"></i>Početna
            </a>
            <a href="logout.php" class="btn btn-outline-danger">
                <i class="bi bi-box-arrow-right me-1"></i>Odjava
            </a>
        </div>
    </header>
<?php endif; ?>

<?php if ($msg !== ''): ?>
    <div class="alert alert-info border-0 shadow-sm rounded-3"><?= h($msg) ?></div>
<?php endif; ?>

<?php if ($is_admin): ?>
<section class="panel">
    <h2 class="panel-title">Filter po datumu povrata</h2>
    <form method="GET" class="row g-3 align-items-end">
        <?php if ($embed): ?><input type="hidden" name="embed" value="1"><?php endif; ?>
        <?php if ($zagreb_id): ?><input type="hidden" name="poslovnica" value="<?= (int)$zagreb_id ?>"><?php endif; ?>
        <div class="col-md-4 col-lg-3">
            <label class="field-label" for="mjesec_povrata">Mjesec povrata</label>
            <input type="month" id="mjesec_povrata" name="mjesec_povrata" class="form-control" value="<?= h($mjesec_povrata) ?>">
        </div>
        <div class="col-auto d-flex gap-2">
            <button class="btn btn-primary"><i class="bi bi-funnel me-1"></i>Filtriraj</button>
            <a class="btn btn-outline-secondary" href="?<?= h(http_build_query(array_filter(['embed' => $embed ? 1 : null, 'poslovnica' => $zagreb_id ?: null]))) ?>">Poništi</a>
        </div>
    </form>
</section>
<?php endif; ?>

<section class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon"><i class="bi bi-car-front"></i></div>
        <div><div class="stat-label">Najmova</div><div class="stat-value"><?= $stats['najmovi'] ?></div></div>
    </div>
    <div class="stat-card">
        <div class="stat-icon"><i class="bi bi-arrow-return-left"></i></div>
        <div><div class="stat-label">Povrata</div><div class="stat-value"><?= $povrati_u_mjesecu ?></div></div>
    </div>
    <div class="stat-card">
        <div class="stat-icon"><i class="bi bi-sun"></i></div>
        <div><div class="stat-label">Dan</div><div class="stat-value"><?= $stats['dan'] ?></div></div>
    </div>
    <div class="stat-card">
        <div class="stat-icon"><i class="bi bi-moon-stars"></i></div>
        <div><div class="stat-label">Noć</div><div class="stat-value"><?= $stats['noc'] ?></div></div>
    </div>
    <div class="stat-card">
        <div class="stat-icon"><i class="bi bi-cash-stack"></i></div>
        <div><div class="stat-label">Ukupno</div><div class="stat-value"><?= number_format($stats['ukupno'], 2, ',', '.') ?> €</div></div>
    </div>
</section>

<section class="panel">
    <h2 class="panel-title"><?= $edit_id > 0 ? 'Uredi afterhour zapis' : 'Novi afterhour zapis' ?></h2>
    <form method="POST" class="row g-3" id="afterhourForm">
        <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
        <input type="hidden" name="akcija" value="save">
        <input type="hidden" name="id" value="<?= $edit_id > 0 ? (int)$edit_id : '' ?>">

        <div class="col-xl-2 col-md-4">
            <label class="field-label" for="datum">Datum najma / događaja</label>
            <input type="date" id="datum" name="datum" class="form-control" required value="<?= h($edit_row['datum'] ?? '') ?>">
        </div>

        <div class="col-xl-2 col-md-4">
            <label class="field-label" for="datum_povrata">Datum povrata</label>
            <input type="date" id="datum_povrata" name="datum_povrata" class="form-control" value="<?= h($edit_row['datum_povrata'] ?? '') ?>">
        </div>

        <div class="col-xl-2 col-md-4">
            <label class="field-label" for="djelatnik">Djelatnik</label>
            <input type="text" id="djelatnik" name="djelatnik" class="form-control" placeholder="Ime djelatnika" required value="<?= h($edit_row['djelatnik'] ?? '') ?>">
        </div>

        <div class="col-xl-2 col-md-4">
            <label class="field-label" for="broj_ugovora">Broj ugovora</label>
            <input type="text" id="broj_ugovora" name="broj_ugovora" class="form-control" placeholder="Broj ugovora" required value="<?= h($edit_row['broj_ugovora'] ?? '') ?>">
        </div>

        <div class="col-xl-2 col-md-4">
            <label class="field-label" for="tip">Tip</label>
            <select id="tip" name="tip" class="form-select">
                <?php foreach ($dozvoljeni_tipovi as $t): ?>
                    <option value="<?= h($t) ?>" <?= (($edit_row['tip'] ?? '') === $t) ? 'selected' : '' ?>><?= h($t) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-xl-2 col-md-4">
            <label class="field-label" for="usluga">Usluga</label>
            <select id="usluga" name="usluga" class="form-select">
                <?php foreach ($dozvoljene_usluge as $u): ?>
                    <option value="<?= h($u) ?>" <?= (($edit_row['usluga'] ?? '') === $u) ? 'selected' : '' ?>><?= $u === 'Noc' ? 'Noć — 20 €' : 'Dan — 10 €' ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-12 d-flex gap-2 justify-content-end">
            <?php if ($edit_id > 0): ?>
                <a class="btn btn-outline-secondary" href="<?= h(page_link(1)) ?>">Odustani</a>
            <?php endif; ?>
            <button class="btn btn-primary px-4">
                <i class="bi bi-check2-circle me-1"></i><?= $edit_id > 0 ? 'Spremi izmjene' : 'Spremi zapis' ?>
            </button>
        </div>
    </form>
</section>

<section class="table-card">
    <div class="table-head">
        <h2>Evidencija afterhoura</h2>
        <span><?= $total ?> <?= $total === 1 ? 'zapis' : 'zapisa' ?></span>
    </div>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Datum</th>
                    <th>Datum povrata</th>
                    <th>Djelatnik</th>
                    <th>Ugovor</th>
                    <th>Tip</th>
                    <th>Usluga</th>
                    <th class="text-end">Iznos</th>
                    <th>Akcije</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($rez && $rez->num_rows > 0): ?>
                <?php $redni = $offset + 1; ?>
                <?php while ($row = $rez->fetch_assoc()): ?>
                    <tr>
                        <td><?= $redni++ ?></td>
                        <td><?= h(format_date_hr($row['datum'] ?? null)) ?></td>
                        <td><?= h(format_date_hr($row['datum_povrata'] ?? null)) ?></td>
                        <td><strong><?= h($row['djelatnik']) ?></strong></td>
                        <td><?= h($row['broj_ugovora']) ?></td>
                        <td>
                            <span class="badge-soft <?= $row['tip'] === 'Povrat' ? 'badge-povrat' : 'badge-najam' ?>">
                                <i class="bi <?= $row['tip'] === 'Povrat' ? 'bi-arrow-return-left' : 'bi-car-front' ?>"></i>
                                <?= h($row['tip']) ?>
                            </span>
                        </td>
                        <td>
                            <span class="badge-soft <?= $row['usluga'] === 'Noc' ? 'badge-noc' : 'badge-dan' ?>">
                                <i class="bi <?= $row['usluga'] === 'Noc' ? 'bi-moon-stars' : 'bi-sun' ?>"></i>
                                <?= $row['usluga'] === 'Noc' ? 'Noć' : 'Dan' ?>
                            </span>
                        </td>
                        <td class="amount"><?= number_format((float)$row['iznos'], 2, ',', '.') ?> €</td>
                        <td>
                            <div class="action-cell">
                                <?php
                                $qs = [
                                    'page' => $page,
                                    'edit_id' => (int)$row['id'],
                                ];
                                if ($embed) { $qs['embed'] = 1; }
                                if ($is_admin && $zagreb_id) { $qs['poslovnica'] = $zagreb_id; }
                                if ($is_admin && $mjesec_povrata !== '') { $qs['mjesec_povrata'] = $mjesec_povrata; }
                                ?>
                                <a class="btn btn-sm btn-outline-primary" href="?<?= h(http_build_query($qs)) ?>">
                                    <i class="bi bi-pencil-square"></i> Uredi
                                </a>
                                <form method="POST" onsubmit="return confirm('Izbrisati ovu stavku?');" class="d-inline">
                                    <input type="hidden" name="csrf" value="<?= h($_SESSION['csrf']) ?>">
                                    <input type="hidden" name="akcija" value="delete">
                                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                    <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i> Izbriši</button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="9" class="empty-state"><i class="bi bi-inbox fs-3 d-block mb-2"></i>Nema evidentiranih zapisa.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</section>

<?php if ($total_pages > 1): ?>
<nav class="mb-3" aria-label="Paginacija">
    <ul class="pagination justify-content-center">
        <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
            <a class="page-link" href="<?= h(page_link(max(1, $page - 1))) ?>">«</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="<?= h(page_link($p)) ?>"><?= $p ?></a>
            </li>
        <?php endfor; ?>
        <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
            <a class="page-link" href="<?= h(page_link(min($total_pages, $page + 1))) ?>">»</a>
        </li>
    </ul>
</nav>
<?php endif; ?>

<?php if (!empty($zbroj_po_djelatniku)): ?>
<section class="panel">
    <h2 class="panel-title">Ukupno po djelatniku</h2>
    <div class="worker-list">
        <?php foreach ($zbroj_po_djelatniku as $radnik): ?>
            <div class="worker-row">
                <div>
                    <strong><?= h($radnik['djelatnik']) ?></strong>
                    <small><?= (int)$radnik['broj'] ?> <?= (int)$radnik['broj'] === 1 ? 'zapis' : 'zapisa' ?></small>
                </div>
                <div class="worker-total"><?= number_format((float)$radnik['total'], 2, ',', '.') ?> €</div>
            </div>
        <?php endforeach; ?>
    </div>
</section>
<?php endif; ?>

</div>
<script>
(function () {
    const tip = document.getElementById('tip');
    const povrat = document.getElementById('datum_povrata');

    function updateReturnRequirement() {
        if (!tip || !povrat) return;
        const isReturn = tip.value === 'Povrat';
        povrat.required = isReturn;
        povrat.closest('div').querySelector('.field-label').textContent = isReturn
            ? 'Datum povrata *'
            : 'Datum povrata';
    }

    if (tip) {
        tip.addEventListener('change', updateReturnRequirement);
        updateReturnRequirement();
    }
})();
</script>
</body>
</html>