<?php
require_once '../../../auth/check_session.php';
require_once '../../../config/database.php';

$batch_id = $_POST['batch_id'] ?? 0;

try {
    $db = getDatabaseConnection();
    
    $sql = "SELECT 
                COALESCE(SUM(
                    CASE 
                        WHEN im.movement_type IN ('PURCHASE', 'RETURN') THEN im.change_qty
                        WHEN im.movement_type IN ('SALE', 'ADJUSTMENT') THEN -im.change_qty
                        ELSE 0
                    END
                ), 0) as available_qty
            FROM inventory_movements im
            JOIN product_batches pb ON im.batch_id = pb.id
            WHERE pb.id = ? 
            AND pb.shop_id = ?";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$batch_id, $_SESSION['user']['shop_id']]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo $result['available_qty'] ?? 0;
    
} catch (PDOException $e) {
    echo "0";
}
?>