<?php
$pageTitle = 'Asignar Insumos a Exámenes';
require_once __DIR__ . '/../../config/config.php';
requireLogin();

$db = getDB();
$examen_id = intval($_GET['examen_id'] ?? 0);

// Obtener examen
$stmt = $db->prepare("SELECT * FROM examenes WHERE id = ?");
$stmt->execute([$examen_id]);
$examen = $stmt->fetch();

if (!$examen) {
    showAlert('Examen no encontrado', 'danger');
    header('Location: ../examenes/list.php');
    exit;
}

// Procesar formulario
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        if ($action == 'add') {
            $stmt = $db->prepare("
                INSERT INTO examenes_insumos (examen_id, insumo_id, cantidad)
                VALUES (?, ?, ?)
            ");
            $stmt->execute([
                $examen_id,
                intval($_POST['insumo_id']),
                floatval($_POST['cantidad'])
            ]);
            showAlert('Insumo asignado correctamente');
        }
        
        if ($action == 'delete') {
            $stmt = $db->prepare("DELETE FROM examenes_insumos WHERE id = ?");
            $stmt->execute([intval($_POST['id'])]);
            showAlert('Insumo removido');
        }
        
        header('Location: insumos_examen.php?examen_id=' . $examen_id);
        exit;
    } catch (PDOException $e) {
        showAlert('Error: ' . $e->getMessage(), 'danger');
    }
}

// Obtener insumos asignados
$stmt = $db->prepare("
    SELECT ei.*, i.codigo, i.nombre, i.unidad_medida
    FROM examenes_insumos ei
    JOIN insumos i ON ei.insumo_id = i.id
    WHERE ei.examen_id = ?
");
$stmt->execute([$examen_id]);
$insumosAsignados = $stmt->fetchAll();

// Obtener todos los insumos para el select
$stmt = $db->query("SELECT * FROM insumos WHERE activo = 1 ORDER BY nombre");
$insumos = $stmt->fetchAll();

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mt-4 mb-4">
    <div>
        <h2><i class="bi bi-link-45deg"></i> Insumos del Examen</h2>
        <p class="text-muted mb-0">
            Examen: <strong><?= htmlspecialchars($examen['nombre']) ?></strong> (<?= $examen['codigo'] ?>)
        </p>
    </div>
    <a href="../examenes/list.php" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left"></i> Volver a Exámenes
    </a>
</div>

<div class="row">
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-plus-circle"></i> Asignar Insumo</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">Insumo *</label>
                        <select name="insumo_id" class="form-select" required>
                            <option value="">Seleccione...</option>
                            <?php foreach ($insumos as $ins): ?>
                            <option value="<?= $ins['id'] ?>">
                                <?= $ins['codigo'] ?> - <?= $ins['nombre'] ?> (<?= $ins['unidad_medida'] ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Cantidad por Examen *</label>
                        <input type="number" name="cantidad" class="form-control" required 
                               min="0.01" step="0.01" value="1">
                    </div>
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-plus"></i> Asignar
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-list-ul"></i> Insumos Asignados</h5>
            </div>
            <div class="card-body">
                <?php if (empty($insumosAsignados)): ?>
                <div class="alert alert-info">
                    No hay insumos asignados a este examen. Los insumos se descontarán automáticamente del inventario cuando se genere una orden.
                </div>
                <?php else: ?>
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Código</th>
                            <th>Insumo</th>
                            <th>Cantidad</th>
                            <th>Unidad</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($insumosAsignados as $ia): ?>
                        <tr>
                            <td><?= $ia['codigo'] ?></td>
                            <td><?= $ia['nombre'] ?></td>
                            <td><strong><?= $ia['cantidad'] ?></strong></td>
                            <td><?= $ia['unidad_medida'] ?></td>
                            <td>
                                <form method="POST" class="d-inline" onsubmit="return confirm('¿Remover este insumo?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $ia['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
