<?php
require_once __DIR__ . '/config.php';
require_auth();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    respond(['error' => 'Method not allowed'], 405);
}

$db = get_db();
$productGroupId = $_GET['product_group_id'] ?? null;
$search = trim($_GET['search'] ?? '');

$sql = '
    SELECT st.*, s.style_code, s.style_name, s.colour, s.gender, s.status AS style_status,
           pg.code AS product_group_code, pg.name AS product_group_name
    FROM stock st
    JOIN styles s ON s.id = st.style_id
    JOIN product_groups pg ON pg.id = s.product_group_id
    WHERE 1=1
';
$params = [];

if ($productGroupId) {
    $sql .= ' AND s.product_group_id = ?';
    $params[] = $productGroupId;
}
if ($search !== '') {
    $sql .= ' AND (s.style_code LIKE ? OR s.style_name LIKE ?)';
    $like = "%$search%";
    array_push($params, $like, $like);
}

$sql .= ' ORDER BY s.style_code';

$stmt = $db->prepare($sql);
$stmt->execute($params);
respond($stmt->fetchAll());
