<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = "Enviar QR Code";

/* ===============================
   CONEXÃO COM BANCO SQLITE
=============================== */
$db         = new SQLite3("./api/maxrebrandscode_qrcode.db");
$table_name = "qrcode";

/* ===============================
   CRIA TABELA SE NÃO EXISTIR
=============================== */
$db->exec("
    CREATE TABLE IF NOT EXISTS $table_name (
        id      INTEGER PRIMARY KEY,
        qrcode  TEXT
    )
");

/* ===============================
   GARANTE REGISTRO PADRÃO
=============================== */
$res = $db->query("SELECT COUNT(*) as count FROM $table_name");
$row = $res->fetchArray(SQLITE3_ASSOC);
if ($row['count'] == 0) {
    $defaultQr = 'https://wa.me/5571983834846';
    $db->exec("INSERT INTO $table_name (id, qrcode) VALUES (1, '$defaultQr')");
}

/* ===============================
   FUNÇÃO PARA ATUALIZAR JSON
=============================== */
function atualizarJsonQr($valor) {
    $jsonPath = __DIR__ . '/api/qrcode.json';
    $data = ["qrcode" => $valor];
    file_put_contents($jsonPath, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
}

/* ===============================
   ATUALIZA QR VIA POST
=============================== */
$success_message = '';
$error_message   = '';

if (isset($_POST['submit'])) {
    $newQrcode = trim($_POST['qrcode']);
    if (!filter_var($newQrcode, FILTER_VALIDATE_URL)) {
        $error_message = "URL inválida. Por favor insira uma URL válida.";
    } else {
        $db->exec("UPDATE $table_name SET qrcode='" . SQLite3::escapeString($newQrcode) . "' WHERE id=1");
        atualizarJsonQr($newQrcode);
        $db->close();
        header("Location: qrcode.php?r=atualizado");
        exit;
    }
}

if (isset($_GET['r']) && $_GET['r'] === 'atualizado') {
    $success_message = "QR Code atualizado com sucesso!";
}

/* ===============================
   OBTÉM QR ATUAL
=============================== */
$res    = $db->query("SELECT qrcode FROM $table_name WHERE id=1");
$row    = $res->fetchArray(SQLITE3_ASSOC);
$qrcode = $row['qrcode'];

/* ===============================
   URL DO QR CODE (via API Google Charts)
=============================== */
$qrApiUrl = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" . urlencode($qrcode) . "&bgcolor=ffffff&color=000000&margin=10";

/* ===============================
   CONTEÚDO DA PÁGINA
=============================== */
$page_content = '
<style>
/* ═══════════════════════════
   PAGE HEADER
═══════════════════════════ */
.mac-page-header {
    background: linear-gradient(135deg, #0d1117 0%, #1a2744 50%, #0d1117 100%);
    border: 1px solid rgba(99,179,237,0.12);
    border-radius: 16px;
    padding: 28px 32px;
    margin-bottom: 24px;
    margin-top: 24px;
    position: relative;
    overflow: hidden;
}
.mac-page-header::before {
    content: "";
    position: absolute;
    top: -60px; right: -60px;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(52,211,153,0.08) 0%, transparent 70%);
    pointer-events: none;
}
.mac-page-header::after {
    content: "";
    position: absolute;
    bottom: -40px; left: 30%;
    width: 150px; height: 150px;
    background: radial-gradient(circle, rgba(99,179,237,0.07) 0%, transparent 70%);
    pointer-events: none;
}
.mac-page-header h1 {
    color: #e2e8f0;
    font-size: 22px;
    font-weight: 700;
    margin: 0 0 6px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.mac-page-header h1 .icon-wrap {
    width: 40px; height: 40px;
    background: rgba(52,211,153,0.10);
    border: 1px solid rgba(52,211,153,0.22);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #34d399;
    flex-shrink: 0;
}
.mac-page-header p {
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    margin: 0;
}

/* ═══════════════════════════
   PANELS
═══════════════════════════ */
.logo-panel {
    background: #161b22;
    border: 1px solid rgba(99,179,237,0.08);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0,0,0,0.3);
    height: 100%;
}
.logo-panel-header {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
    padding: 18px 24px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.ph-icon {
    width: 36px; height: 36px;
    border-radius: 9px;
    display: flex; align-items: center; justify-content: center;
    font-size: 16px;
    flex-shrink: 0;
}
.ph-icon-qr     { background: rgba(52,211,153,0.12);  border: 1px solid rgba(52,211,153,0.2);  color: #34d399; }
.ph-icon-edit   { background: rgba(99,179,237,0.12);  border: 1px solid rgba(99,179,237,0.2);  color: #63b3ed; }
.logo-panel-header-text h5 {
    color: #e2e8f0;
    font-size: 14px;
    font-weight: 700;
    margin: 0 0 2px;
}
.logo-panel-header-text p {
    color: rgba(148,163,184,0.5);
    font-size: 12px;
    margin: 0;
}
.logo-panel-body { padding: 24px; }

/* QR preview box */
.qr-preview-box {
    background: rgba(255,255,255,0.02);
    border: 1px solid rgba(255,255,255,0.06);
    border-radius: 14px;
    padding: 28px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;
}
.qr-img-wrap {
    background: #fff;
    border-radius: 12px;
    padding: 10px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.4);
}
.qr-img-wrap img {
    display: block;
    width: 170px; height: 170px;
    border-radius: 4px;
}
.qr-url-display {
    background: rgba(255,255,255,0.03);
    border: 1px solid rgba(255,255,255,0.07);
    border-radius: 8px;
    padding: 9px 14px;
    width: 100%;
    display: flex;
    align-items: center;
    gap: 10px;
}
.qr-url-display i { color: rgba(52,211,153,0.6); font-size: 13px; flex-shrink: 0; }
.qr-url-display span {
    font-family: monospace;
    font-size: 12px;
    color: #34d399;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
}
.btn-copy-url {
    background: rgba(52,211,153,0.08);
    border: 1px solid rgba(52,211,153,0.15);
    border-radius: 7px;
    color: #34d399;
    font-size: 12px;
    width: 28px; height: 28px;
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
    cursor: pointer;
    transition: all 0.2s ease;
}
.btn-copy-url:hover { background: rgba(52,211,153,0.18); transform: scale(1.1); }

/* Form */
.qr-form-group { margin-bottom: 20px; }
.qr-form-group label {
    color: rgba(148,163,184,0.8);
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    display: block;
    margin-bottom: 8px;
}
.qr-form-group input {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    border-radius: 10px !important;
    color: #e2e8f0 !important;
    font-size: 13px !important;
    padding: 11px 14px !important;
    width: 100%;
    transition: all 0.2s ease !important;
}
.qr-form-group input::placeholder { color: rgba(148,163,184,0.3) !important; }
.qr-form-group input:focus {
    border-color: rgba(52,211,153,0.4) !important;
    box-shadow: 0 0 0 3px rgba(52,211,153,0.08) !important;
    background: rgba(52,211,153,0.03) !important;
    outline: none !important;
}
.qr-form-group .form-hint {
    color: rgba(148,163,184,0.35);
    font-size: 11px;
    margin-top: 6px;
}

.btn-save-qr {
    background: linear-gradient(135deg, #059669, #34d399) !important;
    border: none !important;
    border-radius: 10px !important;
    color: #fff !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 11px 20px !important;
    width: 100%;
    display: flex; align-items: center; justify-content: center; gap: 8px;
    transition: all 0.2s ease !important;
    box-shadow: 0 4px 12px rgba(52,211,153,0.25) !important;
    cursor: pointer;
}
.btn-save-qr:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(52,211,153,0.35) !important;
}

/* Tips */
.tip-list { list-style: none; padding: 0; margin: 20px 0 0; }
.tip-list li {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 8px 0;
    border-bottom: 1px solid rgba(255,255,255,0.04);
    font-size: 12px;
    color: rgba(148,163,184,0.6);
}
.tip-list li:last-child { border-bottom: none; }
.tip-list li i { font-size: 12px; margin-top: 2px; flex-shrink: 0; }

/* Alerts */
.alert-mac {
    border-radius: 10px;
    padding: 12px 16px;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
}
.alert-mac-success { background: rgba(52,211,153,0.08);  border: 1px solid rgba(52,211,153,0.2);  color: #34d399; }
.alert-mac-error   { background: rgba(248,113,113,0.08); border: 1px solid rgba(248,113,113,0.2); color: #f87171; }
</style>

<!-- PAGE HEADER -->
<div class="mac-page-header d-flex align-items-center justify-content-between flex-wrap gap-3">
    <div>
        <h1>
            <span class="icon-wrap"><i class="fa-solid fa-qrcode"></i></span>
            Enviar QR Code
        </h1>
        <p>Gerencie o link associado ao QR Code exibido no aplicativo.</p>
    </div>
</div>

' . (!empty($success_message) ? '
<div class="alert-mac alert-mac-success">
    <i class="fa-solid fa-circle-check"></i> ' . $success_message . '
</div>' : '') . '

' . (!empty($error_message) ? '
<div class="alert-mac alert-mac-error">
    <i class="fa-solid fa-circle-xmark"></i> ' . $error_message . '
</div>' : '') . '

<div class="row g-4">

    <!-- PREVIEW DO QR -->
    <div class="col-lg-5">
        <div class="logo-panel">
            <div class="logo-panel-header">
                <div class="ph-icon ph-icon-qr"><i class="fa-solid fa-qrcode"></i></div>
                <div class="logo-panel-header-text">
                    <h5>QR Code Atual</h5>
                    <p>Visualização do código gerado</p>
                </div>
            </div>
            <div class="logo-panel-body">
                <div class="qr-preview-box">
                    <div class="qr-img-wrap">
                        <img id="qrPreviewImg" src="' . $qrApiUrl . '" alt="QR Code">
                    </div>
                    <div class="qr-url-display">
                        <i class="fa-solid fa-link"></i>
                        <span id="qrUrlText">' . htmlspecialchars($qrcode) . '</span>
                        <button class="btn-copy-url" onclick="copyUrl()" title="Copiar URL">
                            <i class="fa-regular fa-copy"></i>
                        </button>
                    </div>
                </div>
                <ul class="tip-list">
                    <li><i class="fa-solid fa-circle-info" style="color:#63b3ed;"></i> O QR Code é gerado automaticamente a partir da URL</li>
                    <li><i class="fa-solid fa-mobile-screen" style="color:#34d399;"></i> Funciona com qualquer link: WhatsApp, site, etc.</li>
                    <li><i class="fa-solid fa-bolt" style="color:#fbbf24;"></i> Alterações aplicadas instantaneamente após salvar</li>
                </ul>
            </div>
        </div>
    </div>

    <!-- FORMULÁRIO -->
    <div class="col-lg-7">
        <div class="logo-panel">
            <div class="logo-panel-header">
                <div class="ph-icon ph-icon-edit"><i class="fa-solid fa-pen-to-square"></i></div>
                <div class="logo-panel-header-text">
                    <h5>Atualizar Link do QR Code</h5>
                    <p>Insira a nova URL para gerar o código</p>
                </div>
            </div>
            <div class="logo-panel-body">
                <form method="POST" action="" id="qrForm">
                    <div class="qr-form-group">
                        <label>URL do QR Code</label>
                        <input
                            type="text"
                            name="qrcode"
                            id="qrcodeInput"
                            placeholder="https://wa.me/5500000000000"
                            value="' . htmlspecialchars($qrcode) . '"
                            required
                        >
                        <div class="form-hint">Insira uma URL válida (ex: link do WhatsApp, site ou outro serviço)</div>
                    </div>

                    <button type="submit" name="submit" class="btn-save-qr">
                        <i class="fa-solid fa-floppy-disk"></i> Salvar e Atualizar QR Code
                    </button>
                </form>

                <ul class="tip-list" style="margin-top:24px;">
                    <li><i class="fa-brands fa-whatsapp" style="color:#34d399;"></i> WhatsApp: <span style="color:#63b3ed;font-family:monospace;">https://wa.me/55XXXXXXXXXXX</span></li>
                    <li><i class="fa-solid fa-globe" style="color:#818cf8;"></i> Site: <span style="color:#63b3ed;font-family:monospace;">https://seusite.com</span></li>
                    <li><i class="fa-solid fa-shield-halved" style="color:#fbbf24;"></i> Somente URLs válidas são aceitas pelo sistema</li>
                </ul>
            </div>
        </div>
    </div>

</div>
';

include 'includes/layout.php';
?>

<script>
// Atualizar preview do QR em tempo real ao digitar
document.getElementById("qrcodeInput").addEventListener("input", function () {
    const val = this.value.trim();
    if (!val) return;
    const apiUrl = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data="
        + encodeURIComponent(val) + "&bgcolor=ffffff&color=000000&margin=10";
    document.getElementById("qrPreviewImg").src = apiUrl;
    document.getElementById("qrUrlText").textContent = val;
});

// Copiar URL atual
function copyUrl() {
    const text = document.getElementById("qrUrlText").textContent;
    navigator.clipboard.writeText(text).then(() => {
        Swal.fire({ icon: "success", title: "Copiado!", text: "URL copiada para a área de transferência", timer: 1500, showConfirmButton: false });
    });
}
</script>