<?php
$pageTitle = 'Categorías de Exámenes';
require_once __DIR__ . '/../../config/config.php';
requireLogin();

$db = getDB();

// Procesar formulario
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        if ($action == 'add') {
            $stmt = $db->prepare("INSERT INTO categorias_examenes (nombre, descripcion) VALUES (?, ?)");
            $stmt->execute([sanitize($_POST['nombre']), sanitize($_POST['descripcion'])]);
            showAlert('Categoría creada');
        }
        
        if ($action == 'edit') {
            $stmt = $db->prepare("UPDATE categorias_examenes SET nombre = ?, descripcion = ?, activo = ? WHERE id = ?");
            $stmt->execute([
                sanitize($_POST['nombre']),
                sanitize($_POST['descripcion']),
                isset($_POST['activo']) ? 1 : 0,
                intval($_POST['id'])
            ]);
            showAlert('Categoría actualizada');
        }
        
        if ($action == 'delete') {
            $stmt = $db->prepare("DELETE FROM categorias_examenes WHERE id = ?");
            $stmt->execute([intval($_POST['id'])]);
            showAlert('Categoría eliminada');
        }
        
        header('Location: categorias.php');
        exit;
    } catch (PDOException $e) {
        showAlert('Error: ' . $e->getMessage(), 'danger');
    }
}

$stmt = $db->query("
    SELECT c.*, (SELECT COUNT(*) FROM examenes WHERE categoria_id = c.id) as num_examenes
    FROM categorias_examenes c ORDER BY c.nombre
");
$categorias = $stmt->fetchAll();

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

<div class="d-flex justify-content-between align-items-center mt-4 mb-4">
    <h2><i class="bi bi-folder"></i> Categorías de Exámenes</h2>
    <a href="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> Nueva Categoría</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">Nombre *</label>
                        <input type="text" name="nombre" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Descripción</label>
                        <textarea name="descripcion" class="form-control" rows="2"></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-plus"></i> Agregar
                    </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> Categorías</h5>
            </div>
            <div class="card-body">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Nombre</th>
                            <th>Descripción</th>
                            <th>Exámenes</th>
                            <th>Estado</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($categorias as $cat): ?>
                        <tr>
                            <td><strong><?= htmlspecialchars($cat['nombre']) ?></strong></td>
                            <td><?= htmlspecialchars($cat['descripcion']) ?: '-' ?></td>
                            <td><span class="badge bg-secondary"><?= $cat['num_examenes'] ?></span></td>
                            <td>
                                <?php if ($cat['activo']): ?>
                                <span class="badge bg-success">Activo</span>
                                <?php else: ?>
                                <span class="badge bg-danger">Inactivo</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" 
                                        data-bs-target="#editModal<?= $cat['id'] ?>">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <?php if ($cat['num_examenes'] == 0): ?>
                                <form method="POST" class="d-inline" onsubmit="return confirm('¿Eliminar?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $cat['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                                <?php endif; ?>
                            </td>
                        </tr>

                        <!-- Modal Editar -->
                        <div class="modal fade" id="editModal<?= $cat['id'] ?>" tabindex="-1">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <form method="POST">
                                        <input type="hidden" name="action" value="edit">
                                        <input type="hidden" name="id" value="<?= $cat['id'] ?>">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Editar Categoría</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="mb-3">
                                                <label class="form-label">Nombre</label>
                                                <input type="text" name="nombre" class="form-control" required
                                                       value="<?= htmlspecialchars($cat['nombre']) ?>">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Descripción</label>
                                                <textarea name="descripcion" class="form-control" rows="2"><?= htmlspecialchars($cat['descripcion']) ?></textarea>
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="activo"
                                                       <?= $cat['activo'] ? 'checked' : '' ?>>
                                                <label class="form-check-label">Activo</label>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                                            <button type="submit" class="btn btn-primary">Guardar</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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