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

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['store_id'])) {
    $store_id = intval($_GET['store_id']);
    
    // Get items with stock for the specified store
    $items_query = "
        SELECT i.id, i.name, i.item_code,
               COALESCE(
                   (SELECT SUM(CASE WHEN im.movement_type = 'in' THEN im.quantity ELSE 0 END) -
                           SUM(CASE WHEN im.movement_type = 'out' THEN im.quantity ELSE 0 END) +
                           SUM(CASE WHEN im.movement_type = 'adjustment' THEN im.quantity ELSE 0 END)
                    FROM inventory_movements im 
                    WHERE im.item_id = i.id AND (im.store_id = ? OR (im.store_id IS NULL AND ? = 1))
                   ), 0
               ) as current_stock
        FROM items i
        WHERE i.item_role IN ('stock', 'material')
        ORDER BY i.name
    ";
    
    $stmt = $conn->prepare($items_query);
    $stmt->bind_param("ii", $store_id, $store_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $items = [];
    while ($row = $result->fetch_assoc()) {
        $items[] = [
            'id' => $row['id'],
            'name' => $row['name'],
            'item_code' => $row['item_code'],
            'current_stock' => floatval($row['current_stock'])
        ];
    }
    
    $stmt->close();
    
    header('Content-Type: application/json');
    echo json_encode($items);
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request']);
}
?>
