<?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
$id_rev = $_SESSION['rev_logado'];

// BUSCA O NÍVEL PARA SABER SE É MASTER (2) OU COMUM (1)
$sql = $conn_rev->query("SELECT nivel_rev FROM dados_rev WHERE id_rev = '$id_rev'");
$dados = $sql->fetch_assoc();
$nivel = $dados['nivel_rev'];

// Define o prefixo do arquivo baseado no nível para clareza total
$tipo_rev = ($nivel == 2) ? "master" : "comum";

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

// Caminhos isolados do seu Admin
$dir_db = '../api/db/'; 
$dir_img = '../api/img_revendas/'; // Pasta exclusiva para fotos das revendas

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

// Nome do arquivo JSON seguindo o padrão que o arquivo de entrega espera
$jsonFile = $dir_db . "panaci_rev_sub_logo_" . $tipo_rev . "_" . $id_rev . ".json";

// Lógica de Leitura para o Preview no Painel
$imagePreview = "https://via.placeholder.com/300x100?text=Sem+Logo";
$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";
        // Ajusta o caminho para o preview aparecer no painel (rev/ -> api/)
        $imagePreview = "../" . $filenamex; 
    } else {
        $methord = "URL Externa";
        $imagePreview = $filenamex;
    }
}

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

    // Opção 1: Upload de Arquivo
    if (isset($_POST['upload'])) {
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $newName = "logo_" . $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_logo_gerenciar.php?status=ok");
                exit();
            }
        }
    }

    // Opção 2: 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_logo_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>Branding | Logo Revenda</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: 600px; 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-box { background: radial-gradient(circle, #0f172a 0%, #020617 100%); border: 2px dashed #1e293b; border-radius: 16px; padding: 30px 10px; text-align: center; margin-bottom: 25px; position: relative; }
        .preview-box img { max-width: 80%; max-height: 120px; border-radius: 8px; filter: drop-shadow(0 0 10px rgba(59, 130, 246, 0.2)); }
        .method-badge { position: absolute; top: 10px; right: 10px; background: rgba(59, 130, 246, 0.1); color: #3b82f6; 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: 600px; 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>Branding & Logo</h1>
            <p><i class="fas fa-user-shield mr-1"></i> Nível: <?= $tipo_rev ?> | ID: #<?= $id_rev ?></p>
        </div>
        
        <label>Logo Atual no App</label>
        <div class="preview-box">
            <span class="method-badge"><?= $methord ?></span>
            <img src="<?= $imagePreview ?>" alt="Logo">
        </div>

        <div class="method-switch">
            <div class="method-btn active" id="btn-upload">UPLOAD ARQUIVO</div>
            <div class="method-btn" id="btn-url">LINK EXTERNO</div>
        </div>

        <form method="post" enctype="multipart/form-data" id="form-upload">
            <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
            <label>Selecione a Imagem</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-cloud-upload-alt"></i> Atualizar Logo</button>
        </form>

        <form method="post" id="form-url" style="display: none;">
            <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
            <label>Link Direto (HTTPS)</label>
            <input class="form-input" type="text" name="image-url" placeholder="https://site.com/imagem.png" required>
            <button type="submit" name="url-submit" class="btn-premium-save"><i class="fas fa-link"></i> Salvar 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: 'Logo atualizada para o App.', background: '#070e1b', color: '#fff', confirmButtonColor: '#3b82f6' });
    }
</script>
</body>
</html>
