<?php
session_start();
//if (!isset($_SESSION['user_id'])) {
//    echo "User not logged in.";
//    exit();
//}

$user_id = $_SESSION['user_id'];
echo "Current logged-in user: " . $user_id;

$host   = "webdev.iyaserver.com";
$userid = "dhreid_guest";
$userpw = "tPTG;A+J{]Ze";
$db     = "dhreid_marketplace";

$mysql = new mysqli($host, $userid, $userpw, $db);
if($mysql->connect_errno){
    echo "db connection error : " . $mysql->connect_error;
    exit();
}

$cat_res = $mysql->query("SELECT category_id, name FROM categories ORDER BY name");
if(!$cat_res){ echo "SQL error (categories): ".$mysql->error; exit(); }

$cond_res = $mysql->query("SELECT condition_code_id, display_label FROM condition_codes ORDER BY condition_code_id");
if(!$cond_res){ echo "SQL error (conditions): ".$mysql->error; exit(); }

$loc_res = $mysql->query("SELECT location_id, label FROM locations ORDER BY label");
if(!$loc_res){ echo "SQL error (locations): ".$mysql->error; exit(); }

$kw = "";
if(!empty($_REQUEST['q'])){ $kw = trim($_REQUEST['q']); }

$category_id = "ALL";
if(!empty($_REQUEST['category_id'])){ $category_id = $_REQUEST['category_id']; }

$condition_code_id = "ALL";
if(!empty($_REQUEST['condition_code_id'])){ $condition_code_id = $_REQUEST['condition_code_id']; }

$location_id = "ALL";
if(!empty($_REQUEST['location_id'])){ $location_id = $_REQUEST['location_id']; }

$sort = "newest";
if(!empty($_REQUEST['sort'])){ $sort = $_REQUEST['sort']; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-FEM3Q0G7NZ"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'G-FEM3Q0G7NZ');
    </script>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>USC Student Marketplace</title>
    <link rel="stylesheet" href="stylesheet.css">
</head>
<body>

<header>
    <div class="wrap nav">
        <a href="LandingPage.php" class="brand" style="color: white;">USC Student Marketplace</a>
        <nav class="links" aria-label="primary">
            <a href="about.php">About</a>
            <a href="howitworks.php">How it Works</a>
            <a href="safety.php">Safety</a>
            <a href="voices.php">Voices</a>

            <?php if (($_SESSION['is_admin'] ?? 0) == 1): ?>
                <a href="Admin_Files/index.php" class="admin-btn">Admin</a>
            <?php endif; ?>

            <a href="loginPage.php" class="cta">Log in</a>
        </nav>
    </div>
</header>

<main class="wrap">
    <!-- HERO -->
    <section class="hero">
        <form class="search" method="get" action="">
            <label class="sr-only" for="q">Search</label>
            <input id="q" name="q" type="text" value="<?php echo htmlspecialchars($kw); ?>" placeholder="Search for laptops, bikes, furniture..." />
            <button type="submit">Search</button>
        </form>
    </section>

    <section class="summary">
        <div class="left">Showing 0 listing(s)</div>
        <div class="right">
            <form method="get" action="" style="display:flex;gap:8px;align-items:center;">
                <input type="hidden" name="q" value="<?php echo htmlspecialchars($kw); ?>">
                <input type="hidden" name="category_id" value="<?php echo htmlspecialchars($category_id); ?>">
                <input type="hidden" name="condition_code_id" value="<?php echo htmlspecialchars($condition_code_id); ?>">
                <input type="hidden" name="location_id" value="<?php echo htmlspecialchars($location_id); ?>">

                <label class="sr-only" for="sort">Sort</label>
                <select id="sort" name="sort">
                    <option value="newest"    <?php if($sort==='newest')    echo 'selected'; ?>>Newest</option>
                    <option value="oldest"    <?php if($sort==='oldest')    echo 'selected'; ?>>Oldest</option>
                    <option value="price_low" <?php if($sort==='price_low') echo 'selected'; ?>>Price: Low → High</option>
                    <option value="price_high"<?php if($sort==='price_high')echo 'selected'; ?>>Price: High → Low</option>
                </select>
                <button class="btn" type="submit">Apply</button>
                <a class="btn reset" href="search.php">Reset</a>
            </form>
        </div>
    </section>

    <section class="layout">
        <aside class="filters">
            <h3>Filters</h3>

            <form method="get" action="">
                <input type="hidden" name="q" value="<?php echo htmlspecialchars($kw); ?>">

                <label for="category_id">Category</label>
                <select id="category_id" name="category_id">
                    <option value="ALL">All categories</option>
                    <?php
                    $cat_res->data_seek(0);
                    while($r = $cat_res->fetch_assoc()){
                        $sel = ($category_id == $r['category_id']) ? "selected" : "";
                        echo "<option value='".$r['category_id']."' $sel>".htmlspecialchars($r['name'])."</option>";
                    }
                    ?>
                </select>

                <hr>

                <label for="condition_code_id">Condition</label>
                <select id="condition_code_id" name="condition_code_id">
                    <option value="ALL">All conditions</option>
                    <?php
                    $cond_res->data_seek(0);
                    while($r = $cond_res->fetch_assoc()){
                        $sel = ($condition_code_id == $r['condition_code_id']) ? "selected" : "";
                        echo "<option value='".$r['condition_code_id']."' $sel>".htmlspecialchars($r['display_label'])."</option>";
                    }
                    ?>
                </select>

                <hr>

                <label for="location_id">Location</label>
                <select id="location_id" name="location_id">
                    <option value="ALL">Anywhere</option>
                    <?php
                    $loc_res->data_seek(0);
                    while($r = $loc_res->fetch_assoc()){
                        $sel = ($location_id == $r['location_id']) ? "selected" : "";
                        echo "<option value='".$r['location_id']."' $sel>".htmlspecialchars($r['label'])."</option>";
                    }
                    ?>
                </select>

                <button class="btn w-full" type="submit" style="margin-top:8px;">Apply Filters</button>
            </form>
        </aside>

        <div>
            <div class="grid"></div>
        </div>
    </section>

    <footer>Built for USC students.</footer>
</main>

<div id="item-tooltip" class="item-tooltip" style="display:none;"></div>
<script src="minisearch.min.js"></script>

<script>
    /* ====== Client-side Search Bootstrap (robust) ====== */
    const gridEl  = document.querySelector('.grid');
    const qInput  = document.querySelector('#q');
    const sortSel = document.querySelector('#sort');
    const catSel  = document.querySelector('#category_id');
    const condSel = document.querySelector('#condition_code_id');
    const locSel  = document.querySelector('#location_id');

    let DOCS = [];
    let mini = null;

    function moneyFromCents(c){ return '$' + (c/100).toFixed(2); }
    function fmtDate(ts){ const d = new Date(ts*1000); return d.toLocaleDateString(undefined, {month:'short', day:'numeric', year:'numeric'}); }
    function escapeHtml(s){ return (s||'').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m])); }
    function escapeAttr(s){ return escapeHtml(s).replace(/"/g,'&quot;'); }

    function renderResults(items, query){
        if (!gridEl) return;
        if (!items.length){
            gridEl.innerHTML = `<p style="padding:12px;color:#666">No results for <strong>${escapeHtml(query||'')}</strong>.</p>`;
            return;
        }
        gridEl.innerHTML = items.map(doc => {
            const img  = doc.image_url ? escapeAttr(doc.image_url) : 'https://via.placeholder.com/800x600?text=No+Image';
            const date = fmtDate(doc.created_at);
            return `
      <article class="card">
        <a class="thumb"
           data-item-id="${doc.item_id}"
           style="background-image:url('${img}');"
           href="details_page.php?item_id=${doc.item_id}"></a>
        <div class="meta">
          <div class="title">${escapeHtml(doc.title)}</div>
          <div class="price">${moneyFromCents(doc.price_cents)}<span class="badge">${escapeHtml(doc.condition_label)}</span></div>
          <div class="meet">${escapeHtml(doc.location_label)} • ${date}</div>
        </div>
        <div class="actions">
          <a class="btn" href="#">Save</a>
          <a class="btn primary" href="details_page.php?item_id=${doc.item_id}">Contact</a>
        </div>
      </article>
    `;
        }).join('');
    }

    function applyFiltersAndSort(items){
        let out = items.filter(doc => {
            if (catSel && catSel.value && catSel.value !== 'ALL' && parseInt(catSel.value) !== doc.category_id) return false;
            if (condSel && condSel.value && condSel.value !== 'ALL' && parseInt(condSel.value) !== doc.condition_code_id) return false;
            if (locSel && locSel.value && locSel.value !== 'ALL' && parseInt(locSel.value) !== doc.location_id) return false;
            return true;
        });

        const sortVal = (sortSel && sortSel.value) ? sortSel.value : 'newest';
        out.sort((a,b) => {
            if (sortVal === 'newest')     return b.created_at - a.created_at;
            if (sortVal === 'oldest')     return a.created_at - b.created_at;
            if (sortVal === 'price_low')  return a.price_cents - b.price_cents;
            if (sortVal === 'price_high') return b.price_cents - a.price_cents;
            return 0;
        });

        const statsCount = document.querySelector('.stats strong');
        const summaryLeft = document.querySelector('.summary .left');
        if (statsCount)   statsCount.textContent = out.length;
        if (summaryLeft)  summaryLeft.textContent = `Showing ${out.length} listing(s)`;

        return out;
    }

    function searchDocs(query){
        if (!mini) return DOCS.slice();
        if (!query || query.trim() === '') return DOCS.slice();
        const hits = mini.search(query, {
            prefix: true,
            fuzzy: 0.2,
            boost: { title: 4, tags: 3, category_name: 2, description: 1 }
        });
        return hits.map(h => h);
    }

    (async function init(){
        try {
            const base = new URL('.', window.location.href);
            const url  = new URL('search_index.php', base).toString();

            const resp = await fetch(url, { cache: 'no-store', credentials: 'same-origin' });
            if (!resp.ok) throw new Error('HTTP '+resp.status+' from '+url);

            const raw = await resp.text();
            console.log('search_index raw (first 200):', raw.slice(0,200));
            let items;
            try { items = JSON.parse(raw); }
            catch(e){ throw new Error('JSON parse failed (is search_index.php returning JSON?)'); }

            if (!Array.isArray(items)) throw new Error('search_index did not return an array');
            DOCS = items;
            console.log('Items loaded:', DOCS.length);

            if (typeof MiniSearch === 'undefined') throw new Error('MiniSearch not loaded (check minisearch.min.js path)');
            mini = new MiniSearch({
                idField: 'item_id',
                fields: ['title', 'tags', 'category_name', 'description'],
                storeFields: [
                    'item_id','title','description','price_cents','created_at',
                    'category_id','category_name','condition_code_id','condition_label',
                    'location_id','location_label','image_url','tags'
                ]
            });
            mini.addAll(DOCS);

            const runSearch = () => {
                const q = qInput ? qInput.value : '';
                const base = searchDocs(q);
                const filtered = applyFiltersAndSort(base);
                renderResults(filtered, q);
            };

            // 🔥 AUTO-RUN SEARCH ON PAGE LOAD if there's a query parameter
            runSearch();

            ['change','keyup'].forEach(ev => {
                if (qInput)  qInput.addEventListener(ev, runSearch);
                if (sortSel) sortSel.addEventListener(ev, runSearch);
            });
            if (catSel)  catSel.addEventListener('change', runSearch);
            if (condSel) condSel.addEventListener('change', runSearch);
            if (locSel)  locSel.addEventListener('change', runSearch);

            document.querySelectorAll('form.search, .summary form, .filters form').forEach(f => {
                f.addEventListener('submit', e => { e.preventDefault(); runSearch(); });
            });

        } catch (err) {
            console.error('Init error:', err);
            if (gridEl) gridEl.innerHTML = `<p style="padding:12px;color:#a00">Search failed to initialize: ${escapeHtml(String(err))}.<br>Open DevTools → Network → search_index.php and verify it returns valid JSON.</p>`;
        }
    })();

    // === Hover popup for item title + description ===
    const tooltipEl = document.getElementById('item-tooltip');
    let hoverTimeout = null;

    function showTooltip(html, x, y) {
        if (!tooltipEl) return;
        tooltipEl.innerHTML = html;
        tooltipEl.style.left = (x + 12) + 'px';
        tooltipEl.style.top  = (y + 12) + 'px';
        tooltipEl.style.display = 'block';
    }

    function hideTooltip() {
        if (!tooltipEl) return;
        tooltipEl.style.display = 'none';
    }

    if (gridEl) {
        gridEl.addEventListener('mousemove', (e) => {
            const thumb = e.target.closest('.thumb');
            if (!thumb || !gridEl.contains(thumb)) {
                hideTooltip();
                return;
            }

            const itemId = thumb.dataset.itemId;
            if (!itemId) {
                hideTooltip();
                return;
            }

            if (hoverTimeout) clearTimeout(hoverTimeout);
            hoverTimeout = setTimeout(async () => {
                try {
                    const resp = await fetch(`item_detail.php?item_id=${encodeURIComponent(itemId)}`);
                    if (!resp.ok) return;
                    const data = await resp.json();
                    if (!data.ok) return;

                    const html = `
                        <strong>${escapeHtml(data.title)}</strong>
                        <span>${escapeHtml(data.description || 'No description')}</span>
                    `;
                    showTooltip(html, e.clientX, e.clientY);
                } catch (err) {
                    // optional: console.error(err);
                }
            }, 250);
        });

        gridEl.addEventListener('mouseleave', () => {
            if (hoverTimeout) clearTimeout(hoverTimeout);
            hideTooltip();
        });
    }

</script>

</body>
</html>