<?php

function complaint_html($value) {
    return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8');
}

function complaint_node_path_parts($conn, $nodeId) {
    $nodeId = (int)$nodeId;
    if ($nodeId <= 0) {
        return [];
    }

    $parts = [];
    $guard = 0;

    while ($nodeId > 0 && $guard < 20) {
        $result = $conn->query("SELECT id, parent_id, name FROM complaint_nodes WHERE id='$nodeId' LIMIT 1");
        if (!$result || $result->num_rows == 0) {
            break;
        }

        $row = $result->fetch_assoc();
        array_unshift($parts, $row['name']);
        $nodeId = (int)$row['parent_id'];
        $guard++;
    }

    return $parts;
}

function complaint_node_path($conn, $nodeId) {
    return implode(' / ', complaint_node_path_parts($conn, $nodeId));
}

function complaint_node_chain($conn, $nodeId) {
    $nodeId = (int)$nodeId;
    if ($nodeId <= 0) {
        return [];
    }

    $nodes = [];
    $guard = 0;

    while ($nodeId > 0 && $guard < 20) {
        $result = $conn->query("SELECT id, parent_id, name FROM complaint_nodes WHERE id='$nodeId' LIMIT 1");
        if (!$result || $result->num_rows == 0) {
            break;
        }

        $row = $result->fetch_assoc();
        array_unshift($nodes, $row);
        $nodeId = (int)$row['parent_id'];
        $guard++;
    }

    return $nodes;
}

function complaint_admin_level_label($level) {
    $labels = [
        1 => 'Complaint Type',
        2 => 'Category / Priority',
        3 => 'Location',
        4 => 'Item'
    ];

    return $labels[$level] ?? 'Option';
}

function complaint_node_parts_for_list($conn, $nodeId) {
    $parts = complaint_node_path_parts($conn, $nodeId);
    return [
        'type' => $parts[0] ?? '',
        'category' => $parts[1] ?? '',
        'location' => $parts[2] ?? '',
        'item' => $parts[3] ?? ''
    ];
}

function complaint_full_path($conn, $complaintRow) {
    if (!empty($complaintRow['node_id'])) {
        $path = complaint_node_path($conn, $complaintRow['node_id']);
        if ($path != '') {
            return $path . ' / ' . ($complaintRow['details'] ?? $complaintRow['complaint_name'] ?? '');
        }
    }

    $parts = [];
    if (!empty($complaintRow['category_name'])) {
        $parts[] = $complaintRow['category_name'];
    }
    if (!empty($complaintRow['subcategory_name'])) {
        $parts[] = $complaintRow['subcategory_name'];
    }
    $parts[] = $complaintRow['details'] ?? $complaintRow['complaint_name'] ?? '';

    return implode(' / ', array_filter($parts));
}

function complaint_root_nodes($conn) {
    return $conn->query("SELECT id, name FROM complaint_nodes WHERE parent_id IS NULL ORDER BY sort_order ASC, name ASC");
}

function complaint_child_nodes($conn, $parentId) {
    $parentId = (int)$parentId;
    return $conn->query("SELECT id, name FROM complaint_nodes WHERE parent_id='$parentId' ORDER BY sort_order ASC, name ASC");
}

function complaint_node_subdivision($conn, $nodeId) {
    $path = complaint_node_path($conn, $nodeId);
    if (strpos($path, 'E/M') === 0) {
        return 1;
    }
    if (strpos($path, 'B/R') === 0) {
        return 2;
    }
    return 3;
}

function complaint_compat_category_ids($conn, $nodeId) {
    $parts = complaint_node_path_parts($conn, $nodeId);
    $categoryName = $parts[0] ?? '';
    $subcategoryName = $parts[1] ?? '';
    $ccId = 0;
    $csId = 0;

    if ($categoryName != '') {
        $categoryNameSql = $conn->real_escape_string($categoryName);
        $category = $conn->query("SELECT cc_id FROM complaint_category WHERE name='$categoryNameSql' LIMIT 1");
        if ($category && $category->num_rows > 0) {
            $ccId = (int)$category->fetch_assoc()['cc_id'];
        }
    }

    if ($ccId > 0 && $subcategoryName != '') {
        $subcategoryNameSql = $conn->real_escape_string($subcategoryName);
        $subcategory = $conn->query("SELECT cs_id FROM complaint_subcategory WHERE cc_id='$ccId' AND name='$subcategoryNameSql' LIMIT 1");
        if ($subcategory && $subcategory->num_rows > 0) {
            $csId = (int)$subcategory->fetch_assoc()['cs_id'];
        }
    }

    return [$ccId, $csId];
}

function complaint_node_priority($conn, $nodeId, $fallback = 3) {
    $nodeId = (int)$nodeId;
    $guard = 0;

    while ($nodeId > 0 && $guard < 20) {
        $result = $conn->query("SELECT parent_id, name FROM complaint_nodes WHERE id='$nodeId' LIMIT 1");
        if (!$result || $result->num_rows == 0) {
            break;
        }

        $row = $result->fetch_assoc();
        if (preg_match('/priority[^0-9]*([123])/i', $row['name'], $matches)) {
            return (int)$matches[1];
        }

        $nodeId = (int)$row['parent_id'];
        $guard++;
    }

    return (int)$fallback;
}
