<?php
session_start();

// Verifica se o usuário está logado
if (!isset($_SESSION['login']) || empty($_SESSION['login'])) {
    header("Location: login.php");
    exit;
}

$userlogin = $_SESSION['login'];
$username = $_SESSION['nome_usuario'];

// Conexão com o banco
$host = 'localhost';
$db = 'kaltekgo_avila';
$user = 'kaltekgo_admin';
$pass = 'kaltek@2024';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("SELECT * FROM dashboard WHERE user = :user");
    $stmt->execute([':user' => $userlogin]);
    $botoes = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    die("Erro na conexão: " . $e->getMessage());
}

if (count($botoes) === 0) {
    echo "<script>alert('Usuário não autorizado'); window.location.href = 'login.php';</script>";
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>DASHBOARD</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        .vertical-center {
            min-height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .col-custom {
            padding: 10px 5px;
            width: auto;
        }
        .btn-custom {
            width: 100%;
        }
        .header-bar {
            width: 100%;
            padding: 10px;
            background: #f5f5f5;
            border-bottom: 1px solid #ddd;
            position: fixed;
            top: 0;
            right: 0;
            left: 0;
            z-index: 1000;
        }
        .header-bar .header-content {
            display: flex;
            justify-content: flex-end;
            align-items: center;
        }
        .header-bar .welcome {
            font-size: 12px;
            font-weight: bold;
            margin-right: 10px;
        }
        .header-bar .btn {
            margin-left: 5px;
        }
        .container {
            padding-top: 10px;
            
        }
    </style>
</head>
<body>
<div class="header-bar">
    <div class="container header-content">
        <span class="welcome text-uppercase">Seja bem-vindo, <?php echo htmlspecialchars($username); ?></span>
        <a href="dashboard.php" class="btn btn-primary btn-sm">Principal</a>
        <a href="alterarsenha.php" class="btn btn-warning btn-sm">Alterar Senha</a>
        <a href="logout.php" class="btn btn-danger btn-sm">Sair</a>
        <a class="btn btn-danger btn-sm">Tempo restante da sessão: <span id="session-timer"></span></a>
    </div>
</div>

<div class="container vertical-center">
    <div class="w-100">
        <?php
        $total = count($botoes);
        for ($i = 0; $i < $total; $i += 3) {
            echo '<div class="row text-center">';
            $limite = min(3, $total - $i);
            for ($j = 0; $j < $limite; $j++) {
                $botao = $botoes[$i + $j];
                echo '<div class="col-sm-' . (12 / $limite) . ' col-custom">';
                echo '<a href="' . htmlspecialchars($botao['link-buttom']) . '" class="btn btn-success btn-custom text-uppercase btn-sm">'
                    . htmlspecialchars($botao['text-buttom']) . '</a>';
                echo '</div>';
            }
            echo '</div>';
        }
        ?>
    </div>
</div>


<script>
    const loginTime = <?= $_SESSION['login_time'] ?? time(); ?>;
    const sessionDuration = <?= $_SESSION['session_duration'] ?? 3600; ?>;
</script>
<script>
    function formatTime(seconds) {
        const h = Math.floor(seconds / 3600).toString().padStart(2, '0');
        const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
        const s = (seconds % 60).toString().padStart(2, '0');
        return `${h}:${m}:${s}`;
    }

    const display = document.getElementById('session-timer');
    const endTime = loginTime + sessionDuration;

    function updateTimer() {
        const now = Math.floor(Date.now() / 1000);
        const remaining = endTime - now;

        if (remaining <= 0) {
            display.textContent = 'Sessão expirada';
            clearInterval(timer);
            window.location.href = 'logout.php';
        } else {
            display.textContent = formatTime(remaining);
        }
    }

    updateTimer();
    const timer = setInterval(updateTimer, 1000);
</script>
</body>
</html>
