<?php
/**
 * Shared utility functions for the system
 * Contains functions for:
 * - Product category handling
 * - [Other shared functions can be added here in the future]
 */

// Function to get category name by ID
function getCategoryName($conn, $category_id) {
    if (!$category_id) {
        return '未分类';
    }
    
    $sql = "SELECT name FROM product_categories WHERE id = " . intval($category_id);
    $result = mysqli_query($conn, $sql);
    
    if ($row = mysqli_fetch_assoc($result)) {
        return htmlspecialcharsFix($row['name']);
    }
    
    return '未知分类';
}

// Function to get full category path by ID (e.g., "父分类 > 子分类")
function getCategoryPath($conn, $category_id) {
    if (!$category_id) {
        return '未分类';
    }
    
    $path = array();
    $current_id = $category_id;
    
    while ($current_id > 0) {
        $sql = "SELECT id, name, parent_id FROM product_categories WHERE id = " . intval($current_id);
        $result = mysqli_query($conn, $sql);
        
        if ($row = mysqli_fetch_assoc($result)) {
            $path[] = htmlspecialcharsFix($row['name']);
            $current_id = $row['parent_id'];
        } else {
            break;
        }
    }
    
    return implode(' > ', array_reverse($path));
}

// Function to build category tree
function buildCategoryTree($conn) {
    // Get all categories
    $categories_sql = "SELECT * FROM product_categories ORDER BY parent_id ASC, sort_order ASC, id ASC";
    $categories_result = mysqli_query($conn, $categories_sql);
    
    // Build category tree
    $all_categories = array();
    $cat_tree = array();
    
    // First pass: create an array of all categories
    while ($cat_row = mysqli_fetch_assoc($categories_result)) {
        $all_categories[$cat_row['id']] = $cat_row;
        $all_categories[$cat_row['id']]['children'] = array();
    }
    
    // Second pass: build the tree structure
    foreach ($all_categories as $cat_id => $category) {
        if ($category['parent_id'] == 0) {
            // Root category
            $cat_tree[$cat_id] = &$all_categories[$cat_id];
        } else {
            // Child category
            if (isset($all_categories[$category['parent_id']])) {
                $all_categories[$category['parent_id']]['children'][$cat_id] = &$all_categories[$cat_id];
            }
        }
    }
    
    return [
        'all_categories' => $all_categories,
        'tree' => $cat_tree
    ];
}

// Function to output category options for select dropdown
function outputCategoryOptions($categories, $selected_id, $level = 0) {
    foreach ($categories as $cat) {
        $indent = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level);
        $prefix = $level > 0 ? $indent . '└─ ' : '';
        $selected = ($selected_id == $cat['id']) ? ' selected="selected"' : '';
        
        echo '<option value="' . $cat['id'] . '"' . $selected . '>' . $prefix . htmlspecialcharsFix($cat['name']) . '</option>';
        
        // Output children
        if (!empty($cat['children'])) {
            outputCategoryOptions($cat['children'], $selected_id, $level + 1);
        }
    }
}

// Function to get all subcategory IDs (recursively)
function getSubcategoryIds($categories, $parent_id, &$result_ids) {
    foreach ($categories as $id => $category) {
        if ($category['parent_id'] == $parent_id) {
            $result_ids[] = $id;
            getSubcategoryIds($categories, $id, $result_ids);
        }
    }
}