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

$db = get_db();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $rows = $db->query('
        SELECT pg.*,
            (SELECT COUNT(*) FROM styles s WHERE s.product_group_id = pg.id) AS style_count
        FROM product_groups pg
        ORDER BY pg.code
    ')->fetchAll();
    respond($rows);
}

if ($method === 'POST') {
    $input = json_input();
    $code = trim($input['code'] ?? '');
    $name = trim($input['name'] ?? '');
    $brand = trim($input['brand'] ?? '');
    $status = $input['status'] ?? 'Active';

    if ($code === '' || $name === '') {
        respond(['error' => 'Code and name are required'], 422);
    }

    $stmt = $db->prepare('INSERT INTO product_groups (code, name, brand, status) VALUES (?, ?, ?, ?)');
    $stmt->execute([$code, $name, $brand, $status]);

    respond(['id' => $db->lastInsertId(), 'code' => $code, 'name' => $name, 'brand' => $brand, 'status' => $status], 201);
}

if ($method === 'PUT') {
    $input = json_input();
    $id = (int)($input['id'] ?? 0);
    if (!$id) respond(['error' => 'id is required'], 422);

    $stmt = $db->prepare('UPDATE product_groups SET code = ?, name = ?, brand = ?, status = ? WHERE id = ?');
    $stmt->execute([$input['code'], $input['name'], $input['brand'], $input['status'], $id]);

    respond(['ok' => true]);
}

if ($method === 'DELETE') {
    parse_str($_SERVER['QUERY_STRING'] ?? '', $q);
    $id = (int)($q['id'] ?? 0);
    if (!$id) respond(['error' => 'id is required'], 422);

    $stmt = $db->prepare('DELETE FROM product_groups WHERE id = ?');
    $stmt->execute([$id]);

    respond(['ok' => true]);
}

respond(['error' => 'Method not allowed'], 405);
