<?php
/**
 * Rig N Dig - Mobile API v1 / Products
 */
header('Content-Type: application/json');
require_once '../../config/config.php';

$search = $_GET['q'] ?? '';
$cat    = (int)($_GET['cat'] ?? 0);

$query = "SELECT p.id, p.name, p.sku, p.price, p.image, p.slug, 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 ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

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

$query .= " ORDER BY p.id DESC LIMIT 50";

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

// Format image URLs for Mobile
foreach ($products as &$p) {
    $p['image_url'] = SITE_URL . '/uploads/' . $p['image'];
}

echo json_encode([
    'success' => true,
    'count' => count($products),
    'data' => $products
]);
