<?php
session_start();
include '../db.php';

// Check if user is authenticated
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['items' => [], 'total_count' => 0]);
    exit;
}

$search_term = $_GET['q'] ?? '';
$page = intval($_GET['page'] ?? 1);
$limit = 30;
$offset = ($page - 1) * $limit;

// If no search term, show all items
$has_search = strlen($search_term) > 0;

try {
    if ($has_search) {
        // Search items by name or code
        $search_pattern = '%' . $search_term . '%';
        
        // Count total results
        $count_query = "
            SELECT COUNT(*) as total
            FROM items i
            LEFT JOIN categories c ON i.category_id = c.id
            WHERE (i.name LIKE ? OR i.item_code LIKE ? OR i.sku_number LIKE ?)
        ";
        
        $count_stmt = $conn->prepare($count_query);
        $count_stmt->bind_param("sss", $search_pattern, $search_pattern, $search_pattern);
        $count_stmt->execute();
        $total_count = $count_stmt->get_result()->fetch_assoc()['total'];
        $count_stmt->close();
        
        // Get paginated results
        $query = "
            SELECT i.id, i.name, i.item_code, i.sku_number, i.item_role, c.name as category_name
            FROM items i
            LEFT JOIN categories c ON i.category_id = c.id
            WHERE (i.name LIKE ? OR i.item_code LIKE ? OR i.sku_number LIKE ?)
            ORDER BY i.name ASC
            LIMIT ? OFFSET ?
        ";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("sssii", $search_pattern, $search_pattern, $search_pattern, $limit, $offset);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        // Show all items
        $count_query = "
            SELECT COUNT(*) as total
            FROM items i
            LEFT JOIN categories c ON i.category_id = c.id
        ";
        
        $count_stmt = $conn->prepare($count_query);
        $count_stmt->execute();
        $total_count = $count_stmt->get_result()->fetch_assoc()['total'];
        $count_stmt->close();
        
        // Get paginated results
        $query = "
            SELECT i.id, i.name, i.item_code, i.sku_number, i.item_role, c.name as category_name
            FROM items i
            LEFT JOIN categories c ON i.category_id = c.id
            ORDER BY i.name ASC
            LIMIT ? OFFSET ?
        ";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ii", $limit, $offset);
        $stmt->execute();
        $result = $stmt->get_result();
    }
    
    $items = [];
    while ($row = $result->fetch_assoc()) {
        $items[] = [
            'id' => $row['id'],
            'text' => $row['name'] . ' (' . $row['item_code'] . ')',
            'name' => $row['name'],
            'code' => $row['item_code'],
            'sku' => $row['sku_number'],
            'type' => $row['item_role'],
            'category' => $row['category_name'] ?? 'No Category'
        ];
    }
    
    $stmt->close();
    
    echo json_encode([
        'items' => $items,
        'total_count' => $total_count
    ]);
    
} catch (Exception $e) {
    echo json_encode(['items' => [], 'total_count' => 0]);
}
?>
