<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

// Configurações (Mantidas originais)
$upload_dir = __DIR__ . '/rtx/img/';
$db_path = __DIR__ . '/ibo_panel.db';

// Criar diretório se não existir (Proteção extra)
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

try {
    $db = new SQLite3($db_path);
} catch (Exception $e) {
    die("Erro ao conectar ao banco de dados: " . $e->getMessage());
}

// --- Processar uploads e Deletes (Sua lógica original preservada) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    try {
        if (isset($_POST['action']) && $_POST['action'] === 'delete') {
            $id = (int)$_POST['id'];
            $stmt = $db->prepare("SELECT url FROM ads WHERE id = :id");
            $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
            $result = $stmt->execute();
            $row = $result->fetchArray(SQLITE3_ASSOC);
            if (!$row) throw new Exception('Registro não encontrado.');
            $url = $row['url'];
            $file_path = __DIR__ . parse_url($url, PHP_URL_PATH);
            $stmt = $db->prepare("DELETE FROM ads WHERE id = :id");
            $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
            if (!$stmt->execute()) throw new Exception('Falha ao excluir do banco de dados.');
            if (file_exists($file_path)) unlink($file_path);
            echo json_encode(['status' => 'success', 'message' => 'Imagem excluída com sucesso!']);
        } elseif (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $file_type = $_FILES['image']['type'];
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!in_array($file_type, $allowed_types)) throw new Exception('Tipo de arquivo não permitido.');
            $title = isset($_POST['title']) ? trim($_POST['title']) : 'Imagem ' . date('d/m/Y H:i');
            $file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $file_name = uniqid('img_') . '.' . $file_ext;
            $file_path = $upload_dir . $file_name;
            if (!move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) throw new Exception('Erro ao mover arquivo.');
            $url = dirname($_SERVER['SCRIPT_NAME']) . '/rtx/img/' . $file_name;
            $stmt = $db->prepare("INSERT INTO ads (title, url) VALUES (:title, :url)");
            $stmt->bindValue(':title', $title, SQLITE3_TEXT);
            $stmt->bindValue(':url', $url, SQLITE3_TEXT);
            if (!$stmt->execute()) {
                unlink($file_path);
                throw new Exception('Falha ao salvar no banco.');
            }
            echo json_encode(['status' => 'success', 'message' => 'Imagem enviada com sucesso!', 'url' => $url]);
        } else {
            throw new Exception('Nenhum arquivo enviado.');
        }
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

$results = $db->query("SELECT id, title, url FROM ads ORDER BY id DESC");
$images = [];
while ($row = $results->fetchArray(SQLITE3_ASSOC)) { $images[] = $row; }

$page_title = "Galeria de Anúncios";

$page_content = '
<div class="card shadow-sm">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <div class="d-flex align-items-center position-relative my-1">
                <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i>
                <input type="text" id="gallerySearch" class="form-control form-control-solid w-250px ps-12" placeholder="Pesquisar imagem..." />
            </div>
            <div class="ms-4">
                <span class="badge badge-light-primary fs-7 fw-bold">Total: ' . count($images) . '</span>
            </div>
        </div>
        <div class="card-toolbar">
            <button type="button" class="btn btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#uploadModal">
                <i class="ki-outline ki-cloud-add fs-2"></i> Enviar Imagem
            </button>
        </div>
    </div>
    
    <div class="card-body">
        <div class="row g-6" id="imageGallery">
';

if (empty($images)) {
    $page_content .= '<div class="col-12 text-center py-20 text-muted">Nenhuma imagem encontrada na galeria.</div>';
}

foreach ($images as $image) {
    $page_content .= '
            <div class="col-md-4 col-xl-3 image-item" data-title="' . strtolower(htmlspecialchars($image['title'])) . '">
                <div class="card card-flush shadow-sm h-100 border border-secondary border-opacity-10">
                    <div class="card-body p-0">
                        <div class="overlay overflow-hidden rounded">
                            <img src="' . $image['url'] . '" class="card-img-top" alt="' . htmlspecialchars($image['title']) . '" style="height: 180px; object-fit: cover;">
                        </div>
                        <div class="p-5">
                            <h5 class="fs-6 fw-bold text-gray-800 text-truncate mb-4" title="' . htmlspecialchars($image['title']) . '">' . htmlspecialchars($image['title']) . '</h5>
                            
                            <div class="d-flex flex-stack">
                                <button class="btn btn-sm btn-icon btn-light-primary me-2" onclick="copyToClipboard(\'' . $image['url'] . '\')" title="Copiar Link">
                                    <i class="ki-outline ki-copy fs-2"></i>
                                </button>
                                
                                <button class="btn btn-sm btn-light-danger flex-grow-1" onclick="deleteImage(' . $image['id'] . ')">
                                    <i class="ki-outline ki-trash fs-3"></i> Excluir
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
    ';
}

$page_content .= '
        </div>
    </div>
</div>

<div class="modal fade" id="uploadModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">Nova Imagem de Anúncio</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="uploadForm">
                    <div class="mb-7">
                        <label class="form-label fw-semibold">Título de Referência</label>
                        <input type="text" class="form-control form-control-solid" id="imageTitle" placeholder="Ex: Banner Promocional">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Arquivo de Imagem</label>
                        <input class="form-control" type="file" id="imageUpload" accept="image/*" required>
                    </div>
                </form>
                <div id="uploadPreview" class="text-center mt-5 d-none">
                    <img id="previewImage" src="#" class="img-fluid rounded shadow-sm border" style="max-height: 250px;">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Fechar</button>
                <button type="button" class="btn btn-primary" id="uploadButton">Fazer Upload</button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php';
?>

<script>
    // Filtro de Busca (O NOVO)
    document.getElementById('gallerySearch').addEventListener('keyup', function() {
        let filter = this.value.toLowerCase();
        let items = document.querySelectorAll('.image-item');
        
        items.forEach(item => {
            let title = item.getAttribute('data-title');
            item.style.display = title.includes(filter) ? "" : "none";
        });
    });

    // Função Copiar (O NOVO)
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(() => {
            Swal.fire({
                text: "URL da imagem copiada!",
                icon: "success",
                timer: 1500,
                showConfirmButton: false,
                position: 'top-end',
                toast: true
            });
        });
    }

    // Pré-visualização (Sua lógica mantida)
    document.getElementById('imageUpload').addEventListener('change', function(e) {
        const preview = document.getElementById('uploadPreview');
        const previewImage = document.getElementById('previewImage');
        if (this.files && this.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                previewImage.src = e.target.result;
                preview.classList.remove('d-none');
            }
            reader.readAsDataURL(this.files[0]);
        }
    });

    // Enviar (Sua lógica mantida)
    document.getElementById('uploadButton').addEventListener('click', function() {
        const formData = new FormData();
        const fileInput = document.getElementById('imageUpload');
        const titleInput = document.getElementById('imageTitle');
        if (fileInput.files.length === 0) {
            Swal.fire({ icon: 'error', title: 'Erro', text: 'Selecione uma imagem!' });
            return;
        }
        formData.append('image', fileInput.files[0]);
        formData.append('title', titleInput.value);
        
        fetch('ads.php', { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                Swal.fire({ icon: 'success', title: 'Sucesso!', text: data.message }).then(() => location.reload());
            } else {
                Swal.fire({ icon: 'error', title: 'Erro', text: data.message });
            }
        });
    });

    // Excluir (Sua lógica mantida)
    function deleteImage(id) {
        Swal.fire({
            title: 'Excluir imagem?',
            text: "Essa ação removerá o arquivo permanentemente.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Sim, excluir!',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('ads.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: new URLSearchParams({ action: 'delete', id: id })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') location.reload();
                    else Swal.fire({ icon: 'error', title: 'Erro', text: data.message });
                });
            }
        });
    }
</script>