<?php
session_start();
if(!isset($_SESSION['rev_logado'])){ header("Location: index_rev.php"); exit(); }
include('../api/conexao_rev.php');

$id_rev = $_SESSION['rev_logado'];

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

$dir_db = '../api/db/'; 
$dir_img = '../api/img_backgrounds/'; 

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

$jsonFile = $dir_db . "bg_rev_" . $id_rev . ".json";

$filenamex = "";
$methord = "Nenhum";
$imagePreview = "https://via.placeholder.com/1080x1920?text=Sem+Fundo";

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;
    }
}

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

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

    if (isset($_POST['url-submit'])) {
        $imageUrl = $_POST['image-url'];
        if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
            file_put_contents($jsonFile, json_encode([["ImageName" => $imageUrl, 'Upload_type' => 'by_url']], JSON_UNESCAPED_SLASHES));
            header("Location: bg_rev.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>Gerenciar Background</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; overflow-x: hidden; }
        .container-fluid { padding: 30px 15px !important; }
        .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 40px 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; }
        
        /* AJUSTE DA VIEW PARA NÃO CORTAR */
        .preview-box { background: #0f172a; border: 2px dashed #1e293b; border-radius: 16px; padding: 15px; text-align: center; margin-bottom: 25px; position: relative; min-height: 200px; display: flex; align-items: center; justify-content: center; }
        .preview-box img { max-width: 100%; max-height: 400px; object-fit: contain; border-radius: 8px; box-shadow: 0 5px 15px rgba(0,0,0,0.5); }
        
        .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; text-transform: uppercase; }
        .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; display: block; }
        .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; box-shadow: 0 4px 15px rgba(59, 130, 246, 0.2); 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>Background App</h1><p>ID da Sessão: #<?= $id_rev ?></p></div>
        <label>Visualização do Fundo</label>
        <div class="preview-box"><span class="method-badge"><?= $methord ?></span><img src="<?= $imagePreview ?>?v=<?= time() ?>" alt="Background Preview"></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>Escolha a Imagem (Recomendado: 1080x1920)</label>
            <input class="form-input" type="file" name="image" accept="image/*" required>
            <button type="submit" name="upload" class="btn-premium-save">Salvar Background</button>
        </form>
        <form method="post" id="form-url" style="display: none;">
            <input type="hidden" name="token" value="<?= $_SESSION['admin_token'] ?>">
            <label>URL da Imagem</label>
            <input class="form-input" type="text" name="image-url" placeholder="https://..." required>
            <button type="submit" name="url-submit" class="btn-premium-save">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:'Fundo Atualizado!',background:'#070e1b',color:'#fff'});}
</script>
</body>
</html>
