<?php

/*
--------------------------------------------------------------------------------

*NOTE the following code was made with AI assistance.

This script connects to the USC Student Marketplace database, retrieves all
item listings, and outputs them as a JSON array for use in the frontend.

It performs the following:
    • Loads brand, category, and color hint data from a local JSON/CSV file.
    • Queries the database for item details, including title, price, category,
    condition, location, and primary image URL.
    • Automatically generates tags based on brand matches, category aliases,
    color mentions, and size patterns.
    • Merges auto-generated tags with database tags to form a unified tag list.
    • Returns a JSON response with all item data for
    search and filtering features.

--------------------------------------------------------------------------------
*/

error_reporting(0);
ini_set('display_errors', '0');
if (function_exists('ob_get_level')) { while (ob_get_level()) { ob_end_clean(); } }
ob_start();

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

function load_hints($path){
    $brandMap = array();
    $catAliases = array();
    $colors = array('black','white','red','blue','green','yellow','orange','purple','pink','gray','grey','tan','brown','beige','navy');

    if (!file_exists($path)) return array($brandMap, $catAliases, $colors);

    $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    $raw = @file_get_contents($path);
    if (!$raw) return array($brandMap, $catAliases, $colors);

    if ($ext === 'json'){
        $j = @json_decode($raw, true);
        if (is_array($j)) {
            if (!empty($j['needles']) && is_array($j['needles'])) {
                foreach($j['needles'] as $needle => $tags){
                    $needle = strtolower(trim($needle));
                    if ($needle==='') continue;
                    $list = array();
                    if (is_array($tags)) { foreach($tags as $t){ $t = strtolower(trim($t)); if ($t!=='') $list[] = $t; } }
                    else { foreach(explode(',', strtolower($tags)) as $t){ $t = trim($t); if ($t!=='') $list[] = $t; } }
                    if (!empty($list)) $brandMap[$needle] = array_values(array_unique($list));
                }
            }
            if (!empty($j['category_aliases']) && is_array($j['category_aliases'])) {
                foreach($j['category_aliases'] as $cat => $tags){
                    $cat = trim($cat);
                    $list = array();
                    if (is_array($tags)) { foreach($tags as $t){ $t = strtolower(trim($t)); if ($t!=='') $list[] = $t; } }
                    else { foreach(explode(',', strtolower($tags)) as $t){ $t = trim($t); if ($t!=='') $list[] = $t; } }
                    if (!empty($list)) $catAliases[$cat] = array_values(array_unique($list));
                }
            }
            if (!empty($j['colors']) && is_array($j['colors'])){
                $colors = array();
                foreach($j['colors'] as $c){ $c = strtolower(trim($c)); if ($c!=='') $colors[] = $c; }
            }
        }
    } elseif ($ext === 'csv'){
        $lines = preg_split('/\r\n|\n|\r/', $raw);
        foreach($lines as $line){
            if (trim($line)==='' || stripos($line,'needle,')===0) continue;
            $parts = explode(',', $line, 2);
            $needle = strtolower(trim($parts[0] ?? ''));
            $tags = strtolower(trim($parts[1] ?? ''));
            if ($needle==='') continue;
            $list = array();
            foreach(explode(',', $tags) as $t){ $t = trim($t); if ($t!=='') $list[] = $t; }
            if (!empty($list)) $brandMap[$needle] = array_values(array_unique($list));
        }
    }
    return array($brandMap, $catAliases, $colors);
}

list($BRAND_MAP, $CAT_ALIASES, $COLOR_LIST) = load_hints(__DIR__ . '/search_hints.json');

$rows = array();
$mysqli = @new mysqli($host, $userid, $userpw, $db);
if ($mysqli && !$mysqli->connect_errno) {
    @$mysqli->set_charset("utf8mb4");

    $sql = "
 SELECT
    i.item_id,
    i.title,
    i.description,
    i.price_cents,
    UNIX_TIMESTAMP(i.created_at) AS created_ts,
    i.category_id,
    c.name AS category_name,
    i.condition_code_id,
    cc.display_label AS condition_label,
    i.location_id,
    l.label AS location_label,
    i.tags,
    
    -- seller info
    i.seller_id AS seller_id,
    u.usc_email AS seller_usc_email,

    -- primary image
    (
        SELECT ii.url
        FROM item_images ii
        WHERE ii.item_id = i.item_id
        ORDER BY ii.is_primary DESC, ii.image_id ASC
        LIMIT 1
    ) AS image_url

FROM items i
JOIN users u            ON u.user_id = i.seller_id
JOIN categories c       ON c.category_id = i.category_id
JOIN condition_codes cc ON cc.condition_code_id = i.condition_code_id
LEFT JOIN locations l   ON l.location_id = i.location_id
ORDER BY i.created_at DESC
  ";

    if ($res = @$mysqli->query($sql)) {
        while($r = $res->fetch_assoc()){
            $text = strtolower(($r['title']??'').' '.($r['description']??'').' '.($r['category_name']??''));
            $auto = array();

            // Use external BRAND_MAP
            foreach($BRAND_MAP as $needle => $add){
                if ($needle!=='' && strpos($text, $needle) !== false){
                    foreach($add as $t){ $auto[] = $t; }
                }
            }

            // Category aliases
            $catName = $r['category_name'] ?? '';
            if ($catName !== '' && isset($CAT_ALIASES[$catName])){
                foreach($CAT_ALIASES[$catName] as $t){ $auto[] = $t; }
            }

            // Colors (from file)
            foreach($COLOR_LIST as $c){
                if (strpos($text, $c) !== false){ $auto[] = $c; }
            }

            // Sizes
            if (preg_match('/\b(6|6\.5|7|7\.5|8|8\.5|9|9\.5|10|10\.5|11|11\.5|12|13)\b/', $text, $m)){
                $auto[] = 'size ' . $m[1];
            }
            if (preg_match('/\b(xs|s|m|l|xl|xxl)\b/', $text, $m)){
                $auto[] = 'size ' . strtoupper($m[1]);
            }

            // Merge DB tags + auto
            $db_tags = array();
            if (!empty($r['tags'])){
                foreach (explode(',', strtolower($r['tags'])) as $t){
                    $t = trim($t); if ($t!=='') $db_tags[] = $t;
                }
            }
            $tags = array_values(array_unique(array_merge($db_tags, $auto)));

            $rows[] = array(
                "item_id"           => intval($r["item_id"]),
                "title"             => $r["title"] ?? "",
                "description"       => $r["description"] ?? "",
                "price_cents"       => intval($r["price_cents"]),
                "created_at"        => intval($r["created_ts"]),
                "category_id"       => intval($r["category_id"]),
                "category_name"     => $r["category_name"] ?? "",
                "condition_code_id" => intval($r["condition_code_id"]),
                "condition_label"   => $r["condition_label"] ?? "",
                "location_id"       => intval($r["location_id"]),
                "location_label"    => ($r["location_label"] ?? "") !== "" ? $r["location_label"] : "On campus",
                "image_url"         => $r["image_url"] ?? null,
                "tags"              => $tags,
                "seller_id"         => intval($r["seller_id"]),
                "seller_usc_email"  => $r["seller_usc_email"] ?? "",
            );
        }
    }
}

header("Content-Type: application/json; charset=utf-8");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");
$flags = defined('JSON_INVALID_UTF8_SUBSTITUTE') ? JSON_INVALID_UTF8_SUBSTITUTE : 0;
$out = json_encode($rows, $flags);
if (function_exists('ob_get_length') && ob_get_length()) { ob_clean(); }
echo $out ? $out : "[]";
exit;