<?php
session_start();
require '../assets/db_connect.php';
header('Content-Type: application/json');

if (!isset($_POST['product_id']) || !isset($_POST['shop_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing parameters']);
    exit;
}

$product_id = (int)$_POST['product_id'];
$shop_id = (int)$_POST['shop_id'];

// Get batches with available stock
$stmt = $pdo->prepare("
    SELECT pb.id, pb.batch_no, pb.sell_price, pb.expiry_date,
           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.sell_price, pb.expiry_date
    HAVING available_qty > 0
    ORDER BY pb.expiry_date ASC, pb.created_at ASC
");

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

if (empty($batches)) {
    echo json_encode([
        'status' => 'error', 
        'message' => 'No available batches for this product'
    ]);
} else {
    // Format dates
    foreach ($batches as &$batch) {
        if ($batch['expiry_date']) {
            $batch['expiry_date'] = date('d/m/Y', strtotime($batch['expiry_date']));
        }
    }
    
    echo json_encode([
        'status' => 'success',
        'batches' => $batches
    ]);
}
?>