<?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);
$offset = ($page - 1) * $records_per_page;

// Function to get all employees
function getEmployees($conn) {
    try {
        $stmt = $conn->query("SELECT codempleado, CONCAT(apellidoPaterno, ' ', apellidoMaterno, ', ', nombres) AS nombre_completo FROM templeado ORDER BY nombre_completo");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        return [];
    }
}

// Function to get all modules
function getModules($conn) {
    try {
        $stmt = $conn->query("SELECT codmodulos, modulo FROM tmodulos ORDER BY codmodulos");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        return [];
    }
}

// Save/Update module assignments
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['empleado']) && isset($_POST['modulos'])) {
    $empleado = $_POST['empleado'];
    
    try {
        // First, delete existing assignments
        $stmt_delete = $conn->prepare("DELETE FROM templeadomodulo WHERE codempleado = ?");
        $stmt_delete->execute([$empleado]);
        
        // Insert new assignments
        $stmt_insert = $conn->prepare("INSERT INTO templeadomodulo (codempleado, codmodulos) VALUES (?, ?)");
        
        foreach ($_POST['modulos'] as $modulo) {
            $stmt_insert->execute([$empleado, $modulo]);
        }
        
        $_SESSION['success'] = "Asignaciones de módulos actualizadas correctamente";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error al guardar asignaciones: " . $e->getMessage();
    }
    
    header("Location: empleado_modulos.php");
    exit();
}

// Get existing module assignments for selected employee
$existing_assignments = [];
$selected_employee = isset($_GET['empleado']) ? (int)$_GET['empleado'] : null;

if ($selected_employee) {
    try {
        $stmt = $conn->prepare("SELECT codmodulos FROM templeadomodulo WHERE codempleado = ?");
        $stmt->execute([$selected_employee]);
        $existing_assignments = $stmt->fetchAll(PDO::FETCH_COLUMN);
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error al obtener asignaciones existentes: " . $e->getMessage();
    }
}

$empleados = getEmployees($conn);
$modulos = getModules($conn);
?>

<div class="col-md-10 p-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Asignación de Módulos a Usuarios</h2>
    </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; ?>

    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" action="empleado_modulos.php">
                <div class="row">
                    <div class="col-md-6">
                        <label class="form-label">Seleccionar Usuario</label>
                        <select name="empleado" class="form-control" onchange="this.form.submit()">
                            <option value="">Seleccione un Usuario</option>
                            <?php foreach ($empleados as $empleado): ?>
                                <option value="<?php echo $empleado['codempleado']; ?>" 
                                    <?php echo ($selected_employee == $empleado['codempleado']) ? 'selected' : ''; ?>>
                                    <?php echo $empleado['nombre_completo']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <?php if ($selected_employee): ?>
    <form method="POST" action="empleado_modulos.php">
        <input type="hidden" name="empleado" value="<?php echo $selected_employee; ?>">
        
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">Módulos Disponibles</h5>
                <div class="row">
                    <?php foreach ($modulos as $modulo): ?>
                        <div class="col-md-4 mb-2">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" 
                                    name="modulos[]" 
                                    value="<?php echo $modulo['codmodulos']; ?>"
                                    id="modulo_<?php echo $modulo['codmodulos']; ?>"
                                    <?php echo in_array($modulo['codmodulos'], $existing_assignments) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="modulo_<?php echo $modulo['codmodulos']; ?>">
                                    <?php echo $modulo['modulo']; ?>
                                </label>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="mt-3">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Guardar Asignaciones
                    </button>
                </div>
            </div>
        </div>
    </form>
    <?php endif; ?>
</div>

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