<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../includes/auth.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// Check permission
if (!has_permission('inventory')) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden: Stock Management permission required']);
    exit;
}

$action = $_GET['action'] ?? '';
$db = db();

if ($action === 'get_batches') {
    $item_id = $_GET['item_id'] ?? 0;
    if (!$item_id) {
        echo json_encode([]);
        exit;
    }

    $stmt = $db->prepare("SELECT id, batch_number, quantity, expiry_date, cost_price FROM inventory_batches WHERE item_id = ? AND quantity > 0 ORDER BY expiry_date ASC");
    $stmt->execute([$item_id]);
    $batches = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($batches);
    exit;
}

echo json_encode(['error' => 'Invalid action']);