<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$page_title = "Gerenciar QR Code";

// Conexão com o banco
$db = new SQLite3("./api/rgvip_qrcode.db");
$table_name = "qrcode";

// Criação da tabela se não existir
$db->exec("CREATE TABLE IF NOT EXISTS $table_name (
    id INTEGER PRIMARY KEY,
    qrcode TEXT
)");

// Verifica se já existe um QR Code
$res = $db->query("SELECT COUNT(*) as count FROM $table_name");
$row = $res->fetchArray();
$numRows = $row["count"];

if ($numRows == 0) {
    $db->exec("INSERT INTO $table_name (id, qrcode) VALUES (1, 'https://wa.me/593980649398')");
}

// Atualiza QR Code se enviado via POST
if (isset($_POST["submit"])) {
    $newQrcode = trim($_POST["qrcode"]);
    $db->exec("UPDATE $table_name SET qrcode='" . SQLite3::escapeString($newQrcode) . "' WHERE id=1");
    $db->close();
    header("Location: qrcode.php?r=atualizado");
    exit;
}

// Obtém o QR Code atual
$res = $db->query("SELECT qrcode FROM $table_name WHERE id=1");
$row = $res->fetchArray();
$qrcode = $row["qrcode"] ?? '';

// Geração da URL do QR Code
$qrcodeUrl = "https://image-charts.com/chart?chs=500x500&cht=qr&chl=" . urlencode($qrcode);

include 'includes/header.php';
?>
 <div class="col-md-8 mx-auto">
            <div class="card-body">
                <div class="card bg-dark text-white">
                    <div class="card-header card-header-warning">
                        <center>
                <h4 class="card-title">QR Code Actual:</h4>
                <?php if (!empty($qrcode)) : ?>
                    <img class="preview-image" src="<?= $qrcodeUrl ?>" alt="QR Code" width="30%" height="auto">
                <?php endif; ?>

                <form method="POST" action="">
                    <div class="form-group mt-3">
                        <label for="qrcode">ingresa la (URL):</label>
                        <input type="text" name="qrcode" id="qrcode" class="form-control" value="<?= htmlspecialchars($qrcode) ?>" required>
                    </div>
                    <button type="submit" name="submit" class="btn btn-primary mt-3">Atualizar Url</button>
                </form>
            </center>
        </div>
    </div>
</div>

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