<?php 

//db call
$db = new SQLite3("./api/db/studiolivecode_qrcode.db");

//table name
$table_name = "qrcode";

//current file var
$base_file = basename($_SERVER["SCRIPT_NAME"]);

//create if not
$db->exec("CREATE TABLE IF NOT EXISTS " . $table_name . "(id INTEGER PRIMARY KEY, qrcode TEXT)");

$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/554197211993')");   
}

$res = $db->query("SELECT qrcode FROM " . $table_name . " WHERE id='1'");
$row = $res->fetchArray();
$qrcode = $row["qrcode"];

if (isset($_POST["submit"])) {
    // Atualize o valor do QR Code no banco de dados
    $newQrcode = $_POST["qrcode"];
    $db->exec("UPDATE qrcode SET qrcode='" . $newQrcode . "' WHERE id='1'");

    $db->close();
    header("Location: qrcode.php?r=atualizado");
}

?>
<?php include './includes/header.php';?>
<div class="card radius-10">

<div class="card-body">
                    <center><h4 class="card-title">QR Code Atual:</h4>
<?php
$qrcodeUrl = "https://image-charts.com/chart?chs=500x500&cht=qr&chl=" . $qrcode;
if (!empty($qrcode)) {
    ?>
    <img class="preview-image" src="<?= $qrcodeUrl ?>" alt="Uploaded Image" width="50%" height="auto">
    <?php
} else {
    ?>
    <img class="preview-image" src="assets/images/noqr.png" alt="No QR Code Available" width="50%" height="auto">
    <?php
}
?>
</center>
                    <form class="forms-sample" method="post" enctype="multipart/form-data">
                      <div class="form-group mb-4"> 
    <br>
    <input type="text" class="form-control" name="qrcode" id="qrcode" value="<?= $row['qrcode'] ?>">
</div>
                      <button type="submit" name="submit" class="btn btn-primary mr-2"><i class='bx bx-check mr-1'></i>Enviar</button>
                    </form>
                  </div>
          </div>
</div>

<?php 
 if (isset($_GET["r"])) {
          $result = $_GET["r"];
switch ($result) {
            case "atualizado":
            echo "<script>
            const Toast = Swal.mixin({
  toast: true,
  position: 'bottom',
  showConfirmButton: false,
  timer: 2000,
})
Toast.fire({
  icon: 'success',
  title: 'QRCODE Atualizado com Sucesso!'
})</script>";
                break;
              }
            }
            ?>
				
<?php include './includes/footer.php';?>