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

/* ----------------------------------------------------
   Timeout
-----------------------------------------------------*/
$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 ili Zagreb
-----------------------------------------------------*/
if (!isset($_SESSION['uloga']) && !isset($_SESSION['poslovnica_id'])) {
    exit("Pristup nije dozvoljen.");
}

$is_admin = (($_SESSION['uloga'] ?? '') === 'admin');
$zagreb_id = null;
$resZ = $conn->query("SELECT id FROM poslovnice WHERE naziv='Zagreb' LIMIT 1");
if ($resZ && $rowZ = $resZ->fetch_assoc()) {
    $zagreb_id = (int)$rowZ['id'];
}

if (!$is_admin) {
    $is_zagreb = (($_SESSION['naziv'] ?? '') === 'Zagreb');
    if (!$is_zagreb && $zagreb_id && isset($_SESSION['poslovnica_id'])) {
        $is_zagreb = ((int)$_SESSION['poslovnica_id'] === $zagreb_id);
    }
    if (!$is_zagreb) {
        exit("Pristup dozvoljen samo za poslovnicu Zagreb.");
    }
}

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

/* ----------------------------------------------------
   Djelatnici za dropdown
-----------------------------------------------------*/
$djelatnicizg = [];
$resD = $conn->query("SELECT ime FROM djelatnicizg ORDER BY ime ASC");
if ($resD) {
    while ($row = $resD->fetch_assoc()) {
        $djelatnicizg[] = $row['ime'];
    }
}

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

function current_script_url(): string
{
    $script = basename($_SERVER['PHP_SELF'] ?? 'walkin_zagreb.php');
    return $script !== '' ? $script : 'walkin_zagreb.php';
}

function redirect_back(string $msg = ''): void
{
    global $page;
    $qs = ['page' => $page];
    if ($msg !== '') { $qs['msg'] = $msg; }
    header('Location: ' . current_script_url() . '?' . http_build_query($qs));
    exit;
}

function page_link(int $p): string
{
    return current_script_url() . '?' . http_build_query(['page' => $p]);
}

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

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

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

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

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

    $djelatnik = trim($_POST['djelatnik'] ?? '');
    $datum_out = $_POST['datum_out'] ?? '';
    $datum_in = $_POST['datum_in'] ?? '';
    $ugovor = trim($_POST['broj_ugovora'] ?? '');
    $najam = (float)str_replace(',', '.', $_POST['cijena_najma'] ?? 0);
    $usluge = (float)str_replace(',', '.', $_POST['dodatne_usluge'] ?? 0);
    $ukupno = $najam + $usluge;

    if ($djelatnik === '' || $datum_out === '' || $datum_in === '' || $ugovor === '') {
        redirect_back("Molimo popunite sva obavezna polja.");
    }

    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE walkin SET djelatnik=?, datum_out=?, datum_in=?, broj_ugovora=?, cijena_najma=?, dodatne_usluge=?, ukupno=? WHERE id=?");
        $stmt->bind_param("ssssdddi", $djelatnik, $datum_out, $datum_in, $ugovor, $najam, $usluge, $ukupno, $id);
        $ok = $stmt->execute();
        $stmt->close();
        redirect_back($ok ? "Stavka je ažurirana." : "Greška pri spremanju.");
    }

    $stmt = $conn->prepare("INSERT INTO walkin (djelatnik, datum_out, datum_in, broj_ugovora, cijena_najma, dodatne_usluge, ukupno) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssddd", $djelatnik, $datum_out, $datum_in, $ugovor, $najam, $usluge, $ukupno);
    $ok = $stmt->execute();
    $stmt->close();
    redirect_back($ok ? "Stavka je dodana." : "Greška pri spremanju.");
}

/* ----------------------------------------------------
   EDIT prefill
-----------------------------------------------------*/
$edit_row = [
    'djelatnik' => '',
    'datum_out' => '',
    'datum_in' => '',
    'broj_ugovora' => '',
    'cijena_najma' => '',
    'dodatne_usluge' => ''
];

if ($edit_id > 0) {
    $stmt = $conn->prepare("SELECT * FROM walkin 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 podaci
-----------------------------------------------------*/
$whereSQL = "WHERE deleted_at IS NULL";
$per_page = 20;
$offset = ($page - 1) * $per_page;

$totalRes = $conn->query("SELECT COUNT(*) AS c FROM walkin $whereSQL");
$total = (int)($totalRes ? ($totalRes->fetch_assoc()['c'] ?? 0) : 0);

$rez = $conn->query("SELECT * FROM walkin $whereSQL ORDER BY id DESC LIMIT $per_page OFFSET $offset");

$total_pages = (int)ceil($total / $per_page);
?>
<!DOCTYPE html>
<html lang="hr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Walk In — Zagreb</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        :root {
            --bg: #f4f7fb;
            --card: #ffffff;
            --line: #dfe6f1;
            --muted: #6b778c;
            --text: #182033;
            --blue: #0d6efd;
        }
        * { 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;
        }
        .page-shell { max-width: 1480px; margin: 0 auto; padding: 22px; }
        .topbar, .panel, .table-card {
            background: var(--card);
            border: 1px solid var(--line);
            border-radius: 16px;
            box-shadow: 0 7px 24px rgba(24, 32, 51, .05);
        }
        .topbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 18px;
            padding: 16px 18px;
            margin-bottom: 18px;
        }
        .brand { display: flex; align-items: center; gap: 12px; }
        .brand-icon {
            width: 44px; height: 44px; border-radius: 13px;
            display: grid; place-items: center;
            background: #eaf2ff; color: var(--blue); font-size: 21px;
        }
        .brand h1 { font-size: 19px; margin: 0; font-weight: 800; }
        .brand p { margin: 2px 0 0; color: var(--muted); font-size: 13px; }
        .action-bar { display: flex; gap: 9px; flex-wrap: wrap; }
        .btn { border-radius: 10px; font-weight: 700; }
        .section-title { margin: 0 0 14px; font-size: 22px; font-weight: 800; }
        .panel { padding: 18px; margin-bottom: 18px; }
        .form-label { font-size: 12px; font-weight: 800; color: #34425a; margin-bottom: 6px; }
        .form-control, .form-select { border-radius: 10px; border-color: #d6deea; min-height: 42px; }
        .form-control:focus, .form-select:focus { border-color: #8db7ff; box-shadow: 0 0 0 .2rem rgba(13, 110, 253, .10); }
        .table-card { overflow: hidden; }
        .table-head {
            display: flex; align-items: center; justify-content: space-between;
            gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--line);
        }
        .table-head h2 { font-size: 15px; margin: 0; font-weight: 800; }
        .record-count { color: var(--muted); font-size: 12px; }
        .table-responsive { overflow-x: auto; }
        table { margin: 0 !important; min-width: 1050px; }
        thead th {
            background: #f5f8fc !important;
            color: #526079 !important;
            text-transform: uppercase;
            letter-spacing: .03em;
            font-size: 10px;
            font-weight: 800;
            border-bottom: 1px solid var(--line) !important;
            padding: 11px 14px !important;
            white-space: nowrap;
        }
        tbody td {
            font-size: 12.5px;
            padding: 11px 14px !important;
            border-color: #e7ecf3 !important;
            vertical-align: middle;
            white-space: nowrap;
        }
        tbody tr:hover td { background: #f8fbff; }
        .money { font-weight: 800; text-align: right; }
        .contract-badge {
            display: inline-flex; align-items: center;
            background: #eef4ff; color: #265da8;
            border-radius: 999px; padding: 4px 9px; font-weight: 800;
        }
        .row-actions { display: flex; gap: 7px; align-items: center; }
        .row-actions form { margin: 0; }
        .alert { border-radius: 12px; }
        .pagination { margin: 16px 0 0; }
        .page-link { border-radius: 9px !important; margin-right: 5px; }
        .empty-state { padding: 34px; text-align: center; color: var(--muted); }
        @media (max-width: 980px) {
            .topbar { align-items: flex-start; flex-direction: column; }
        }
        @media (max-width: 580px) {
            .page-shell { padding: 12px; }
            .action-bar { width: 100%; }
            .action-bar .btn { flex: 1; }
        }
    </style>
</head>
<body>
<div class="page-shell">

    <?php if (!$embed): ?>
    <div class="topbar">
        <div class="brand">
            <div class="brand-icon"><i class="bi bi-person-walking"></i></div>
            <div>
                <h1>Walk In — Zagreb</h1>
                <p>Unos i pregled direktnih najmova</p>
            </div>
        </div>
        <div class="action-bar">
            <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>
    </div>
    <?php endif; ?>

    <?php if ($embed): ?>
        <h1 class="section-title">Walk In — Zagreb</h1>
    <?php endif; ?>

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

    <div class="panel">
        <h2 class="section-title" style="font-size:18px;"><?= $edit_id > 0 ? 'Uredi Walk In' : 'Novi Walk In' ?></h2>
        <form method="POST" class="row g-3">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">
            <input type="hidden" name="akcija" value="save">
            <input type="hidden" name="id" value="<?= $edit_id > 0 ? (int)$edit_id : '' ?>">

            <div class="col-lg-3 col-md-6">
                <label class="form-label">Djelatnik</label>
                <select name="djelatnik" class="form-select" required>
                    <option value="">Odaberi djelatnika</option>
                    <?php foreach ($djelatnicizg as $d): ?>
                        <option value="<?= htmlspecialchars($d) ?>" <?= ($edit_row['djelatnik'] === $d) ? 'selected' : '' ?>><?= htmlspecialchars($d) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-lg-2 col-md-6">
                <label class="form-label">Datum OUT</label>
                <input type="date" name="datum_out" class="form-control" required value="<?= htmlspecialchars($edit_row['datum_out']) ?>">
            </div>
            <div class="col-lg-2 col-md-6">
                <label class="form-label">Datum IN</label>
                <input type="date" name="datum_in" class="form-control" required value="<?= htmlspecialchars($edit_row['datum_in']) ?>">
            </div>
            <div class="col-lg-2 col-md-6">
                <label class="form-label">Broj ugovora</label>
                <input type="text" name="broj_ugovora" class="form-control" required value="<?= htmlspecialchars($edit_row['broj_ugovora']) ?>">
            </div>
            <div class="col-lg-1 col-md-6">
                <label class="form-label">Najam €</label>
                <input type="number" name="cijena_najma" class="form-control" step="0.01" min="0" required value="<?= htmlspecialchars($edit_row['cijena_najma']) ?>">
            </div>
            <div class="col-lg-1 col-md-6">
                <label class="form-label">Dodatno €</label>
                <input type="number" name="dodatne_usluge" class="form-control" step="0.01" min="0" required value="<?= htmlspecialchars($edit_row['dodatne_usluge']) ?>">
            </div>
            <div class="col-lg-1 col-md-12 d-flex align-items-end gap-2">
                <button class="btn btn-primary w-100"><?= $edit_id > 0 ? 'Spremi' : 'Dodaj' ?></button>
            </div>
            <?php if ($edit_id > 0): ?>
            <div class="col-12">
                <a class="btn btn-outline-secondary" href="<?= htmlspecialchars(page_link(1)) ?>">Odustani od uređivanja</a>
            </div>
            <?php endif; ?>
        </form>
    </div>

    <div class="table-card">
        <div class="table-head">
            <h2>Evidencija Walk In najmova</h2>
            <span class="record-count"><?= number_format($total, 0, ',', '.') ?> zapisa</span>
        </div>
        <div class="table-responsive">
            <table class="table align-middle">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Djelatnik</th>
                        <th>Datum OUT</th>
                        <th>Datum IN</th>
                        <th>Ugovor</th>
                        <th class="text-end">Najam</th>
                        <th class="text-end">Dodatne</th>
                        <th class="text-end">Ukupno</th>
                        <th>Akcije</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($rez && $rez->num_rows > 0): ?>
                    <?php $rb = $offset + 1; while ($row = $rez->fetch_assoc()): ?>
                    <tr>
                        <td><?= $rb++ ?></td>
                        <td><strong><?= htmlspecialchars($row['djelatnik']) ?></strong></td>
                        <td><?= format_date_hr($row['datum_out']) ?></td>
                        <td><?= format_date_hr($row['datum_in']) ?></td>
                        <td><span class="contract-badge"><?= htmlspecialchars($row['broj_ugovora']) ?></span></td>
                        <td class="money"><?= number_format((float)$row['cijena_najma'], 2, ',', '.') ?> €</td>
                        <td class="money"><?= number_format((float)$row['dodatne_usluge'], 2, ',', '.') ?> €</td>
                        <td class="money"><?= number_format((float)$row['ukupno'], 2, ',', '.') ?> €</td>
                        <td>
                            <div class="row-actions">
                                <a class="btn btn-sm btn-outline-primary" href="<?= htmlspecialchars(current_script_url() . '?' . http_build_query(['page' => $page, 'edit_id' => (int)$row['id']])) ?>">Uredi</a>
                                <form method="POST" onsubmit="return confirm('Izbrisati ovu stavku?');">
                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($_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">Izbriši</button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="9" class="empty-state">Nema unesenih Walk In najmova.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

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

</div>
</body>
</html>