<?php
/**
 * Rig N Dig - Mobile API v1 / Product Search & List
 */
header('Content-Type: application/json');
require_once '../../../config/config.php';
require_once '../../../includes/functions.php';
require_once '../api_helper.php';

$search = $_GET['q'] ?? '';
$catId  = (int)($_GET['cat'] ?? 0);
$limit  = (int)($_GET['limit'] ?? 20);
$page   = (int)($_GET['page'] ?? 1);
$offset = ($page - 1) * $limit;

$query = "SELECT p.id, p.name, p.sku, p.price, p.image, p.slug, p.short_description, c.name as category_name 
          FROM products p 
          LEFT JOIN categories c ON p.category_id = c.id 
          WHERE p.status = 'active'";
$params = [];

if ($search) {
    $query .= " AND (p.name LIKE ? OR p.sku LIKE ? OR p.description LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($catId) {
    $query .= " AND p.category_id = ?";
    $params[] = $catId;
}

$query .= " ORDER BY p.id DESC LIMIT $limit OFFSET $offset";

try {
    $products = Database::fetchAll($query, $params);

    foreach ($products as &$p) {
        $p['image_url'] = SITE_URL . '/uploads/' . ($p['image'] ?: 'default-product.png');
    }

    apiResponse(true, 'Products loaded', [
        'count' => count($products),
        'page' => $page,
        'products' => $products
    ]);
} catch (Exception $e) {
    apiResponse(false, 'Failed to load products: ' . $e->getMessage());
}
