<?php

require_once __DIR__ . '/../lib/init.php';
Auth::requireLogin();

$term    = trim($_GET['q'] ?? '');
$results = $term !== '' ? Reservation::search($term) : [];

$page_title = 'Recherche';
require_once APP_ROOT . '/lib/layout_header.php';
?>

<div class="row justify-content-center mb-4">
<div class="col-lg-6">
    <form method="get" autocomplete="off" id="search-form">
        <div class="input-group">
            <span class="input-group-text"><i class="bi bi-search"></i></span>
            <input type="text" name="q" id="search-input" class="form-control form-control-lg"
                   value="<?= h($term) ?>"
                   placeholder="Hostname, MAC (bc:dd:… ou bc-dd-…) ou description…"
                   autofocus>
            <button type="submit" class="btn btn-primary">Rechercher</button>
        </div>
    </form>
    <div id="search-history" class="mt-2"></div>
</div>
</div>

<?php if ($term !== ''): ?>

<?php if (!$results): ?>
<div class="text-center text-muted py-5">
    <i class="bi bi-search fs-1"></i>
    <p class="mt-3">Aucun résultat pour <strong><?= h($term) ?></strong>.</p>
</div>

<?php else: ?>
<div class="card">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <span><i class="bi bi-search me-2"></i><?= count($results) ?> résultat<?= count($results) > 1 ? 's' : '' ?> pour <strong><?= h($term) ?></strong></span>
    </div>
    <div class="card-body p-0">
        <table class="table table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th>Hostname</th>
                    <th>Adresse IP</th>
                    <th>Adresse MAC</th>
                    <th>Subnet</th>
                    <th>Description</th>
                    <th style="width:110px"></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($results as $r): ?>
            <tr>
                <td class="fw-semibold">
                    <?= h($r['hostname']) ?>
                    <?php if ($r['has_options']): ?>
                    <i class="bi bi-sliders text-primary ms-1"
                       style="font-size:.8em"
                       data-bs-toggle="tooltip"
                       title="Options DHCP spécifiques (gateway / routes)"></i>
                    <?php endif; ?>
                    <?php if ($r['has_ntp']): ?>
                    <i class="bi bi-clock text-info ms-1"
                       style="font-size:.8em"
                       data-bs-toggle="tooltip"
                       title="NTP activé (option 42)"></i>
                    <?php endif; ?>
                    <?php if ($r['short_lease']): ?>
                    <i class="bi bi-hourglass-split text-warning ms-1"
                       style="font-size:.8em"
                       data-bs-toggle="tooltip"
                       title="Lease court (1h) — client class short-lease"></i>
                    <?php endif; ?>
                </td>
                <td><span class="ip-address"><?= h($r['ip_address']) ?></span></td>
                <td><span class="mac-address"><?= h($r['mac']) ?></span></td>
                <td>
                    <?php if ($r['subnet_app_id']): ?>
                    <a href="subnet.php?id=<?= (int)$r['subnet_app_id'] ?>"
                       class="badge bg-secondary text-decoration-none">
                        <?= h($r['subnet_name']) ?>
                    </a>
                    <?php else: ?>
                    <span class="text-muted"><?= h($r['subnet_name']) ?></span>
                    <?php endif; ?>
                </td>
                <td><small class="text-muted"><?= h($r['description'] ?? '') ?></small></td>
                <td class="text-end">
                    <?php if (Auth::currentUserRole() !== 'viewer'): ?>
                    <a href="reservation_edit.php?id=<?= $r['host_id'] ?>&subnet_id=<?= (int)$r['subnet_app_id'] ?>"
                       class="btn btn-sm btn-outline-secondary me-1" title="Modifier">
                        <i class="bi bi-pencil"></i>
                    </a>
                    <a href="reservation_delete.php?id=<?= $r['host_id'] ?>&subnet_id=<?= (int)$r['subnet_app_id'] ?>"
                       class="btn btn-sm btn-outline-danger" title="Supprimer">
                        <i class="bi bi-trash"></i>
                    </a>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<?php endif; ?>

<?php require_once APP_ROOT . '/lib/layout_footer.php'; ?>
<script>
document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function (el) {
    new bootstrap.Tooltip(el);
});

(function () {
    var STORAGE_KEY = 'dhcpman_search_history';
    var MAX_ITEMS   = 10;
    var container   = document.getElementById('search-history');
    var form        = document.getElementById('search-form');
    var input       = document.getElementById('search-input');
    var currentTerm = <?= json_encode($term) ?>;

    function load() {
        try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); }
        catch (e) { return []; }
    }

    function save(history) {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(history));
    }

    function push(term) {
        term = term.trim();
        if (!term) return;
        var history = load().filter(function (t) { return t.toLowerCase() !== term.toLowerCase(); });
        history.unshift(term);
        if (history.length > MAX_ITEMS) history = history.slice(0, MAX_ITEMS);
        save(history);
    }

    function remove(term) {
        save(load().filter(function (t) { return t !== term; }));
        render();
    }

    function render() {
        var history = load();
        container.innerHTML = '';
        if (!history.length) return;

        var wrap = document.createElement('div');
        wrap.className = 'd-flex flex-wrap align-items-center gap-1';

        var label = document.createElement('small');
        label.className = 'text-muted me-1';
        label.textContent = 'Récent :';
        wrap.appendChild(label);

        history.forEach(function (term) {
            var badge = document.createElement('span');
            badge.className = 'badge rounded-pill bg-light text-dark border d-inline-flex align-items-center gap-1';
            badge.style.cursor = 'pointer';

            var text = document.createElement('span');
            text.textContent = term;
            text.addEventListener('click', function () {
                input.value = term;
                form.submit();
            });

            var del = document.createElement('button');
            del.type = 'button';
            del.className = 'btn-close btn-close-sm';
            del.style.cssText = 'font-size:.55rem;opacity:.4';
            del.setAttribute('aria-label', 'Supprimer');
            del.addEventListener('click', function (e) {
                e.stopPropagation();
                remove(term);
            });

            badge.appendChild(text);
            badge.appendChild(del);
            wrap.appendChild(badge);
        });

        var clearBtn = document.createElement('button');
        clearBtn.type = 'button';
        clearBtn.className = 'btn btn-link btn-sm text-muted p-0 ms-1';
        clearBtn.style.fontSize = '.75rem';
        clearBtn.textContent = 'Tout effacer';
        clearBtn.addEventListener('click', function () {
            save([]);
            render();
        });
        wrap.appendChild(clearBtn);

        container.appendChild(wrap);
    }

    // Enregistrer le terme courant au chargement si une recherche vient d'être faite
    if (currentTerm) push(currentTerm);

    render();
}());
</script>
