<?php
session_start();

if (!isset($_SESSION['login'])) {
    header('Location: login.php');
    exit();
}

//echo "<h4>Bem-vindo, " . htmlspecialchars($_SESSION['nome_usuario']) . "!</h4>";
//echo "<a href='logout.php'>Sair</a>";
?><?php
$conn = new mysqli("localhost", "kaltekgo_admin", "kaltek@2024", "kaltekgo_avila");
if ($conn->connect_error) {
    die("Erro de conexão: " . $conn->connect_error);
}

$sql = "SELECT * FROM inventario_informatica";
$result = $conn->query($sql);

$tipos_result = $conn->query("SELECT DISTINCT UPPER(tipo) as tipo FROM inventario_informatica WHERE tipo IS NOT NULL AND tipo != ''");
$tipos = [];
if ($tipos_result->num_rows > 0) {
    while ($row = $tipos_result->fetch_assoc()) {
        $tipos[] = $row['tipo'];
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lista de Equipamentos</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #ffffff;
            margin: 20px;
            color: #000000;
        }

        h4 {
            color: #000000;
            margin-left: 0px;
            margin-top: 35px;
            margin-bottom: 15px;
        }
        
        p {
            color: #000000;
            margin-left: 15px;
            margin-top: 35px;
            margin-bottom: 15px;
            display: flex; 
            align-items: center; gap: 10px;
        }

        .btn-cadastrar {
            margin-left: 15px;
            margin-bottom: 10px;
        }

        .filtro-btns {
            margin-left: 15px;
            margin-bottom: 15px;
            display: flex;
            flex-wrap: wrap;
        }

        .filtro-btns .btn {
            margin-right: 10px;
            margin-bottom: 5px;
        }

        .table-responsive-custom {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            margin: 0 15px 20px 15px;
        }

        table {
            white-space: nowrap;
            width: 100%;
            border-collapse: collapse;
            background-color: #ffffff;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            text-transform: uppercase;
            min-width: 700px;
        }

        th, td {
            padding: 12px 15px;
            text-align: left;
            font-size: 12px;
            border: 1px solid #000000;
            white-space: nowrap;
        }

        th {
            background-color: #000000;
            color: #ffffff;
        }

        tr:nth-child(even) {
            background-color: #f4f4f4;
        }

        tr:hover {
            background-color: #e0e0e0;
        }

  .cabecalho-superior {
    display: flex;
    justify-content: space-between; /* separa h4 à esquerda e p à direita */
    align-items: center;
    margin: 15px;
    flex-wrap: wrap; /* quebra para mobile se precisar */
}

.boas-vindas {
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}


        @media (max-width: 768px) {
            .btn-cadastrar,
            .filtro-btns .btn {
                width: 92% !important;
                display: flex;
                justify-content: center;
                align-items: center;
                margin: 10px auto;
                font-size: 14px;
                height: 40px;
                padding: 8px 10px;
            }

            a.btn-cadastrar {
                display: block;
                text-align: center;
                margin-left: 13px !important;
            }

            .table th,
            .table td {
                min-width: 125px;
                white-space: nowrap;
                height: 20px;
                font-size: 14px;
                padding: 8px 10px;
            }

            h4 {
                text-align: center;
            }
        }

        .linha-equipamento {
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="cabecalho-superior">
    <h4 class="text-uppercase">Equipamentos/Dispositivos</h4>
    
    <p class="boas-vindas">
        <span>Bem-vindo, <strong><a class="text-uppercase"><?php echo htmlspecialchars($_SESSION['nome_usuario']);?>!</a></strong></span>
        <a href="logout.php" class="btn btn-success btn-sm">Sair</a> 
    </p>
</div>

<!--h4 class="text-uppercase">Equipamentos/Dispositivos</h4-->

<?php if (strtolower($_SESSION['tipoUsuario']) !== 'diretoria'): ?>
    <a href="choose.php" class="btn btn-primary btn-cadastrar">
        Cadastrar Novo Dispositivo/Equipamento
    </a>
<?php endif; ?>


<div class="filtro-btns hidden-xs">
    <button class="btn btn-default filtro" data-filtro="todos">Todos</button>
    <?php foreach ($tipos as $tipo): ?>
        <button class="btn btn-info filtro text-capitalize" data-filtro="<?= $tipo ?>"><?= ucfirst(strtolower($tipo)) ?></button>
    <?php endforeach; ?>
</div>

<div class="visible-xs" style="margin: 0 15px 15px 15px;">
    <select id="filtro-mobile" class="form-control text-capitalize">
        <option value="todos">Todos</option>
        <?php foreach ($tipos as $tipo): ?>
            <option class="text-capitalize" value="<?= $tipo ?>"><?= ucfirst(strtolower($tipo)) ?></option>
        <?php endforeach; ?>
    </select>
</div>

<!-- Tabela Principal -->
<div class="table-responsive-custom" id="tabelaPrincipal">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Fabricante</th>
                <th>Modelo</th>
                <th>Ano Fabricação</th>
                <th>Tipo</th>
                <th>Localização</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result->num_rows > 0): ?>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <?php if (strtoupper($row['tipo']) !== 'WORKSTATION' && strtoupper($row['tipo']) !== 'SERVIDOR'): ?>
                        <tr class="linha-equipamento" 
                            data-tipo="<?= strtoupper($row['tipo']) ?>" 
                            data-rede="<?= htmlspecialchars($row['nomeRedeWireless']) ?>"
                            data-senha="<?= htmlspecialchars($row['senhaRedeWireless']) ?>"
                            data-user="<?= htmlspecialchars($row['userAdm']) ?>"
                            data-pass="<?= htmlspecialchars($row['senhaAdm']) ?>"
                            data-ip="<?= htmlspecialchars($row['ipRede']) ?>">
                            
                            <td><?= htmlspecialchars($row['fabricante']) ?></td>
                            <td><?= htmlspecialchars($row['modelo']) ?></td>
                            <td><?= empty($row['anofabricacao']) || $row['anofabricacao'] == '0' ? 'Dados não encontrados' : htmlspecialchars($row['anofabricacao']) ?></td>
                            <td><?= htmlspecialchars($row['tipo']) ?></td>
                            <td><?= htmlspecialchars($row['localizacao']) ?></td>
                        </tr>
                    <?php endif; ?>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="5">Nenhum equipamento encontrado.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Tabela Workstation/Servidor -->
<div class="table-responsive-custom" id="tabelaWorkstation" style="display:none">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Código</th>
                <th>Processador</th>
                <th>Memória</th>
                <th>Armazenamento</th>
                <th>GPU</th>
                <th>Ano Fabricação</th>
                <th>Tipo</th>
                <th>Localização</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $result->data_seek(0);
            while ($row = $result->fetch_assoc()):
                if (in_array(strtoupper($row['tipo']), ['WORKSTATION'])):
                    $classe = strtoupper($row['tipo']) === 'WORKSTATION' ? 'info' : 'success';
            ?>
            <tr class="<?= $classe ?>">
                <td><?= htmlspecialchars($row['codigo']) ?></td>
                <td><?= htmlspecialchars($row['processador']) ?></td>
                <td><?= htmlspecialchars($row['memoria']) ?></td>
                <td><?= htmlspecialchars($row['armazenamento']) ?></td>
                <td><?= htmlspecialchars($row['gpu']) ?></td>
                <td><?= empty($row['anofabricacao']) || $row['anofabricacao'] == '0' ? 'Dados não encontrados' : htmlspecialchars($row['anofabricacao']) ?></td>
                <td><?= htmlspecialchars($row['tipo']) ?></td>
                <td><?= htmlspecialchars($row['localizacao']) ?></td>
            </tr>
            <?php 
                endif;
            endwhile;
            ?>
        </tbody>
    </table>
</div>
<!-- Tabela Workstation/Servidor -->
<div class="table-responsive-custom" id="tabelaServidor" style="display:none">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Código</th>
                <th>Processador</th>
                <th>Memória</th>
                <th>Armazenamento</th>
                <th>GPU</th>
                <th>Ano Fabricação</th>
                <th>Tipo</th>
                <th>Localização</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $result->data_seek(0);
            while ($row = $result->fetch_assoc()):
                if (in_array(strtoupper($row['tipo']), ['SERVIDOR'])):
                    $classe = strtoupper($row['tipo']) === 'SERVIDOR' ? 'info' : 'success';
            ?>
            <tr class="<?= $classe ?>">
                <td><?= htmlspecialchars($row['codigo']) ?></td>
                <td><?= htmlspecialchars($row['processador']) ?></td>
                <td><?= htmlspecialchars($row['memoria']) ?></td>
                <td><?= htmlspecialchars($row['armazenamento']) ?></td>
                <td><?= htmlspecialchars($row['gpu']) ?></td>
                <td><?= empty($row['anofabricacao']) || $row['anofabricacao'] == '0' ? 'Dados não encontrados' : htmlspecialchars($row['anofabricacao']) ?></td>
                <td><?= htmlspecialchars($row['tipo']) ?></td>
                <td><?= htmlspecialchars($row['localizacao']) ?></td>
            </tr>
            <?php 
                endif;
            endwhile;
            ?>
        </tbody>
    </table>
</div>
<!-- Modal -->
<div id="modalInfo" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Informações da Rede</h4>
      </div>
      <div class="modal-body">
        <p><strong>Nome da Rede:</strong> <span id="info-rede"></span></p>
        <p><strong>Senha:</strong> <span id="info-senha"></span></p>
        <p><strong>Usuário Adm:</strong> <span id="info-user"></span></p>
        <p><strong>Senha Adm:</strong> <span id="info-pass"></span></p>
        <p><strong>IP:</strong> <span id="info-ip"></span></p>
      </div>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
    function aplicarFiltro(tipo) {
        if (tipo.toUpperCase() === "TODOS") {
            $("#tabelaPrincipal").show();
            $("#tabelaWorkstation").show();
            $("#tabelaServidor").show();
            $(".linha-equipamento").show();
        } else if (tipo.toUpperCase() === "SERVIDOR") {
            $("#tabelaPrincipal").hide();
            $("#tabelaWorkstation").hide();
            $("#tabelaServidor").show();
        } else if (tipo.toUpperCase() === "WORKSTATION") {
            $("#tabelaPrincipal").hide();
            $("#tabelaServidor").hide();
            $("#tabelaWorkstation").show();
        } else {
            $("#tabelaPrincipal").show();
            $("#tabelaWorkstation").hide();
            $("#tabelaServidor").hide();
            $(".linha-equipamento").hide();
            $('.linha-equipamento[data-tipo="' + tipo.toUpperCase() + '"]').show();
        }
    }

    $(".filtro").click(function(){
        var tipo = $(this).data("filtro");
        aplicarFiltro(tipo);
    });

    $("#filtro-mobile").change(function(){
        var tipo = $(this).val();
        aplicarFiltro(tipo);
    });

    $(".linha-equipamento").click(function() {
        var rede = $(this).data("rede");
        var senha = $(this).data("senha");
        var user = $(this).data("user");
        var pass = $(this).data("pass");
        var ip = $(this).data("ip");

        $("#info-rede").text(rede || "N/A");
        $("#info-senha").text(senha || "N/A");
        $("#info-user").text(user || "N/A");
        $("#info-pass").text(pass || "N/A");
        $("#info-ip").text(ip || "N/A");

        $("#modalInfo").modal("show");
    });
});
</script>

</body>
</html>

<?php $conn->close(); ?>
