<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$db = new SQLite3('./a/.eggziedb.db');
$db->exec('CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY NOT NULL, mac_address VARCHAR(100), username VARCHAR(100), password VARCHAR(100), expire_date VARCHAR(100), url VARCHAR(100), title VARCHAR(100), created_at VARCHAR(100))');

$success = false; // Variável para controlar a exibição do modal

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $we = strtotime($_POST['expire_date']);
    $ne = empty($_POST['expire_date']) ? '9000-12-30' : date('Y-m-d', $we);
    $start = date('Y-m-d');
    $end = date('h:m:s');
    $full = $start . 'T' . $end . '.000000Z';

    $stmt = $db->prepare('INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at) VALUES(:mac_address, :username, :password, :expire_date, :url, :title, :created_at)');
    
    $stmt->bindValue(':mac_address', strtoupper($_POST['mac_address']), SQLITE3_TEXT);
    $stmt->bindValue(':username', $_POST['username'], SQLITE3_TEXT);
    $stmt->bindValue(':password', $_POST['password'], SQLITE3_TEXT);
    $stmt->bindValue(':expire_date', $ne, SQLITE3_TEXT);
    $stmt->bindValue(':url', $_POST['dns'], SQLITE3_TEXT);
    $stmt->bindValue(':title', $_POST['title'], SQLITE3_TEXT);
    $stmt->bindValue(':created_at', $full, SQLITE3_TEXT);

    if ($stmt->execute()) {
        $success = true; // Define que o cadastro foi realizado com sucesso
    }

    $db->close();

    // Redirecionar após o cadastro bem-sucedido para evitar reenvio do formulário
    if ($success) {
        header("Location: " . $_SERVER['PHP_SELF'] . "?success=1");
        exit; // Terminando o script após o redirecionamento
    }
}

$playlistNames = [
    'Ultimate Entertainment',
    'Global TV Hub',
    'Prime Streaming Zone',
    'All-in-One IPTV Lounge',
    'HD Channel Showcase',
];

$randomPlaylistName = $playlistNames[array_rand($playlistNames)];

// Verifica se a URL contém o parâmetro 'success'
$showModal = isset($_GET['success']) && $_GET['success'] == 1;
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cadastro de Cliente</title>
    <link rel="icon" type="image/png" href="img/logo.png">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        body {
            background-color: #000;
            color: #fff;
            font-family: Arial, sans-serif;
        }
        .container {
            margin-top: 50px;
            border-radius: 15px;
            box-shadow: 0 4px 8px rgba(255, 255, 255, 0.2);
            background-color: #1a1a1a;
            padding: 30px;
        }
        /* Consulta de mídia para dispositivos móveis */
        @media (max-width: 768px) {
            .container {
                width: 90%; /* Ajuste a largura conforme necessário */
                padding: 20px; /* Reduza o padding se necessário */
            }
        }
        .btn {
            border-radius: 30px;
        }
        .logo {
            text-align: center;
            margin-bottom: 30px;
        }
        .logo img {
            width: 150px; /* Ajuste o tamanho conforme necessário */
        }
        .form-control {
            background-color: #333;
            border: 1px solid #555;
            color: #fff;
        }
        .form-control:focus {
            background-color: #444;
            color: #fff;
            border-color: #007bff;
            box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
        }
        .form-group label {
            color: #ccc;
        }
        .modal-content {
            background-color: #1a1a1a; /* Fundo do modal */
            color: #fff; /* Cor do texto do modal */
        }
        .modal-header {
            border-bottom: 1px solid #555; /* Borda inferior do cabeçalho */
        }
    </style>
</head>
<body>

<div class="container">
    <div class="logo">
        <img src="img/logo.png" alt="Logotipo">
    </div>
    <h1 class="h3 mb-4 text-center">Cadastre-se:</h1>

    <form method="post">
        <div class="form-group">
            <label for="mac_address"><strong>Endereço MAC</strong></label>
            <input type="text" class="form-control" name="mac_address" id="mac_address" placeholder="Digite o Endereço MAC" required />
        </div>

        <div class="form-group" style="display: none;">
            <input type="text" class="form-control" name="title" id="title" value="<?php echo $randomPlaylistName; ?>" />
        </div>

        <div class="form-group">
            <label for="dns"><strong>DNS</strong></label>
            <input type="text" class="form-control" name="dns" id="dns" placeholder="Digite o DNS" required />
        </div>

        <div class="form-group">
            <label for="username"><strong>Usuário</strong></label>
            <input type="text" class="form-control" name="username" id="username" placeholder="Usuário" required />
        </div>

        <div class="form-group">
            <label for="password"><strong>Senha</strong></label>
            <input type="text" class="form-control" name="password" id="password" placeholder="Senha" required />
        </div>

        <div class="form-group" style="display: none;">
            <input type="text" class="form-control" name="expire_date" id="expire_date" placeholder="Data de Expiração (ANO-MES-DIA)" />
        </div>

        <button type="submit" name="submit" class="btn btn-success btn-block">
            <span class="text">Cadastrar</span>
        </button>
    </form>
</div>

<!-- Modal de Sucesso -->
<div class="modal fade" id="successModal" tabindex="-1" role="dialog" aria-labelledby="successModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content" style="border-radius: 15px; background-color: #2c2c2c; border: 1px solid #007bff;">
            <div class="modal-header" style="border-bottom: 1px solid #555;">
                <h5 class="modal-title" id="successModalLabel">Cadastro Realizado! 😉👍</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: #fff;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" style="text-align: center;">
                <p style="margin: 0; color: #ccc;">
                    <strong>INSTRUÇÕES:</strong> Feche seu aplicativo e abra novamente para visualizar o conteúdo!
                </p>
            </div>
            <div class="modal-footer" style="justify-content: center;">
                <button type="button" class="btn btn-secondary" data-dismiss="modal" style="border-radius: 10px;">Fechar</button>
            </div>
        </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.0.7/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
document.getElementById('username').addEventListener('input', function() {
    var username = document.getElementById('username').value;
    document.getElementById('title').value = username;
});

// Exibir modal de sucesso após o cadastro, se o parâmetro 'success' estiver presente na URL
<?php if ($showModal): ?>
    $(document).ready(function() {
        $('#successModal').modal('show');
    });
<?php endif; ?>
</script>

</body>
</html>
