
<?php
ob_start(); // Inicie o buffer de saída
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
include ('includes/header.php');

// Configurações
define('LOGO_UPLOAD_DIR', 'api/logo/');
define('ALLOWED_TYPES', ['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
define('MAX_FILE_SIZE', 2 * 1024 * 1024); // 2MB

// Criar diretório se não existir
if (!file_exists(LOGO_UPLOAD_DIR)) {
    mkdir(LOGO_UPLOAD_DIR, 0755, true);
}

// Nome da tabela e variáveis
$table_name = "ads";
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// Criar tabela se não existir
$adb3->exec("CREATE TABLE IF NOT EXISTS {$table_name}(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title VARCHAR(100), caminho TEXT)");

// Processar upload via arquivo
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["logo_file"]) && !isset($_POST['submitU'])) {
    $file = $_FILES["logo_file"];
    
    if (in_array($file["type"], ALLOWED_TYPES)) {
        if ($file["size"] <= MAX_FILE_SIZE) {
            $fileName = 'logo_' . time() . '.' . pathinfo($file["name"], PATHINFO_EXTENSION);
            $uploadPath = LOGO_UPLOAD_DIR . $fileName;
            
            if (move_uploaded_file($file["tmp_name"], $uploadPath)) {
                $_SESSION['alert'] = ['type' => 'success', 'message' => 'Logo enviado com sucesso!'];
                
                // Inserir no banco de dados
                $adb3->exec("INSERT INTO {$table_name}(title, caminho) VALUES('Logo Upload', '{$uploadPath}')");
            } else {
                $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Falha ao enviar o arquivo.'];
            }
        } else {
            $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Arquivo muito grande. Máximo 2MB.'];
        }
    } else {
        $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Apenas imagens JPG, PNG, GIF ou WebP são permitidas.'];
    }
    header("Location: logo.php");
    exit;
}

// Processar upload via URL
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["logo_url"]) && !isset($_POST['submitU'])) {
    $imageUrl = filter_var($_POST["logo_url"], FILTER_VALIDATE_URL);
    
    if ($imageUrl && preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $imageUrl)) {
        $uploadPath = LOGO_UPLOAD_DIR . 'logo_' . time() . '.png';
        
        $headers = @get_headers($imageUrl);
        if($headers && strpos($headers[0], '200')) {
            $imageData = file_get_contents($imageUrl);
            
            if ($imageData !== false) {
                $finfo = new finfo(FILEINFO_MIME_TYPE);
                $mime = $finfo->buffer($imageData);
                
                if (in_array($mime, ALLOWED_TYPES)) {
                    if (file_put_contents($uploadPath, $imageData)) {
                        $_SESSION['alert'] = ['type' => 'success', 'message' => 'Logo baixado com sucesso!'];
                        
                        // Inserir no banco de dados
                        $adb3->exec("INSERT INTO {$table_name}(title, caminho) VALUES('Logo URL', '{$uploadPath}')");
                    } else {
                        $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Falha ao salvar a imagem.'];
                    }
                } else {
                    $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Tipo de imagem não suportado.'];
                }
            } else {
                $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Falha ao baixar a imagem.'];
            }
        } else {
            $_SESSION['alert'] = ['type' => 'danger', 'message' => 'URL inacessível ou inválida.'];
        }
    } else {
        $_SESSION['alert'] = ['type' => 'danger', 'message' => 'URL inválida ou não é uma imagem suportada.'];
    }
    header("Location: logo.php");
    exit;
}

// Processar atualização
if (isset($_POST['submitU'])) {
    $id = $_POST['id'];
    $title = $_POST['title'];
    
    // Obter o caminho atual do logo
    $currentQuery = $adb3->query("SELECT caminho FROM {$table_name} WHERE id={$id}");
    $currentRow = $currentQuery->fetchArray();
    $currentPath = $currentRow['caminho'];
    
    $newPath = $currentPath; // Mantém o caminho atual por padrão
    
    // Verificar se um novo arquivo foi enviado
    if (!empty($_FILES["logo_file"]["name"])) {
        $file = $_FILES["logo_file"];
        
        if (in_array($file["type"], ALLOWED_TYPES)) {
            if ($file["size"] <= MAX_FILE_SIZE) {
                $fileName = 'logo_' . time() . '.' . pathinfo($file["name"], PATHINFO_EXTENSION);
                $uploadPath = LOGO_UPLOAD_DIR . $fileName;
                
                if (move_uploaded_file($file["tmp_name"], $uploadPath)) {
                    // Remove o arquivo antigo se existir
                    if (!empty($currentPath) && file_exists($currentPath)) {
                        unlink($currentPath);
                    }
                    $newPath = $uploadPath;
                }
            }
        }
    }
    
    // Atualizar no banco de dados
    $adb3->exec("UPDATE {$table_name} SET title='{$title}', caminho='{$newPath}' WHERE id='{$id}'");
    echo "<script>window.location.href='{$base_file}?status=5';</script>";
    exit;
}

// Processar exclusão
if (isset($_GET['delete'])) {
    $deleteQuery = $adb3->query("SELECT caminho FROM {$table_name} WHERE id={$_GET['delete']}");
    $deleteRow = $deleteQuery->fetchArray();
    $deleteUrl = $deleteRow['caminho'];
    
    if(file_exists($deleteUrl)) {
        unlink($deleteUrl);
    }
    $adb3->exec("DELETE FROM {$table_name} WHERE id={$_GET['delete']}");
    echo "<script>window.location.href='{$base_file}?status=6';</script>";
    exit;
}

// Processar exclusão de todos os registros
if (isset($_GET['deleteall'])) {
    $getAllQuery = $adb3->query("SELECT caminho FROM {$table_name}");
    while ($row = $getAllQuery->fetchArray()) {
        if (!empty($row['caminho']) && file_exists($row['caminho'])) {
            unlink($row['caminho']);
        }
    }
    
    $adb3->exec("DELETE FROM {$table_name}");
    echo "<script>window.location.href='{$base_file}?status=7';</script>";
    exit;
}

// Consultas
$res = $adb3->query("SELECT * FROM {$table_name}");
@$resU = $adb3->query("SELECT * FROM {$table_name} WHERE id='{$_GET['update']}'");
@$rowU = $resU->fetchArray();

// Verificar se existem logos
$countQuery = $adb3->query("SELECT COUNT(*) as total FROM {$table_name}");
$countRow = $countQuery->fetchArray();
$hasLogos = ($countRow['total'] > 0);
?>

<style>
/* Main Colors - Dark Blue Theme (igual ao qrcode.php) */
:root {
    --primary-blue: #1a237e;
    --dark-blue: #0d1541;
    --accent-blue: #3d5afe;
    --light-blue: #e8eaf6;
    --danger-red: #dc3545;
    --success-green: #28a745;
    --warning-orange: #fd7e14;
    --white: #ffffff;
    --light-gray: #f8f9fa;
    --medium-gray: #e9ecef;
    --dark-gray: #6c757d;
    --black: #212529;
}

/* Card Styles - White with Blue Accents */
.card {
    border: none;
    border-radius: 10px;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    margin-bottom: 25px;
    background-color: var(--white);
    border: 1px solid var(--light-blue);
}

.card-header {
    border-radius: 10px 10px 0 0 !important;
    padding: 15px 20px;
    font-weight: 600;
    color: var(--white);
    background: linear-gradient(135deg, var(--primary-blue) 0%, var(--dark-blue) 100%) !important;
}

.card-body {
    padding: 25px;
    background-color: var(--white);
}

/* Form Styles */
.form-control {
    padding: 10px 12px;
    border-radius: 8px;
    border: 1px solid var(--medium-gray);
    transition: all 0.3s;
    background-color: var(--white);
}

.form-control:focus {
    border-color: var(--accent-blue);
    box-shadow: 0 0 0 3px rgba(61, 90, 254, 0.15);
}

.form-label {
    font-weight: 500;
    margin-bottom: 8px;
    color: var(--dark-blue);
    display: block;
}

/* Button Styles */
.btn {
    padding: 10px 18px;
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 0.85rem;
}

.btn-primary {
    background-color: var(--primary-blue);
    border-color: var(--primary-blue);
    color: var(--white);
}

.btn-primary:hover {
    background-color: var(--dark-blue);
    border-color: var(--dark-blue);
}

.btn-success {
    background-color: var(--success-green);
    border-color: var(--success-green);
    color: var(--white);
}

.btn-success:hover {
    background-color: #218838;
    border-color: #1e7e34;
}

/* Botões menores */
.btn-smaller {
    padding: 8px 16px;
    font-size: 0.85rem;
}

/* Títulos menores */
.card-header-smaller h4 {
    font-size: 1.1rem;
    margin-bottom: 0;
}

/* Logo Preview Section */
.logo-current-section {
    background-color: var(--light-blue);
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 25px;
    text-align: center;
    border: 1px solid var(--accent-blue);
}

.logo-preview {
    max-width: 200px;
    max-height: 100px;
    border-radius: 8px;
    border: 1px solid var(--medium-gray);
    margin: 0 auto 15px;
    display: block;
    box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.smaller-preview {
    max-width: 180px;
    max-height: 80px;
}

.logo-section {
    margin-bottom: 30px;
    padding-bottom: 30px;
    border-bottom: 1px solid var(--medium-gray);
}

.logo-section:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.section-title {
    color: var(--primary-blue);
    margin-bottom: 20px;
    font-size: 1.1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
}

.section-title i {
    margin-right: 10px;
    font-size: 1.2rem;
    color: var(--accent-blue);
}

.upload-method {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
}

.upload-method-btn {
    flex: 1;
    padding: 10px;
    border-radius: 8px;
    background: var(--light-gray);
    border: 1px solid var(--medium-gray);
    cursor: pointer;
    transition: all 0.3s;
    text-align: center;
    font-size: 0.85rem;
}

.upload-method-btn.active {
    border-color: var(--accent-blue);
    background-color: rgba(61, 90, 254, 0.1);
}

.upload-method-btn i {
    font-size: 1.2rem;
    margin-bottom: 8px;
    color: var(--accent-blue);
}

/* Table Styles */
.table-responsive {
    overflow-x: auto;
}

.table {
    width: 100%;
    margin-bottom: 1rem;
    color: var(--black);
    background-color: var(--white);
    font-size: 0.9rem;
}

.table th,
.table td {
    padding: 0.6rem;
    vertical-align: top;
    border-top: 1px solid var(--medium-gray);
}

.table thead th {
    vertical-align: bottom;
    border-bottom: 2px solid var(--medium-gray);
    background-color: var(--light-blue);
    color: var(--dark-blue);
    font-size: 0.9rem;
}

.table tbody + tbody {
    border-top: 2px solid var(--medium-gray);
}

.table-striped tbody tr:nth-of-type(odd) {
    background-color: rgba(0, 0, 0, 0.05);
}

.table-hover tbody tr:hover {
    background-color: rgba(0, 0, 0, 0.075);
}

/* Responsive Adjustments */
@media (max-width: 768px) {
    .card-body {
        padding: 15px;
    }
    
    .upload-method {
        flex-direction: column;
    }
    
    .logo-preview {
        max-width: 150px;
    }
    
    .table-responsive {
        display: block;
        width: 100%;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }
}
</style>

<div class="container-fluid py-4">
    <?php if (isset($_GET['status'])): ?>
        <?php if ($_GET['status'] == 5): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> Operação realizada com sucesso!
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php elseif ($_GET['status'] == 6): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> Logo excluído com sucesso!
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php elseif ($_GET['status'] == 7): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle me-2"></i> Todos os logos foram excluídos com sucesso!
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php endif; ?>
    <?php endif; ?>

    <?php if (isset($_SESSION['alert'])): ?>
        <div class="alert alert-<?= $_SESSION['alert']['type'] ?> alert-dismissible fade show" role="alert">
            <i class="fas <?= $_SESSION['alert']['type'] === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?> me-2"></i>
            <?= $_SESSION['alert']['message'] ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        <?php unset($_SESSION['alert']); ?>
    <?php endif; ?>

    <?php if (isset($_GET['create'])): ?>
        <!-- Formulário de criação -->
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card shadow-sm">
                    <div class="card-header card-header-smaller">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-plus-circle me-2"></i>Novo Logo</h4>
                            <a href="<?= $base_file ?>" class="btn btn-light btn-smaller">
                                <i class="fas fa-arrow-left me-1"></i> Voltar
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="upload-method">
                            <div class="upload-method-btn active" onclick="showUploadMethod('file')">
                                <i class="fas fa-file-upload"></i>
                                <div>Upload de Arquivo</div>
                            </div>
                            <div class="upload-method-btn" onclick="showUploadMethod('url')">
                                <i class="fas fa-link"></i>
                                <div>Importar por URL</div>
                            </div>
                        </div>
                        
                        <!-- Método: Upload de Arquivo -->
                        <div id="file-upload-method">
                            <form method="post" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label for="title" class="form-label">Nome do Logo</label>
                                    <input type="text" class="form-control" id="title" name="title" required>
                                </div>
                                <div class="mb-3">
                                    <label for="logo_file" class="form-label">Imagem do Logo</label>
                                    <input type="file" class="form-control" id="logo_file" name="logo_file" accept="image/*" required>
                                    <small class="text-muted">Formatos aceitos: JPG, PNG, GIF, WebP (Máx. 2MB)</small>
                                </div>
                                <div class="text-center mt-4">
                                    <button type="submit" class="btn btn-primary px-4 btn-smaller">
                                        <i class="fas fa-save me-2"></i>Salvar
                                    </button>
                                </div>
                            </form>
                        </div>
                        
                        <!-- Método: Importar por URL -->
                        <div id="url-upload-method" style="display: none;">
                            <form method="post">
                                <div class="mb-3">
                                    <label for="title_url" class="form-label">Nome do Logo</label>
                                    <input type="text" class="form-control" id="title_url" name="title" required>
                                </div>
                                <div class="mb-3">
                                    <label for="logo_url" class="form-label">URL da Imagem</label>
                                    <input type="url" class="form-control" id="logo_url" name="logo_url" 
                                           placeholder="https://exemplo.com/logo.png" required>
                                    <small class="text-muted">Informe uma URL direta para uma imagem</small>
                                </div>
                                <div class="text-center mt-4">
                                    <button type="submit" class="btn btn-success px-4 btn-smaller">
                                        <i class="fas fa-download me-2"></i>Importar
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    
    <?php elseif (isset($_GET['update'])): ?>
        <!-- Formulário de edição -->
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card shadow-sm">
                    <div class="card-header card-header-smaller">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-edit me-2"></i>Editar Logo</h4>
                            <a href="<?= $base_file ?>" class="btn btn-light btn-smaller">
                                <i class="fas fa-arrow-left me-1"></i> Voltar
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <form method="post" enctype="multipart/form-data">
                            <input type="hidden" name="id" value="<?= $_GET['update'] ?>">
                            <div class="mb-3">
                                <label for="title" class="form-label">Nome do Logo</label>
                                <input type="text" class="form-control" id="title" name="title" value="<?= htmlspecialchars($rowU['title']) ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Imagem Atual</label>
                                <?php if (!empty($rowU['caminho']) && file_exists($rowU['caminho'])): ?>
                                    <img src="<?= $rowU['caminho'] ?>" class="logo-preview d-block mb-2">
                                    <small class="text-muted"><?= basename($rowU['caminho']) ?></small>
                                <?php else: ?>
                                    <p class="text-muted">Nenhuma imagem carregada</p>
                                <?php endif; ?>
                            </div>
                            <div class="mb-3">
                                <label for="logo_file" class="form-label">Substituir Imagem</label>
                                <input type="file" class="form-control" id="logo_file" name="logo_file" accept="image/*">
                                <small class="text-muted">Deixe em branco para manter a imagem atual</small>
                            </div>
                            <div class="text-center mt-4">
                                <button type="submit" name="submitU" class="btn btn-primary px-4 btn-smaller">
                                    <i class="fas fa-save me-2"></i>Atualizar
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    
    <?php else: ?>
        <!-- Lista de logos -->
        <div class="row">
            <div class="col-12">
                <div class="card shadow-sm">
                    <div class="card-header card-header-smaller">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-images me-2"></i>Gerenciamento de Logos</h4>
                            <div>
                                <?php if ($hasLogos): ?>
                                <a href="<?= $base_file ?>?deleteall" class="btn btn-danger btn-smaller me-2" onclick="return confirm('Tem certeza que deseja excluir TODOS os logos? Esta ação não pode ser desfeita e todos os arquivos serão removidos.');">
                                    <i class="fas fa-trash-alt me-1"></i> Remover Todos
                                </a>
                                <?php endif; ?>
                                <a href="<?= $base_file ?>?create" class="btn btn-light btn-smaller">
                                    <i class="fas fa-plus me-1"></i> Novo Logo
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if ($hasLogos): ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th width="5%">ID</th>
                                        <th width="25%">Nome</th>
                                        <th width="50%">Prévia</th>
                                        <th width="20%" class="text-center">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $listRes = $adb3->query("SELECT * FROM {$table_name}");
                                    while ($row = $listRes->fetchArray()): 
                                    ?>
                                    <tr>
                                        <td><?= $row['id'] ?></td>
                                        <td><?= htmlspecialchars($row['title']) ?></td>
                                        <td>
                                            <?php if (!empty($row['caminho']) && file_exists($row['caminho'])): ?>
                                                <img src="<?= $row['caminho'] ?>" class="logo-preview smaller-preview">
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <a href="<?= $base_file ?>?update=<?= $row['id'] ?>" class="btn btn-outline-primary btn-sm me-1">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="<?= $base_file ?>?delete=<?= $row['id'] ?>" class="btn btn-outline-danger btn-sm" onclick="return confirm('Tem certeza que deseja excluir este logo? Esta ação não pode ser desfeita.');">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                        <div class="text-center py-4">
                            <i class="fas fa-image fa-3x text-muted mb-3"></i>
                            <p class="text-muted">Nenhum logo encontrado. Clique em "Novo Logo" para adicionar.</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
// Mostrar método de upload selecionado
function showUploadMethod(method) {
    document.querySelectorAll('.upload-method-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    if (method === 'file') {
        document.getElementById('file-upload-method').style.display = 'block';
        document.getElementById('url-upload-method').style.display = 'none';
        document.querySelector('.upload-method-btn:nth-child(1)').classList.add('active');
    } else {
        document.getElementById('file-upload-method').style.display = 'none';
        document.getElementById('url-upload-method').style.display = 'block';
        document.querySelector('.upload-method-btn:nth-child(2)').classList.add('active');
    }
}

// Fechar alertas automaticamente
setTimeout(function() {
    document.querySelectorAll('.alert').forEach(function(alert) {
        var closeButton = alert.querySelector('.btn-close');
        if (closeButton) {
            closeButton.click();
        }
    });
}, 5000);
</script>

<?php 
ob_end_flush(); // Envie a saída do buffer
include ('includes/footer.php');
?>
