<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'session_check.php';
require_once __DIR__ . '/includes/functions.php';

$page_title = 'QR Code • TV VIP';
$rows = $db->select('qr_code', '*', 'id = :id', '', [':id' => 1]);
if (empty($rows)) {
    $db->insert('qr_code', ['id' => 1, 'name' => 'SUPORTE QR-CODE', 'url' => 'https://wa.me/5571983834846']);
    $rows = $db->select('qr_code', '*', 'id = :id', '', [':id' => 1]);
}
$current = $rows[0];
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newUrl = trim((string)($_POST['qrcode'] ?? ''));
    $newName = trim((string)($_POST['name'] ?? 'SUPORTE QR-CODE'));
    if (!filter_var($newUrl, FILTER_VALIDATE_URL)) {
        $error = 'Informe uma URL válida para o QR Code.';
    } else {
        $db->update('qr_code', ['name' => $newName, 'url' => $newUrl], 'id = :id', [':id' => 1]);
        $current = ['id' => 1, 'name' => $newName, 'url' => $newUrl];
        $message = 'QR Code atualizado e sincronizado com o aplicativo.';
    }
}

$name = htmlspecialchars((string)$current['name'], ENT_QUOTES, 'UTF-8');
$url = htmlspecialchars((string)$current['url'], ENT_QUOTES, 'UTF-8');
$page_content = '
<div class="row justify-content-center"><div class="col-xl-8">
<div class="card"><div class="card-header"><h3 class="card-title">🔳 QR Code integrado ao aplicativo</h3></div>
<div class="card-body">'
. ($message ? '<div class="alert alert-success">' . htmlspecialchars($message, ENT_QUOTES, 'UTF-8') . '</div>' : '')
. ($error ? '<div class="alert alert-danger">' . htmlspecialchars($error, ENT_QUOTES, 'UTF-8') . '</div>' : '')
. '<div class="row align-items-center g-8">
<div class="col-md-5 text-center"><div style="display:inline-block;padding:14px;background:#fff;border-radius:18px"><img src="api/qr_png.php?v=' . time() . '" alt="QR Code" style="width:220px;height:220px;object-fit:contain"></div></div>
<div class="col-md-7"><form method="post">
<div class="mb-5"><label class="form-label">Nome interno</label><input class="form-control" name="name" value="' . $name . '"></div>
<div class="mb-5"><label class="form-label">Link de destino</label><input type="url" class="form-control" name="qrcode" value="' . $url . '" required><div class="form-text">O app abre a página /api/qr.php, que exibe este QR Code.</div></div>
<button class="btn btn-primary" type="submit">Salvar e sincronizar</button>
</form></div></div></div></div></div></div>';

include 'includes/layout.php';
