<?php
// GET  /api/customer/products  — list active products (optionally filter by category)
require_once __DIR__ . '/../../../api/cors.php'; // Enable CORS for React Native
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../middleware/auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') jsonError('Method not allowed', 405);

requireAuth(); // must be logged in

$db       = getDB();
$category = $_GET['category'] ?? '';

if ($category) {
    $stmt = $db->prepare(
        'SELECT id, name, description, price, category, image_url, stock
         FROM products WHERE is_active = 1 AND category = ?
         ORDER BY created_at DESC'
    );
    $stmt->execute([$category]);
} else {
    $stmt = $db->query(
        'SELECT id, name, description, price, category, image_url, stock
         FROM products WHERE is_active = 1
         ORDER BY created_at DESC'
    );
}

$rows = $stmt->fetchAll();

// Fix image_url: prepend full server URL if it's a relative path
$baseUrl = 'http://' . $_SERVER['HTTP_HOST'];
foreach ($rows as &$row) {
    if (!empty($row['image_url']) && str_starts_with($row['image_url'], '/')) {
        $row['image_url'] = $baseUrl . $row['image_url'];
    }
}
unset($row);

jsonResponse($rows);
