<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['GET']);

$category = $_GET['category'] ?? '';
$search = $_GET['search'] ?? '';
$limit = min((int)($_GET['limit'] ?? 20), 50);
$offset = max((int)($_GET['offset'] ?? 0), 0);

try {
    $pdo = hw_db();
    
    // Build query with filters
    $where = ['p.active = 1'];
    $params = [];
    
    if ($category) {
        $where[] = 'c.slug = ?';
        $params[] = $category;
    }
    
    if ($search) {
        $where[] = '(p.name LIKE ? OR p.description LIKE ?)';
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    
    $whereClause = implode(' AND ', $where);
    
    // Get products with category and coach info
    $stmt = $pdo->prepare("
        SELECT p.*, c.name as category_name, c.slug as category_slug,
               coach.display_name as coach_name
        FROM products p 
        JOIN product_categories c ON p.category_id = c.id 
        LEFT JOIN coaches coach ON p.coach_id = coach.id
        WHERE $whereClause
        ORDER BY p.created_at DESC 
        LIMIT ? OFFSET ?
    ");
    $params[] = $limit;
    $params[] = $offset;
    $stmt->execute($params);
    $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format products
    foreach ($products as &$product) {
        $product['price'] = (float)$product['price'];
        $product['stock_quantity'] = (int)$product['stock_quantity'];
    }
    
    // Get categories for filters
    $stmt = $pdo->query("SELECT * FROM product_categories WHERE active = 1 ORDER BY name");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    hw_json([
        'success' => true,
        'products' => $products,
        'categories' => $categories,
        'pagination' => [
            'limit' => $limit,
            'offset' => $offset,
            'has_more' => count($products) === $limit
        ]
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}