<?php
session_start();
require_once '../assets/db_connect.php';

$product_id = $_GET['product_id'] ?? 0;
$shop_id = $_GET['shop_id'] ?? 0;

if (!$product_id || !$shop_id) {
    die("Invalid parameters");
}

// Get product details
$product_sql = "SELECT * FROM products WHERE id = ? AND shop_id = ?";
$product_stmt = $pdo->prepare($product_sql);
$product_stmt->execute([$product_id, $shop_id]);
$product = $product_stmt->fetch(PDO::FETCH_ASSOC);

// Get available batches with stock
$sql = "SELECT 
            pb.*,
            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
        HAVING available_qty > 0
        ORDER BY pb.expiry_date ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute([$product_id, $shop_id]);
$batches = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($batches)) {
    echo '<div class="alert alert-warning">No batches available for this product.</div>';
    return;
}
?>

<div class="text-center mb-3">
    <h5><?= htmlspecialchars($product['name']) ?></h5>
    <p class="text-muted">Select a batch to add to cart</p>
</div>

<div class="batch-grid">
    <?php foreach($batches as $batch): ?>
        <div class="batch-item" onclick="selectBatch(<?= $batch['id'] ?>)" 
             data-batch-id="<?= $batch['id'] ?>">
            <div class="batch-info">
                <div class="batch-no">Batch: <?= htmlspecialchars($batch['batch_no']) ?></div>
                <div class="batch-stock <?= $batch['available_qty'] <= 10 ? 'low' : '' ?>">
                    Stock: <?= $batch['available_qty'] ?> units
                </div>
                <div class="batch-price">
                    Price: TZS <?= number_format($batch['sell_price'], 2) ?>
                </div>
                <?php if($batch['expiry_date']): ?>
                    <div class="batch-expiry">
                        Exp: <?= date('M Y', strtotime($batch['expiry_date'])) ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    <?php endforeach; ?>
</div>