<?php
session_start();
// Proteção de Login
if(!isset($_SESSION['rev_logado'])){ header("Location: index_rev.php"); exit(); }

include('../api/conexao_rev.php');

// Identificação do Usuário e Nível
$id_rev = $_SESSION['rev_logado'];
$sql = $conn_rev->query("SELECT nivel_rev FROM dados_rev WHERE id_rev = '$id_rev'");
$dados = $sql->fetch_assoc();
$nivel = $dados['nivel_rev'];

$tipo_rev = ($nivel == 2) ? "master" : "comum";

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

// Caminhos Isolados
$dir_db = '../api/db/'; 
$dir_img = '../api/img_revendas/'; 

if (!is_dir($dir_db)) mkdir($dir_db, 0777, true);
if (!is_dir($dir_img)) mkdir($dir_img, 0777, true);

// Nome do JSON de QR Code
$jsonFile = $dir_db . "panaci_rev_sub_qr_" . $tipo_rev . "_" . $id_rev . ".json";

// Leitura para o Preview (Mais vertical para QR Code)
$imagePreview = "https://via.placeholder.com/400x600?text=Sem+QR+Code";
$methord = "Nenhum";

if (file_exists($jsonFile)) {
    $data = json_decode(file_get_contents($jsonFile), true);
    $filenamex = $data[0]['ImageName'] ?? '';
    $uploadmethord = $data[0]['Upload_type'] ?? '';
    
    if ($uploadmethord == "by_file") {
        $methord = "Arquivo Local";
        $imagePreview = "../" . $filenamex; 
    } else {
        $methord = "URL Externa";
        $imagePreview = $filenamex;
    }
}

// PROCESSAMENTO
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) { exit('Token Inválido'); }

    // Upload de Arquivo
    if (isset($_POST['upload'])) {
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $newName = "qr_" . $tipo_rev . "_" . $id_rev . "_" . time() . "." . $ext;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $dir_img . $newName)) {
                $savePath = "api/img_revendas/" . $newName;
                $jsonData = json_encode([["ImageName" => $savePath, 'Upload_type' => 'by_file']], JSON_UNESCAPED_SLASHES);
                file_put_contents($jsonFile, $jsonData);
                header("Location: panaci_rev_sub_qr_gerenciar.php?status=ok");
                exit();
            }
        }
    }

    // Link Externo
    if (isset($_POST['url-submit'])) {
        $imageUrl = $_POST['image-url'];
        if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
            $jsonData = json_encode([["ImageName" => $imageUrl, 'Upload_type' => 'by_url']], JSON_UNESCAPED_SLASHES);
            file_put_contents($jsonFile, $jsonData);
            header("Location: panaci_rev_sub_qr_gerenciar.php?status=ok");
            exit();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pagamentos | QR Code PIX</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        * { box-sizing: border-box; }
        html, body { background-color: #020617 !important; color: #e2e8f0 !important; font-family: 'Inter', sans-serif; margin: 0; padding: 0; }
        .container-fluid { padding: 30px 15px; }
        .btn-back-nav { display: inline-flex; align-items: center; gap: 8px; color: #64748b; text-decoration: none !important; font-size: 0.85rem; font-weight: 600; margin-bottom: 20px; }
        .premium-card { background: #070e1b !important; border: 1px solid #1e293b !important; border-radius: 20px; padding: 25px; box-shadow: 0 10px 25px rgba(0,0,0,0.3); max-width: 500px; margin: 0 auto; width: 100%; }
        .card-header-premium { margin-bottom: 25px; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 15px; }
        .card-header-premium h1 { font-size: 1.4rem; font-weight: 800; color: #fff; margin: 0; }
        .card-header-premium p { color: #3b82f6; font-size: 0.8rem; margin-top: 4px; font-weight: 600; text-transform: uppercase; }
        
        /* Preview focado em QR Code (Retangular Vertical) */
        .preview-box { background: #fff; border: 4px solid #1e293b; border-radius: 16px; overflow: hidden; margin-bottom: 25px; position: relative; min-height: 300px; display: flex; align-items: center; justify-content: center; padding: 10px; }
        .preview-box img { max-width: 100%; max-height: 400px; object-fit: contain; }
        .method-badge { position: absolute; top: 10px; right: 10px; background: rgba(59, 130, 246, 0.9); color: #fff; padding: 4px 10px; border-radius: 8px; font-size: 0.65rem; font-weight: 800; }

        .method-switch { display: grid; grid-template-columns: 1fr 1fr; background: #0f172a; border-radius: 12px; padding: 5px; margin-bottom: 25px; border: 1px solid #1e293b; }
        .method-btn { padding: 12px; text-align: center; border-radius: 8px; font-size: 0.8rem; font-weight: 700; color: #64748b; cursor: pointer; transition: 0.3s; }
        .method-btn.active { background: #3b82f6; color: #fff; }

        label { display: block; color: #3b82f6; font-size: 0.7rem; font-weight: 800; margin-bottom: 8px; text-transform: uppercase; }
        .form-input { width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; color: #fff !important; padding: 15px; border-radius: 12px; font-size: 0.95rem; margin-bottom: 20px; }
        .btn-premium-save { width: 100%; background: #3b82f6 !important; color: #fff !important; padding: 18px; border-radius: 14px; font-weight: 800; text-transform: uppercase; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 10px; transition: 0.3s; }
    </style>
</head>
<body>
<div class="container-fluid">
    <div style="max-width: 500px; margin: 0 auto;">
        <a href="dashboard_rev.php" class="btn-back-nav"><i class="fas fa-chevron-left"></i> Voltar</a>
    </div>
    <div class="premium-card">
        <div class="card-header-premium">
            <h1>QR-Code PIX</h1>
            <p><i class="fas fa-qrcode mr-1"></i> Recebimentos da Revenda (<?= $tipo_rev ?>)</p>
        </div>
        
        <label>Seu QR Code Atual</label>
        <div class="preview-box">
            <img src="<?= $imagePreview ?>" alt="QR Code Preview">
            <span class="method-badge"><?= $methord ?></span>
        </div>

        <div class="method-switch">
            <div class="method-btn active" id="btn-upload">UPLOAD IMAGEM</div>
            <div class="method-btn" id="btn-url">LINK DO PIX</div>
        </div>

        <form method="post" enctype="multipart/form-data" id="form-upload">
            <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
            <label>Selecione o Print do seu QR Code</label>
            <input class="form-input" type="file" name="image" accept="image/*" required>
            <button type="submit" name="upload" class="btn-premium-save"><i class="fas fa-qrcode"></i> Atualizar QR Code</button>
        </form>

        <form method="post" id="form-url" style="display: none;">
            <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
            <label>Link Direto da Imagem do QR Code</label>
            <input class="form-input" type="text" name="image-url" placeholder="https://..." required>
            <button type="submit" name="url-submit" class="btn-premium-save"><i class="fas fa-link"></i> Salvar via Link</button>
        </form>
    </div>
</div>
<script>
    const bU = document.getElementById('btn-upload'), bL = document.getElementById('btn-url'), fU = document.getElementById('form-upload'), fL = document.getElementById('form-url');
    bU.onclick = () => { bU.classList.add('active'); bL.classList.remove('active'); fU.style.display = 'block'; fL.style.display = 'none'; };
    bL.onclick = () => { bL.classList.add('active'); bU.classList.remove('active'); fU.style.display = 'none'; fL.style.display = 'block'; };
    if (new URLSearchParams(window.location.search).get('status') === 'ok') {
        Swal.fire({ icon: 'success', title: 'Sucesso!', text: 'QR Code atualizado para seus clientes.', background: '#070e1b', color: '#fff', confirmButtonColor: '#3b82f6' });
    }
</script>
</body>
</html>
