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

include 'session_check.php';

$page_title = "Actualizar 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 = $_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"];

// Caminho para imagens estáticas, se necessário
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';

// Conteúdo da página
$page_content = '
<div class="container-fluid">
    <div class="card radius-10">
        <div class="card-body">
            <center>
                <h4 class="card-title">QR Code Actual:</h4>';

$qrcodeUrl = "https://image-charts.com/chart?chs=500x500&cht=qr&chl=" . urlencode($qrcode);
if (!empty($qrcode)) {
    $page_content .= '<img class="preview-image" src="' . $qrcodeUrl . '" alt="QR Code" width="30%" height="auto">';
}

$page_content .= '
                <form method="POST" action="">
                    <div class="form-group mt-3">
                        <label for="qrcode">Nuevo Link:</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">Actualizar QR Code</button>
                </form>
            </center>
        </div>
    </div>
</div>';

include 'includes/layout.php';
