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

$db = get_db();

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

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

$sql = '
    SELECT s.*, pg.code AS product_group_code, pg.name AS product_group_name, sup.name AS supplier_name
    FROM styles s
    JOIN product_groups pg ON pg.id = s.product_group_id
    LEFT JOIN suppliers sup ON sup.id = s.supplier_id
    WHERE 1=1
';
$params = [];

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

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

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