<?php
require_once '../config/db.php';
require_once '../config/auth.php';
require_once '../config/functions.php';
requireLogin();

$page_title = 'Search Items';
$q    = sanitize($conn, $_GET['q'] ?? '');
$type = $_GET['type'] ?? 'all';
$cat  = sanitize($conn, $_GET['category'] ?? '');

$lost_results = $found_results = null;
if ($q || $cat) {
    $where = "WHERE 1=1";
    if ($q)   $where .= " AND (item_name LIKE '%$q%' OR description LIKE '%$q%' OR location LIKE '%$q%')";
    if ($cat) $where .= " AND category='$cat'";
    if ($type === 'all' || $type === 'lost')
        $lost_results = $conn->query("SELECT l.*, u.name as reporter FROM lost_items l JOIN users u ON l.user_id=u.id $where ORDER BY l.created_at DESC");
    if ($type === 'all' || $type === 'found')
        $found_results = $conn->query("SELECT f.*, u.name as reporter FROM found_items f JOIN users u ON f.user_id=u.id $where ORDER BY f.created_at DESC");
}
$categories = $conn->query("SELECT name FROM categories ORDER BY name");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= $page_title ?> - RELINK</title>
<link rel="stylesheet" href="/lostfound_relink/assets/css/style.css">
<style>
.ac-wrap { position:relative; flex:1; min-width:200px; }
.ac-dropdown {
    display:none; position:absolute; top:calc(100% + 4px); left:0; right:0;
    background:var(--white); border:1px solid var(--border); border-radius:var(--radius-sm);
    box-shadow:var(--shadow-lg); z-index:999; max-height:340px; overflow-y:auto;
}
.ac-dropdown.open { display:block; }
.ac-group-label {
    padding:8px 14px 4px; font-size:10px; font-weight:700; text-transform:uppercase;
    letter-spacing:1px; color:var(--text-muted); background:var(--bg-secondary);
    border-bottom:1px solid var(--border-light);
}
.ac-item {
    display:flex; align-items:center; gap:10px; padding:10px 14px;
    cursor:pointer; transition:background .15s; border-bottom:1px solid var(--border-light);
}
.ac-item:last-child { border-bottom:none; }
.ac-item:hover, .ac-item.focused { background:var(--primary-lighter); }
.ac-item-img { width:38px; height:38px; border-radius:8px; object-fit:cover; flex-shrink:0; }
.ac-item-placeholder { width:38px; height:38px; border-radius:8px; background:var(--bg-secondary); display:flex; align-items:center; justify-content:center; font-size:18px; flex-shrink:0; }
.ac-item-name { font-size:13px; font-weight:600; color:var(--text); line-height:1.3; }
.ac-item-meta { font-size:11px; color:var(--text-muted); margin-top:2px; }
.ac-tag { font-size:10px; font-weight:700; padding:2px 8px; border-radius:20px; flex-shrink:0; margin-left:auto; }
.ac-tag.lost  { background:#fee2e2; color:#991b1b; }
.ac-tag.found { background:#d1fae5; color:#065f46; }
.ac-empty { padding:20px 14px; text-align:center; color:var(--text-muted); font-size:13px; }
.ac-loading { padding:14px; text-align:center; color:var(--text-muted); font-size:13px; }
body.dark-mode .ac-dropdown { background:var(--white); border-color:var(--border); }
body.dark-mode .ac-group-label { background:var(--bg-secondary); }
body.dark-mode .ac-item:hover, body.dark-mode .ac-item.focused { background:var(--primary-lighter); }
body.dark-mode .ac-item-name { color:var(--text); }
body.dark-mode .ac-item-placeholder { background:var(--bg-secondary); }
</style>
</head>
<body>
<div class="layout">
    <?php include '../includes/user_sidebar.php'; ?>
    <div class="main-content">
        <?php include '../includes/topbar.php'; ?>
        <div class="page-content">

            <div class="card mb-24">
                <div class="card-header"><h3>🔎 Search Items</h3></div>
                <div class="card-body">
                    <form method="GET" id="searchForm" class="search-bar" autocomplete="off">
                        <div class="ac-wrap">
                            <input type="text" name="q" id="searchInput" class="form-control"
                                placeholder="Search by item name, location..."
                                value="<?= htmlspecialchars($q) ?>" autocomplete="off">
                            <div class="ac-dropdown" id="acDropdown"></div>
                        </div>
                        <select name="category" class="form-control" style="max-width:160px">
                            <option value="">All Categories</option>
                            <?php while($c=$categories->fetch_assoc()): ?>
                            <option value="<?= $c['name'] ?>" <?= $cat===$c['name']?'selected':'' ?>><?= $c['name'] ?></option>
                            <?php endwhile; ?>
                        </select>
                        <select name="type" class="form-control" style="max-width:130px">
                            <option value="all"   <?= $type==='all'  ?'selected':'' ?>>All Items</option>
                            <option value="lost"  <?= $type==='lost' ?'selected':'' ?>>Lost Only</option>
                            <option value="found" <?= $type==='found'?'selected':'' ?>>Found Only</option>
                        </select>
                        <button type="submit" class="btn btn-primary">🔎 Search</button>
                        <?php if($q||$cat): ?><a href="search.php" class="btn btn-light">✕ Clear</a><?php endif; ?>
                    </form>
                </div>
            </div>

            <?php if(!$q && !$cat): ?>
            <div class="text-center" style="padding:64px 24px;color:var(--text-muted)">
                <div style="font-size:56px;margin-bottom:16px">🔎</div>
                <p style="font-size:16px;font-weight:600;margin-bottom:6px">Search for lost or found items</p>
                <p style="font-size:13px">Start typing in the search box — suggestions will appear automatically</p>
            </div>
            <?php else: ?>

            <?php if($lost_results && $lost_results->num_rows > 0): ?>
            <div class="card mb-24">
                <div class="card-header">
                    <h3>🔍 Lost Items</h3>
                    <span class="badge badge-pending"><?= $lost_results->num_rows ?> result<?= $lost_results->num_rows>1?'s':'' ?></span>
                </div>
                <div class="table-wrapper">
                    <table>
                        <thead><tr><th>Image</th><th>Item Name</th><th>Category</th><th>Location</th><th>Date Lost</th><th>Reporter</th><th>Status</th></tr></thead>
                        <tbody>
                        <?php while($item=$lost_results->fetch_assoc()): ?>
                        <tr>
                            <td><?php if($item['image_path']): ?><img src="/lostfound_relink/<?= htmlspecialchars($item['image_path']) ?>" class="img-preview"><?php else: ?>📷<?php endif; ?></td>
                            <td><strong><?= htmlspecialchars($item['item_name']) ?></strong><br><small class="text-muted"><?= htmlspecialchars(substr($item['description'],0,80)) ?></small></td>
                            <td><?= htmlspecialchars($item['category']) ?></td>
                            <td><?= htmlspecialchars($item['location']) ?></td>
                            <td><?= $item['date_lost'] ? date('M d, Y', strtotime($item['date_lost'])) : '-' ?></td>
                            <td><?= htmlspecialchars($item['reporter']) ?></td>
                            <td><span class="badge badge-<?= $item['status'] ?>"><?= $item['status'] ?></span></td>
                        </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php elseif($lost_results): ?>
            <div class="alert alert-info">No lost items found matching your search.</div>
            <?php endif; ?>

            <?php if($found_results && $found_results->num_rows > 0): ?>
            <div class="card">
                <div class="card-header">
                    <h3>📦 Found Items</h3>
                    <span class="badge badge-returned"><?= $found_results->num_rows ?> result<?= $found_results->num_rows>1?'s':'' ?></span>
                </div>
                <div class="table-wrapper">
                    <table>
                        <thead><tr><th>Image</th><th>Item Name</th><th>Category</th><th>Location</th><th>Date Found</th><th>Reporter</th><th>Status</th></tr></thead>
                        <tbody>
                        <?php while($item=$found_results->fetch_assoc()): ?>
                        <tr>
                            <td><?php if($item['image_path']): ?><img src="/lostfound_relink/<?= htmlspecialchars($item['image_path']) ?>" class="img-preview"><?php else: ?>📷<?php endif; ?></td>
                            <td><strong><?= htmlspecialchars($item['item_name']) ?></strong><br><small class="text-muted"><?= htmlspecialchars(substr($item['description'],0,80)) ?></small></td>
                            <td><?= htmlspecialchars($item['category']) ?></td>
                            <td><?= htmlspecialchars($item['location']) ?></td>
                            <td><?= $item['date_found'] ? date('M d, Y', strtotime($item['date_found'])) : '-' ?></td>
                            <td><?= htmlspecialchars($item['reporter']) ?></td>
                            <td><span class="badge badge-<?= $item['status'] ?>"><?= $item['status'] ?></span></td>
                        </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php elseif($found_results): ?>
            <div class="alert alert-info">No found items found matching your search.</div>
            <?php endif; ?>

            <?php endif; ?>
        </div>
    </div>
</div>
<script src="/lostfound_relink/assets/js/main.js"></script>
<script>
(function(){
    const input = document.getElementById('searchInput');
    const drop  = document.getElementById('acDropdown');
    let timer, focusIdx = -1, lastQ = '';

    function esc(s){ return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
    function close(){ drop.classList.remove('open'); focusIdx = -1; }

    function render(data){
        if(!data.length){ drop.innerHTML='<div class="ac-empty">No suggestions found</div>'; drop.classList.add('open'); return; }
        const lost  = data.filter(d=>d.type==='lost');
        const found = data.filter(d=>d.type==='found');
        let html = '';
        if(lost.length){
            html += '<div class="ac-group-label">🔍 Lost Items</div>';
            lost.forEach(d=>{
                const img = d.image ? `<img class="ac-item-img" src="/lostfound_relink/${esc(d.image)}">` : `<div class="ac-item-placeholder">🔍</div>`;
                html += `<div class="ac-item" data-val="${esc(d.name)}">${img}<div><div class="ac-item-name">${esc(d.name)}</div><div class="ac-item-meta">📍 ${esc(d.location)} · 📂 ${esc(d.category)}</div></div><span class="ac-tag lost">Lost</span></div>`;
            });
        }
        if(found.length){
            html += '<div class="ac-group-label">📦 Found Items</div>';
            found.forEach(d=>{
                const img = d.image ? `<img class="ac-item-img" src="/lostfound_relink/${esc(d.image)}">` : `<div class="ac-item-placeholder">📦</div>`;
                html += `<div class="ac-item" data-val="${esc(d.name)}">${img}<div><div class="ac-item-name">${esc(d.name)}</div><div class="ac-item-meta">📍 ${esc(d.location)} · 📂 ${esc(d.category)}</div></div><span class="ac-tag found">Found</span></div>`;
            });
        }
        drop.innerHTML = html;
        drop.classList.add('open');
        drop.querySelectorAll('.ac-item').forEach(el=>{
            el.addEventListener('mousedown', e=>{
                e.preventDefault();
                input.value = el.dataset.val;
                close();
                document.getElementById('searchForm').submit();
            });
        });
    }

    function suggest(q){
        if(q===lastQ) return; lastQ=q;
        drop.innerHTML='<div class="ac-loading">⏳ Searching...</div>';
        drop.classList.add('open');
        const xhr = new XMLHttpRequest();
        xhr.open('GET','/lostfound_relink/user/search_suggest.php?q='+encodeURIComponent(q));
        xhr.onload = ()=>{ try{ render(JSON.parse(xhr.responseText)); }catch(e){ close(); } };
        xhr.onerror = close;
        xhr.send();
    }

    input.addEventListener('input', ()=>{
        const q = input.value.trim();
        clearTimeout(timer);
        if(q.length < 2){ close(); lastQ=''; return; }
        timer = setTimeout(()=>suggest(q), 250);
    });

    input.addEventListener('keydown', e=>{
        const items = drop.querySelectorAll('.ac-item');
        if(e.key==='ArrowDown'){ e.preventDefault(); focusIdx=Math.min(focusIdx+1,items.length-1); }
        else if(e.key==='ArrowUp'){ e.preventDefault(); focusIdx=Math.max(focusIdx-1,-1); }
        else if(e.key==='Enter' && focusIdx>=0){ e.preventDefault(); input.value=items[focusIdx].dataset.val; close(); document.getElementById('searchForm').submit(); return; }
        else if(e.key==='Escape'){ close(); return; }
        items.forEach((el,i)=>el.classList.toggle('focused',i===focusIdx));
        if(focusIdx>=0) items[focusIdx].scrollIntoView({block:'nearest'});
    });

    document.addEventListener('click', e=>{ if(!e.target.closest('.ac-wrap')) close(); });
})();
</script>
</body>
</html>
