<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../core/SecurityHeaders.php';
require_once __DIR__ . '/../core/Auth.php';
require_once __DIR__ . '/../core/Router.php';
require_once __DIR__ . '/../core/Model.php';
require_once __DIR__ . '/../core/helpers.php';

// Set security headers for API
SecurityHeaders::setApi();

// Handle stock-info request directly
Auth::requireLogin();
Auth::requireActiveTenant();

$productId = filter_input(INPUT_GET, 'product_id', FILTER_VALIDATE_INT);
$locationId = filter_input(INPUT_GET, 'location_id', FILTER_VALIDATE_INT);
$tid = Auth::tenantId();

if (!$productId || !$locationId) {
    jsonResponse(['error' => 'product_id and location_id are required'], 400);
}

// Get stock info
$stmt = db()->prepare("
    SELECT COALESCE(SUM(s.quantity), 0) as stock
    FROM stock s
    WHERE s.product_id = ? AND s.location_id = ? AND s.tenant_id = ?
");
$stmt->execute([$productId, $locationId, $tid]);
$stock = (float)$stmt->fetchColumn();

// Get batch info if product has batch tracking
$product = db()->prepare("SELECT batch_tracking FROM products WHERE id = ? AND tenant_id = ?");
$product->execute([$productId, $tid]);
$productData = $product->fetch();

$batches = [];
if ($productData && $productData['batch_tracking']) {
    $batchStmt = db()->prepare("
        SELECT b.id, b.batch_no, b.expiry_date, COALESCE(s.quantity, 0) as quantity
        FROM batches b
        LEFT JOIN stock s ON s.batch_id = b.id AND s.location_id = ? AND s.tenant_id = ?
        WHERE b.product_id = ? AND b.tenant_id = ? AND COALESCE(s.quantity, 0) > 0
        ORDER BY b.expiry_date ASC
    ");
    $batchStmt->execute([$locationId, $tid, $productId, $tid]);
    $batches = $batchStmt->fetchAll();
}

jsonResponse([
    'stock' => $stock,
    'batches' => $batches,
    'batch_tracking' => $productData['batch_tracking'] ?? 0
]);
