<?php
include 'core/autoload.php';
include 'core/app/model/StoreProductData.php';

header('Content-Type: application/json; charset=utf-8');

$category = isset($_GET['category']) ? strtolower($_GET['category']) : 'all';
$search = isset($_GET['search']) ? strtolower($_GET['search']) : '';
$page    = isset($_GET['page'])     ? (int) $_GET['page']     : 1;
$perPage = isset($_GET['per_page']) ? (int) $_GET['per_page'] : 100;

$page    = max(1, $page);
$perPage = max(1, min(200, $perPage));
$offset  = ($page - 1) * $perPage;

// Keywords por categoría
$categoryKeywords = array(
    'mouse' => array('mouse', 'ratón', 'raton', 'mousepad', 'pad'),
    'teclado' => array('teclado', 'keyboard'),
    'audio' => array('audifono', 'auricular', 'headset', 'microfono'),
    'monitor' => array('monitor', 'pantalla', 'display'),
    'silla' => array('silla', 'escritorio'),
    'webcam' => array('webcam', 'camara'),
    'all' => array()
);

// Keywords gaming generales
$gamingKeywords = array('mouse', 'ratón', 'raton', 'teclado', 'keyboard', 'audifono', 'auricular', 'headset', 'microfono', 'monitor', 'pantalla', 'display', 'gamer', 'gaming', 'silla', 'escritorio', 'webcam', 'camara', 'mousepad', 'pad');

function gaming_text_raw($value)
{
    return html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
}

function gaming_img($image)
{
    $default = 'assets/images/error/01.png';
    if (!is_string($image) || $image === '') {
        return $default;
    }

    $image = trim($image);
    if (preg_match('/^https?:\/\//i', $image)) {
        return $image;
    }

    if (strpos($image, '/') !== false) {
        $cleanPath = ltrim($image, '/');
        if (file_exists(__DIR__ . '/' . $cleanPath)) {
            return $cleanPath;
        }
    }

    $filename  = basename($image);
    $extension = strtolower((string) pathinfo($filename, PATHINFO_EXTENSION));
    if (!in_array($extension, array('jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'), true)) {
        return $default;
    }

    $path = 'assets/images/products/' . $filename;
    if (file_exists(__DIR__ . '/' . $path)) {
        return $path;
    }

    return $default;
}

// BUSCAR EN TODOS LOS PRODUCTOS
$items = StoreProductData::getPublicProducts('', 5000);
if (empty($items)) {
    // Fallback si no existe getAllProducts
    $items = StoreProductData::getRecentProductsPaged(500, 0, 500);
}

$keywords = $categoryKeywords[$category] ?? $categoryKeywords['all'];

$gamingProducts = array();
$priorityProducts = array();

foreach ($items as $p) {
    $name = isset($p['name']) ? strtolower($p['name']) : '';
    $desc = isset($p['description']) ? strtolower($p['description']) : '';
    $brand = isset($p['brand']) ? strtolower($p['brand']) : '';
    $code = isset($p['code']) ? strtolower($p['code']) : '';
    
    $text = $name . ' ' . $desc . ' ' . $brand . ' ' . $code;
    
    // Filter búsqueda de texto
    if ($search && stripos($text, $search) === false) {
        continue;
    }
    
    // Verificar si es gaming
    $isGaming = false;
    foreach ($gamingKeywords as $kw) {
        if (stripos($text, $kw) !== false) {
            $isGaming = true;
            break;
        }
    }
    
    if (!$isGaming) continue;
    
    // Si hay filtro de categoría, verificar
    if (!empty($keywords)) {
        $catMatch = false;
        foreach ($keywords as $kw) {
            if (stripos($text, $kw) !== false) {
                $catMatch = true;
                break;
            }
        }
        if (!$catMatch) continue;
    }
    
    // Prioridad para gamer/mecanico/rgb
    $isPriority = (stripos($text, 'gamer') !== false || 
                   stripos($text, 'mecanico') !== false || 
                   stripos($text, 'rgb') !== false);
    
    $p['_priority'] = $isPriority ? 1 : 0;
    
    if ($isPriority) {
        $priorityProducts[] = $p;
    } else {
        $gamingProducts[] = $p;
    }
}

// Ordenar
usort($priorityProducts, function($a, $b) {
    return $b['_priority'] - $a['_priority'];
});

// Combinar
$combined = array_merge($priorityProducts, $gamingProducts);

$total = count($combined);
$hasMore = ($offset + $perPage) < $total;

$start = $offset;
$end = min($offset + $perPage, $total);
$itemsPage = array_slice($combined, $start, $end - $start);

$out = array();
foreach ($itemsPage as $p) {
    $rawPrice   = isset($p['price']) ? (float) $p['price'] : 0;
    $priceFinal = (int) ceil($rawPrice * 0.87 * 1.4);

    $out[] = array(
        'id'           => (int) $p['id'],
        'name'         => gaming_text_raw(isset($p['name'])  ? $p['name']  : ''),
        'brand'        => gaming_text_raw(isset($p['brand']) ? $p['brand'] : ''),
        'code'         => gaming_text_raw(isset($p['code'])  ? $p['code']  : ''),
        'description'  => gaming_text_raw(isset($p['description']) ? $p['description'] : ''),
        'price'        => $rawPrice,
        'price_final'  => $priceFinal,
        'stock_lapaz'  => isset($p['stock_lapaz'])   ? (int) $p['stock_lapaz']   : 0,
        'stock_interior' => isset($p['stock_interior']) ? (int) $p['stock_interior'] : 0,
        'image'        => gaming_img(isset($p['image']) ? $p['image'] : ''),
    );
}

echo json_encode(array(
    'items'    => $out,
    'total'    => $total,
    'page'     => $page,
    'per_page' => $perPage,
    'has_more' => $hasMore,
));