<?php
require 'db.php';

$category_id = intval($_GET['category_id'] ?? 0);
$subcategory_id = intval($_GET['subcategory_id'] ?? 0);

if (!$category_id) {
    echo json_encode([]);
    exit;
}

$groups = [];

/* Fetch sorting groups for category (all or subcategory) */
if ($subcategory_id > 0) {
    $gq = $conn->prepare("
        SELECT id, name 
        FROM sorting_groups 
        WHERE category_id=? 
        AND (subcategory_id IS NULL OR subcategory_id=?) 
        AND status='active'
        ORDER BY sort_order
    ");
    $gq->bind_param("ii", $category_id, $subcategory_id);
} else {
    $gq = $conn->prepare("
        SELECT id, name 
        FROM sorting_groups 
        WHERE category_id=? 
        AND status='active'
        ORDER BY sort_order
    ");
    $gq->bind_param("i", $category_id);
}

$gq->execute();
$gr = $gq->get_result();

while ($g = $gr->fetch_assoc()) {

    // Fetch options and deduplicate by name
    $oq = $conn->prepare("
        SELECT DISTINCT name, id
        FROM sorting_options 
        WHERE sorting_group_id=? AND status='active'
        ORDER BY sort_order
    ");
    $oq->bind_param("i", $g['id']);
    $oq->execute();

    $or = $oq->get_result();
    $opts = [];
    $seenNames = []; // track duplicates by name

    while ($o = $or->fetch_assoc()) {
        // Only add if name not seen yet
        if (!in_array(strtolower($o['name']), $seenNames)) {
            $seenNames[] = strtolower($o['name']);
            $opts[] = [
                "id" => $o['id'],
                "name" => $o['name']
            ];
        }
    }

    if (!empty($opts)) {
        $groups[] = [
            "id" => $g['id'],
            "name" => $g['name'],
            "options" => $opts
        ];
    }
}

header('Content-Type: application/json');
echo json_encode($groups);