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

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

try {
    $db = getDatabaseConnection();
    
    // Get product info
    $sql = "SELECT p.* FROM products p WHERE p.id = ? AND p.shop_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$product_id, $_SESSION['user']['shop_id']]);
    $product = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$product) {
        echo json_encode(['success' => false, 'message' => 'Product not found']);
        exit;
    }
    
    // Get available batches with stock
    $sql = "SELECT 
                pb.id,
                pb.batch_no,
                pb.expiry_date,
                pb.cost_price,
                pb.sell_price,
                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 product_batches pb
            LEFT JOIN inventory_movements im ON pb.id = im.batch_id
            WHERE pb.product_id = ? 
            AND pb.shop_id = ?
            AND pb.is_active = 1
            GROUP BY pb.id, pb.batch_no, pb.expiry_date, pb.cost_price, pb.sell_price
            HAVING available_qty > 0
            ORDER BY pb.expiry_date ASC";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$product_id, $_SESSION['user']['shop_id']]);
    $batches = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'product' => $product,
        'batches' => $batches
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?>