<?php
session_start();

if (!isset($_SESSION['access_granted'])) {
    $_SESSION['access_granted'] = false;
}

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$filename = './token/tokens.txt';

// Função para ler tokens do arquivo
function readTokens($filename) {
    $tokens = [];
    if (file_exists($filename)) {
        $lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            list($token, $status) = explode('|', $line);
            $tokens[$token] = $status;
        }
    }
    return $tokens;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['access_code'])) {
        $access_code = trim($_POST['access_code']);
        $tokens = readTokens($filename);

        if (isset($tokens[$access_code]) && $tokens[$access_code] === 'active') {
            $_SESSION['access_granted'] = true;
            echo 'success';
        } else {
            echo 'fail';
        }
        exit();
    }
}
include ('./includes/header_token.php');

// Your database connection setup here

if (isset($_POST['submit'])) {
    unset($_POST['submit']);
    $db->insert('playlist', $_POST);
    $db->close();
    echo "<script>
        alert('Lista salva com sucesso.Fecha e Abra seu aplicativo para atualizar.');
        window.location.href='". basename($_SERVER["SCRIPT_NAME"]) ."?status=1';
    </script>";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ativar Usuário</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .modal-content {
            border-radius: 15px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        .modal-header {
            background-color: #007bff;
            color: white;
            border-bottom: 2px solid #0056b3;
        }
        .modal-body {
            background-color: #e9ecef;
        }
        .btn-primary {
            background-color: #007bff;
            border: none;
        }
        .btn-primary:hover {
            background-color: #0056b3;
        }
        .form-control {
            border-radius: 10px;
            border: 1px solid #ced4da;
        }
        .container-fluid {
            margin-top: 30px;
        }
        .card {
            border-radius: 15px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        .card-header {
            background-color: #007bff;
            color: white;
            border-bottom: 2px solid #0056b3;
        }
        .btn-success {
            background-color: #28a745;
            border: none;
        }
        .btn-success:hover {
            background-color: #218838;
        }
        .modal-backdrop.show {
            opacity: 0.5;
        }
    </style>
</head>
<body>
<?php if (!$_SESSION['access_granted']): ?>
    <div class="modal" id="accessModal" tabindex="-1" role="dialog" aria-labelledby="accessModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="accessModalLabel">Entre com seu Token</h5>
                </div>
                <div class="modal-body">
                    <form id="accessForm" method="post">
                        <div class="form-group">
                            <label for="access_code">Código de Acesso:</label>
                            <input type="password" class="form-control" id="access_code" name="access_code" required>
                        </div>
                        <button type="submit" class="btn btn-primary">ENTRAR</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script>
    $(document).ready(function(){
        $('#accessModal').modal({backdrop: 'static', keyboard: false});
        $('#accessModal').modal('show');

        $('#accessForm').on('submit', function(e){
            e.preventDefault();
            var access_code = $('#access_code').val();
            $.ajax({
                type: "POST",
                url: "",
                data: {access_code: access_code},
                success: function(response){
                    if(response === 'success'){
                        location.reload();
                    } else {
                        alert('Invalid Access Code');
                    }
                }
            });
        });
    });
    </script>
<?php endif; ?>

<div class="container-fluid">
    <div class="col-md-8 mx-auto">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="icon icon-bullhorn"></i> Adicionar Usuário</h2>
                </center>
            </div>
            <div class="card-body">
                <div class="col-12">
                    <h3>Adicionar Usuário</h3>
                </div>
                <form method="post">
                    <div class="form-group">
                        <label class="form-label" for="title">DNS</label>
                        <select class="form-control" name="dns_id">
                            <option selected="selected">Selecione o Servidor</option>
                            <?php
                            $dnss = $db->select('dns', '*', '', '');
                            foreach($dnss as $dns) { ?>
                                <option value="<?= $dns['id'] ?>"><?= $dns['title'] ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="dns">Endereço MAC (somente numeros)</label>
                        <input class="form-control" id="mac" name="mac_address" placeholder="MAC Address" type="text"/>
                    </div>
                    <script>
                        document.getElementById("mac").addEventListener('keyup', function() {
                            this.value = 
                                (this.value.toUpperCase()
                                .replace(/[^\d|A-Z]/g, '')
                                .match(/.{1,2}/g) || [])
                                .join(":");
                        });
                    </script>
                    <div class="form-group">
                        <label class="form-label" for="title">Usuário</label>
                        <input class="form-control" id="description" name="username" placeholder="Username" type="text"/>
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="dns">Senha</label>
                        <input class="form-control" id="description" name="password" placeholder="Password" type="text"/>
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="dns">Controle Parental</label>
                        <input class="form-control" id="description" name="pin" placeholder="Parental Pin" type="text" value="0000"/>
                    </div>
                    <div class="form-group">
                        <center>
                            <button class="btn btn-info" name="submit" type="submit">
                                <i class="icon icon-check"></i> ENVIAR
                            </button>
                        </center>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include ('./includes/footer.php'); ?>

</body>
</html>
