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

$db = new SQLite3("./api/.ansdb.db"); 

$jsonFilex = './img/logo/logo2_filenames.json'; // Ajustado para logo2
if (!file_exists($jsonFilex)) {
    if (!is_dir('./img/logo/')) mkdir('./img/logo/', 0777, true);
    file_put_contents($jsonFilex, json_encode([["ImageName" => "", "Upload_type" => "none"]]));
}

$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/300x100?text=Sem+Logo+2";
    $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 ELEMENTOS DO HEADER */
    .lua-icon, .fa-moon, .fa-sun, .navbar, #dark-mode-switch { display: none !important; }

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

    /* BOTÃO VOLTAR */
    .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; }

    /* PREVIEW DA LOGO */
    .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;
        width: 100%;
    }
    .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; text-transform: uppercase;
    }

    /* ALTERNADOR DE MÉTODO (TABS) */
    .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; }

    /* FORMULÁRIOS */
    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;
    }

    /* BOTÕES */
    .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;
    }
    .btn-premium-save: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>Branding & Logo 2</h1>
            <p><i class="fas fa-palette mr-1"></i> Identidade visual secundária</p>
        </div>

        <label>Logo Atual</label>
        <div class="preview-box">
            <span class="method-badge"><?= $methord ?></span>
            <img src="<?= $imageFilex ?>" alt="Logo 2">
        </div>

        <label>Método de Atualização</label>
        <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="<?php echo $_SESSION['admin_token']; ?>">
            <label>Selecione o Arquivo (PNG/JPG)</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> Enviar Logotipo 2
            </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</label>
            <input class="form-input" type="text" name="image-url" placeholder="https://exemplo.com/logo.png" required>
            
            <button type="submit" name="url-submit" class="btn-premium-save">
                <i class="fas fa-link"></i> Salvar via Link
            </button>
        </form>
    </div>
</div>

<?php
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) {
            $uploadPath = './img_custom/logo/';
            if (!is_dir($uploadPath)) mkdir($uploadPath, 0777, true);
            $fileName = 'logo2_' . uniqid() . '.' . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath . $fileName)) {
                $jsonData = json_encode([["ImageName" => "../img_custom/logo/" . $fileName, 'Upload_type' => 'by_file']]);
                file_put_contents($jsonFilex, $jsonData);
                echo "<script>window.location.href='logo2.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='logo2.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 btnUpload = document.getElementById('btn-upload');
    const btnUrl = document.getElementById('btn-url');
    const formUpload = document.getElementById('form-upload');
    const formUrl = document.getElementById('form-url');

    btnUpload.addEventListener('click', () => {
        btnUpload.classList.add('active');
        btnUrl.classList.remove('active');
        formUpload.style.display = 'block';
        formUrl.style.display = 'none';
    });

    btnUrl.addEventListener('click', () => {
        btnUrl.classList.add('active');
        btnUpload.classList.remove('active');
        formUpload.style.display = 'none';
        formUrl.style.display = 'block';
    });

    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('status') === 'ok') {
        Swal.fire({ 
            icon: 'success', 
            title: 'Logo 2 Atualizada!', 
            text: 'A nova identidade foi aplicada com sucesso.',
            background: '#070e1b', 
            color: '#fff', 
            confirmButtonColor: '#3b82f6' 
        });
    }
</script>

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