<?php
session_start();
if (!isset($_SESSION['id'])) {
    header("Location: login.php");
    exit();
}

include "includes/header.php";

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

// Caminho do arquivo JSON de configuração
$jsonFilex = './img/fundo/image_filenames.json';
$jsonDatax = file_get_contents($jsonFilex);
$imageDatax = json_decode($jsonDatax, true);
$filenamex = $imageDatax[0]['ImageName'];
$uploadmethord = $imageDatax[0]['Upload_type'];

if ($uploadmethord == "by_file") {
    $imageFilex = substr($filenamex, 1);
    $methord = "Arquivo Local";
} elseif ($uploadmethord == "by_url") {
    $imageFilex = $filenamex;
    $methord = "URL Externa";
} else {
    $imageFilex = "https://via.placeholder.com/1280x720?text=Sem+Background";
    $methord = "Nenhum";
}
?>

<style>
    /* RESET E SEGURANÇA DE LARGURA */
    * { box-sizing: border-box; }

    /* FUNDO TOTAL DARK */
    html, body, .wrapper, .main-panel, .content, .container-fluid { 
        background-color: #020617 !important; 
        color: #e2e8f0 !important;
        overflow-x: hidden;
    }

    /* OCULTAR NAVBAR ORIGINAL */
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }

    .container-fluid { padding: 15px !important; }

    /* BOTÃO VOLTAR NAVEGAÇÃO CENTRALIZADO */
    .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;
        max-width: 600px;
        margin-left: auto;
        margin-right: auto;
    }

    /* CARD PREMIUM CENTRALIZADO */
    .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; }

    /* CONTAINER DE PREVIEW DO BACKGROUND */
    .preview-box {
        background: #000;
        border: 1px solid #1e293b;
        border-radius: 16px;
        overflow: hidden;
        margin-bottom: 25px;
        position: relative;
        aspect-ratio: 16/9;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
    }
    .preview-box img { width: 100%; height: 100%; object-fit: cover; transition: 0.5s; }
    .method-tag {
        position: absolute; bottom: 15px; left: 15px;
        background: rgba(0, 0, 0, 0.7); backdrop-filter: blur(5px);
        color: #fff; padding: 6px 12px; border-radius: 8px;
        font-size: 0.7rem; font-weight: 700; border: 1px solid rgba(255,255,255,0.1);
    }

    /* ALTERNADOR DE MÉTODO (SWITCH TABS) */
    .tab-container {
        display: grid; grid-template-columns: 1fr 1fr;
        background: #0f172a; border-radius: 14px;
        padding: 6px; margin-bottom: 25px; border: 1px solid #1e293b;
        width: 100%;
    }
    .tab-item {
        padding: 14px; text-align: center; border-radius: 10px;
        font-size: 0.8rem; font-weight: 800; color: #64748b; cursor: pointer; transition: 0.3s;
        text-transform: uppercase;
    }
    .tab-item.active { background: #3b82f6; color: #fff; box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3); }

    /* ESTILO FORMULÁRIO */
    label { display: block; color: #3b82f6; font-size: 0.7rem; font-weight: 800; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px; }
    
    .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: 25px; 
        display: block;
    }

    /* BOTÃO */
    .btn-premium-action {
        width: 100%; background: #3b82f6 !important; color: #fff !important;
        padding: 18px; border-radius: 15px; 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;
    }
    .btn-premium-action:active { transform: scale(0.98); }
</style>

<div class="container-fluid">
    <div style="max-width: 600px; margin: 0 auto;">
        <a href="index.php" class="btn-back-nav"><i class="fas fa-chevron-left"></i> Voltar ao Início</a>
    </div>

    <div class="premium-card">
        <div class="card-header-premium">
            <h1>Papel de Parede</h1>
            <p><i class="fas fa-image mr-1"></i> Imagem de fundo do aplicativo</p>
        </div>

        <label>Visualização Atual</label>
        <div class="preview-box">
            <img src="<?= $imageFilex ?>" alt="Wallpaper Preview" id="bg-preview">
            <span class="method-tag"><i class="fas fa-info-circle mr-1"></i> <?= $methord ?></span>
        </div>

        <label>Como deseja alterar?</label>
        <div class="tab-container">
            <div class="tab-item active" id="tab-file">ENVIAR ARQUIVO</div>
            <div class="tab-item" id="tab-url">LINK DA WEB</div>
        </div>

        <form method="post" enctype="multipart/form-data" id="form-file">
            <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token']; ?>">
            <label>Selecione a Imagem (Recomendado: 1920x1080)</label>
            <input class="form-input" type="file" name="image" accept="image/*" required>
            
            <button type="submit" name="upload" class="btn-premium-action">
                <i class="fas fa-upload"></i> Atualizar Background
            </button>
        </form>

        <form method="post" id="form-url" style="display: none;">
            <input type="hidden" name="token" value="<?php echo $_SESSION['admin_token']; ?>">
            <label>Link Direto da Imagem (JPG/PNG)</label>
            <input class="form-input" type="text" name="image-url" placeholder="https://site.com/imagem-fundo.jpg" required>
            
            <button type="submit" name="url-submit" class="btn-premium-action">
                <i class="fas fa-link"></i> Salvar via URL
            </button>
        </form>
    </div>
</div>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        exit('Token expirado. Recarregue a página.');
    }

    if (isset($_POST['upload'])) {
        if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
            $uploadPath = './img_custom/Img/';
            if (!is_dir($uploadPath)) mkdir($uploadPath, 0777, true);
            $fileName = uniqid() . '.' . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath . $fileName)) {
                $jsonData = json_encode([["ImageName" => "../img_custom/Img/" . $fileName, 'Upload_type' => 'by_file']]);
                file_put_contents($jsonFilex, $jsonData);
                echo "<script>window.location.href='Image.php?status=ok';</script>";
            }
        }
    }

    if (isset($_POST['url-submit'])) {
        $imageUrl = $_POST['image-url'];
        if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
            $newImageData = [['ImageName' => $imageUrl, 'Upload_type' => 'by_url']];
            file_put_contents($jsonFilex, json_encode($newImageData));
            echo "<script>window.location.href='Image.php?status=ok';</script>";
        }
    }
}
?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    const tabFile = document.getElementById('tab-file');
    const tabUrl = document.getElementById('tab-url');
    const formFile = document.getElementById('form-file');
    const formUrl = document.getElementById('form-url');

    tabFile.addEventListener('click', () => {
        tabFile.classList.add('active');
        tabUrl.classList.remove('active');
        formFile.style.display = 'block';
        formUrl.style.display = 'none';
    });

    tabUrl.addEventListener('click', () => {
        tabUrl.classList.add('active');
        tabFile.classList.remove('active');
        formFile.style.display = 'none';
        formUrl.style.display = 'block';
    });

    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('status') === 'ok') {
        Swal.fire({ 
            icon: 'success', 
            title: 'Fundo Atualizado!', 
            text: 'O novo wallpaper foi aplicado ao sistema.',
            background: '#070e1b', 
            color: '#fff', 
            confirmButtonColor: '#3b82f6' 
        });
    }
</script>

<?php include "includes/footer.php"; ?>