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

// Temporarily removed authentication check - will be added later
// if (!isset($_SESSION['user_id'])) {
//     echo json_encode(['success' => false, 'message' => 'User not authenticated']);
//     exit;
// }

$store_id = $_SESSION['store_id'] ?? 1;
$category_id = $_GET['category'] ?? '';
$search = $_GET['search'] ?? '';

try {
    // Build the query
    $query = "
        SELECT i.id, i.item_code, i.sku_number, i.name, i.retail_price, 
               i.tax_type, i.tax_rate_id, i.category_id, i.sub_category_id,
               c.name as category_name, sc.name as subcategory_name
        FROM items i
        LEFT JOIN categories c ON i.category_id = c.id
        LEFT JOIN sub_categories sc ON i.sub_category_id = sc.id
        WHERE i.item_role = 'stock'
    ";
    
    $params = [];
    $types = '';
    
    // Add category filter
    if (!empty($category_id)) {
        $query .= " AND i.category_id = ?";
        $params[] = $category_id;
        $types .= 'i';
    }
    
    // Add search filter
    if (!empty($search)) {
        $query .= " AND (i.name LIKE ? OR i.item_code LIKE ? OR i.sku_number LIKE ?)";
        $search_term = "%$search%";
        $params[] = $search_term;
        $params[] = $search_term;
        $params[] = $search_term;
        $types .= 'sss';
    }
    
    $query .= " ORDER BY i.name LIMIT 100";
    
    // Prepare and execute the statement
    if (!empty($params)) {
        $stmt = $conn->prepare($query);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $result = $conn->query($query);
    }
    
    $items = [];
    while ($row = $result->fetch_assoc()) {
        // Get tax rate
        $tax_rate = 0;
        if ($row['tax_rate_id']) {
            $tax_stmt = $conn->prepare("SELECT rate FROM tax_rates WHERE id = ?");
            $tax_stmt->bind_param("i", $row['tax_rate_id']);
            $tax_stmt->execute();
            $tax_result = $tax_stmt->get_result();
            if ($tax_row = $tax_result->fetch_assoc()) {
                $tax_rate = $tax_row['rate'];
            }
        }
        
        $items[] = [
            'id' => $row['id'],
            'item_code' => $row['item_code'],
            'sku_number' => $row['sku_number'],
            'name' => $row['name'],
            'retail_price' => $row['retail_price'],
            'tax_rate_id' => $row['tax_rate_id'],
            'tax_rate' => $tax_rate,
            'category_name' => $row['category_name'],
            'subcategory_name' => $row['subcategory_name']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'items' => $items,
        'total' => count($items)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching items: ' . $e->getMessage()
    ]);
}
?>
