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

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

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

$batch_id = isset($_POST['batch_id']) ? (int)$_POST['batch_id'] : 0;
$shop_id = isset($_POST['shop_id']) ? (int)$_POST['shop_id'] : 0;

error_log("Check stock request - Batch ID: $batch_id, Shop ID: $shop_id");

if ($batch_id <= 0 || $shop_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

try {
    // Simple stock check - just check if batch exists
    $sql = "SELECT 
                pb.id,
                pb.batch_no,
                p.name as product_name
            FROM product_batches pb
            JOIN products p ON pb.product_id = p.id
            WHERE pb.id = ?
            AND pb.shop_id = ?
            AND pb.is_active = 1";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$batch_id, $shop_id]);
    $batch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$batch) {
        echo json_encode(['success' => false, 'message' => 'Batch not found']);
        exit;
    }
    
    // For now, return success - we'll add actual stock calculation later
    echo json_encode([
        'success' => true,
        'message' => 'Batch available',
        'product_name' => $batch['product_name'],
        'batch_no' => $batch['batch_no']
    ]);
    
} catch (Exception $e) {
    error_log("Stock check error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>