<?php
include_once 'includes/header.php';
include_once 'config/database.php';

$database = new Database();
$conn = $database->getConnection();

// Pagination settings
$records_per_page = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page); // Ensure page is at least 1
$offset = ($page - 1) * $records_per_page;

// Delete logic
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    try {
        $stmt = $conn->prepare("DELETE FROM tmodulos WHERE codmodulos = ?");
        $stmt->execute([$id]);
        $_SESSION['success'] = "Módulo eliminado correctamente";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error al eliminar el módulo: " . $e->getMessage();
    }
    header("Location: modulos.php");
    exit();
}

// Insert/Update logic
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $modulo = $_POST['modulo'];
    
    if (isset($_POST['id'])) {
        // Update
        try {
            $stmt = $conn->prepare("UPDATE tmodulos SET modulo = ? WHERE codmodulos = ?");
            $stmt->execute([$modulo, $_POST['id']]);
            $_SESSION['success'] = "Módulo actualizado correctamente";
        } catch(PDOException $e) {
            $_SESSION['error'] = "Error al actualizar el módulo: " . $e->getMessage();
        }
    } else {
        // Insert
        try {
            $stmt = $conn->prepare("INSERT INTO tmodulos (modulo) VALUES (?)");
            $stmt->execute([$modulo]);
            $_SESSION['success'] = "Módulo creado correctamente";
        } catch(PDOException $e) {
            $_SESSION['error'] = "Error al crear el módulo: " . $e->getMessage();
        }
    }
    header("Location: modulos.php");
    exit();
}

// Edit logic - fetch single record
$editData = null;
if (isset($_GET['edit'])) {
    try {
        $stmt = $conn->prepare("SELECT * FROM tmodulos WHERE codmodulos = ?");
        $stmt->execute([$_GET['edit']]);
        $editData = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error al obtener el módulo: " . $e->getMessage();
    }
}

// Count total records for pagination
try {
    $stmt = $conn->query("SELECT COUNT(*) FROM tmodulos");
    $total_records = $stmt->fetchColumn();
    $total_pages = ceil($total_records / $records_per_page);
} catch(PDOException $e) {
    $_SESSION['error'] = "Error al contar registros: " . $e->getMessage();
    $total_pages = 1;
}

// Fetch records with pagination
try {
    $query = "SELECT * FROM tmodulos ORDER BY codmodulos LIMIT $records_per_page OFFSET $offset";
    
    $stmt = $conn->query($query);
    $modulos = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $_SESSION['error'] = "Error al obtener los datos: " . $e->getMessage();
    $modulos = [];
}
?>

<div class="col-md-10 p-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Gestión de Módulos</h2>
        <?php if (!isset($_GET['edit']) && !isset($_GET['create'])): ?>
            <a href="?create" class="btn btn-primary">
                <i class="fas fa-plus"></i> Nuevo Módulo
            </a>
        <?php endif; ?>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success">
            <?php 
            echo $_SESSION['success']; 
            unset($_SESSION['success']);
            ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger">
            <?php 
            echo $_SESSION['error']; 
            unset($_SESSION['error']);
            ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['create']) || isset($_GET['edit'])): ?>
        <!-- Form for create/edit -->
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title"><?php echo isset($_GET['edit']) ? 'Editar' : 'Crear' ?> Módulo</h5>
                <form method="POST" action="modulos.php">
                    <?php if (isset($_GET['edit'])): ?>
                        <input type="hidden" name="id" value="<?php echo $editData['codmodulos']; ?>">
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label class="form-label">Nombre del Módulo</label>
                        <input type="text" class="form-control" name="modulo" maxlength="250"
                               value="<?php echo $editData ? $editData['modulo'] : ''; ?>" required>
                    </div>

                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Guardar
                        </button>
                        <a href="modulos.php" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancelar
                        </a>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <!-- List of records -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Módulo</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($modulos as $modulo): ?>
                            <tr>
                                <td><?php echo $modulo['codmodulos']; ?></td>
                                <td><?php echo $modulo['modulo']; ?></td>
                                <td>
                                    <a href="?edit=<?php echo $modulo['codmodulos']; ?>" class="btn btn-sm btn-warning">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?delete=<?php echo $modulo['codmodulos']; ?>" 
                                       class="btn btn-sm btn-danger"
                                       onclick="return confirm('¿Está seguro de eliminar este módulo?')">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <div class="d-flex justify-content-between align-items-center mt-3">
                <div class="pagination-info">
                    Mostrando página <?php echo $page; ?> de <?php echo $total_pages; ?>
                </div>
                <div class="d-flex align-items-center gap-3">
                    <nav aria-label="Page navigation">
                        <ul class="pagination mb-0">
                            <?php if ($page > 1): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=1">
                                        <i class="fas fa-angle-double-left"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo ($page - 1); ?>">
                                        <i class="fas fa-angle-left"></i>
                                    </a>
                                </li>
                            <?php endif; ?>

                            <?php
                            $start_page = max(1, $page - 2);
                            $end_page = min($total_pages, $start_page + 4);
                            
                            for ($i = $start_page; $i <= $end_page; $i++): ?>
                                <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>

                            <?php if ($page < $total_pages): ?>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo ($page + 1); ?>">
                                        <i class="fas fa-angle-right"></i>
                                    </a>
                                </li>
                                <li class="page-item">
                                    <a class="page-link" href="?page=<?php echo $total_pages; ?>">
                                        <i class="fas fa-angle-double-right"></i>
                                    </a>
                                </li>
                            <?php endif; ?>
                        </ul>
                    </nav>

                     <!-- Direct page input -->
                     <form class="d-flex align-items-center gap-2" method="GET">
                        <label class="mb-0">Ir a página:</label>
                        <input type="number" name="page" class="form-control form-control-sm" 
                               style="width: 70px;" min="1" max="<?php echo $total_pages; ?>" 
                               value="<?php echo $page; ?>">
                        <button type="submit" class="btn btn-sm btn-primary">Ir</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
include_once 'includes/footer.php';
?>