<?php
// Copied from clinicademo fefo_lots.php — no clinicademo-specific paths found
// Path: fefo_lots.php (AJAX — FEFO lot list for warehouse)
// Uses: core/autoload.php (exists in both), no scanner dependencies
require_once __DIR__ . '/core/autoload.php';
header('Content-Type: application/json');

if (session_status() !== PHP_SESSION_ACTIVE) {
    @session_start();
}

$userId = $_SESSION['user_id'] ?? null;
if (!$userId) {
    echo json_encode(['error' => 'No autenticado.']);
    exit;
}
$con = Database::getCon();
$userIdInt = (int)$userId;
$result = $con->query("SELECT role FROM user WHERE id=$userIdInt LIMIT 1");
if (!$result || $result->num_rows === 0) {
    echo json_encode(['error' => 'Usuario no encontrado.']);
    exit;
}
$role = $result->fetch_object()->role;
$allowedRoles = ['admin', 'administracion', 'medico'];
if (!in_array($role, $allowedRoles, true)) {
    echo json_encode(['error' => 'No tiene permisos.']);
    exit;
}

$itemId      = isset($_GET['item_id'])      ? (int)($_GET['item_id'])      : 0;
$warehouseId = isset($_GET['warehouse_id']) ? (int)($_GET['warehouse_id']) : 0;

if ($itemId <= 0 || $warehouseId <= 0) {
    echo json_encode(['error' => 'item_id y warehouse_id son requeridos.']);
    exit;
}

$itemId      = (int)$itemId;
$warehouseId = (int)$warehouseId;

$sql = "SELECT l.id AS lot_id, l.lot_number, l.fecha_vencimiento, l.quantity,
               DATEDIFF(l.fecha_vencimiento, CURDATE()) AS days_to_expiry
        FROM inventory_lot l
        WHERE l.item_id=$itemId
          AND l.warehouse_id=$warehouseId
          AND l.quantity > 0
          AND (l.fecha_vencimiento IS NULL OR l.fecha_vencimiento >= CURDATE())
        ORDER BY
          CASE WHEN l.fecha_vencimiento IS NULL THEN 1 ELSE 0 END ASC,
          l.fecha_vencimiento ASC,
          l.id ASC";

$r = $con->query($sql);
$lots = [];
$totalAvailable = 0;
while ($row = $r->fetch_object()) {
    $lots[] = [
        'lot_id'           => (int)$row->lot_id,
        'lot_number'       => $row->lot_number,
        'fecha_vencimiento' => $row->fecha_vencimiento,
        'quantity'         => (float)$row->quantity,
        'days_to_expiry'   => $row->fecha_vencimiento !== null ? (int)$row->days_to_expiry : null,
    ];
    $totalAvailable += (float)$row->quantity;
}

echo json_encode([
    'lots'            => $lots,
    'total_available' => $totalAvailable,
]);
