<?php
session_start();
include 'conexion.php';

// Verificar si el usuario tiene rol de administrador
if (!isset($_SESSION['rol']) || $_SESSION['rol'] !== 'admin') {
    header("Location: login.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nombre = $_POST['nombre'];
    $rut = $_POST['rut'];
    $email = $_POST['email'];
    $password = password_hash('123456', PASSWORD_BCRYPT); // Contraseña inicial por defecto
    $rol = 'conserje';

    // Verificar si el correo ya existe
    $stmt_check = $conn->prepare("SELECT * FROM usuarios WHERE email = ?");
    $stmt_check->bind_param("s", $email);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();

    if ($result_check->num_rows > 0) {
        $error = "El correo ya está registrado.";
    } else {
        // Insertar nuevo conserje
        $stmt = $conn->prepare("INSERT INTO usuarios (nombre, rut, email, password, rol, estado) VALUES (?, ?, ?, ?, ?, 'activo')");
        $stmt->bind_param("sssss", $nombre, $rut, $email, $password, $rol);

        if ($stmt->execute()) {
            $success = "Conserje creado con éxito. Contraseña inicial: '123456'";
        } else {
            $error = "Error al crear el conserje: " . $stmt->error;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crear Conserje</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <h1>Crear Conserje</h1>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php elseif (isset($success)): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>

    <form method="POST" action="">
        <div class="mb-3">
            <label for="nombre" class="form-label">Nombre</label>
            <input type="text" class="form-control" id="nombre" name="nombre" required>
        </div>
        <div class="mb-3">
            <label for="rut" class="form-label">RUT</label>
            <input type="text" class="form-control" id="rut" name="rut" required>
        </div>
        <div class="mb-3">
            <label for="email" class="form-label">Correo Electrónico</label>
            <input type="email" class="form-control" id="email" name="email" required>
        </div>
        <button type="submit" class="btn btn-primary">Crear Conserje</button>
    </form>
    <a href="admin_dashboard.php" class="btn btn-secondary mt-3">Volver</a>
</div>
</body>
</html>
