<?php
// admin/news_add.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require '../includes/conexao.php';

// SEGURANÇA
if (!isset($_SESSION['account_id'])) { header("Location: ../login.php"); exit; }

$stmt = $pdo->prepare("SELECT page_access, name FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$acc = $stmt->fetch();

if (!$acc || $acc['page_access'] < 3) {
    die("<div class='container p-5 text-center text-white bg-dark'><h1>⛔ Acesso Negado</h1><a href='../index.php' class='btn btn-warning'>Voltar</a></div>");
}

$page_title = "Gerenciar Notícias";

// Header
if(file_exists('../includes/admin_header.php')) include '../includes/admin_header.php';
else include '../includes/header.php';

$msg = '';
$editMode = false;
$newsData = [];

// --- 1. PROCESSAR AÇÕES ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // A. EXCLUIR
    if (isset($_POST['delete_id'])) {
        // Busca imagem para deletar o arquivo fisico
        $stmtImg = $pdo->prepare("SELECT image FROM site_news WHERE id = ?");
        $stmtImg->execute([$_POST['delete_id']]);
        $imgDel = $stmtImg->fetchColumn();
        
        $stmt = $pdo->prepare("DELETE FROM site_news WHERE id = ?");
        if ($stmt->execute([$_POST['delete_id']])) {
            // Remove arquivo físico se não for o padrão
            if($imgDel && $imgDel != 'default.png' && file_exists("../" . $imgDel)) {
                @unlink("../" . $imgDel); 
            }
            $msg = '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-trash-alt me-2"></i> Notícia removida com sucesso!</div>';
        }
    }

    // B. SALVAR (CRIAR OU EDITAR)
    elseif (isset($_POST['action']) && $_POST['action'] == 'save') {
        $title = trim($_POST['title']);
        $body = $_POST['body'];
        $date = time();
        $id = $_POST['id'] ?? null;
        
        // Upload da Imagem
        $image_path = $_POST['current_image'] ?? 'images/default_news.jpg'; // Caminho padrão

        if (!empty($_FILES['news_image']['name'])) {
            $target_dir = "../images/news/";
            // Cria a pasta se ela não existir
            if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
            
            $ext = strtolower(pathinfo($_FILES['news_image']['name'], PATHINFO_EXTENSION));
            $allowed = ['png', 'jpg', 'jpeg', 'gif', 'webp'];
            
            if(in_array($ext, $allowed)) {
                $new_name = uniqid('news_') . '.' . $ext;
                if(move_uploaded_file($_FILES['news_image']['tmp_name'], $target_dir . $new_name)) {
                    $image_path = "images/news/" . $new_name;
                }
            } else {
                $msg = '<div class="alert alert-danger shadow-sm border-0">Formato de imagem inválido! Use PNG, JPG ou GIF.</div>';
            }
        }

        if(empty($msg)) {
            if ($id) {
                // UPDATE
                $sql = "UPDATE site_news SET title = ?, body = ?, image = ? WHERE id = ?";
                $stmt = $pdo->prepare($sql);
                if($stmt->execute([$title, $body, $image_path, $id])) {
                    $msg = '<div class="alert alert-info shadow-sm border-0"><i class="fas fa-check-circle me-2"></i> Notícia atualizada com sucesso! <a href="news_add.php" class="fw-bold text-dark">Voltar</a></div>';
                    $editMode = false;
                }
            } else {
                // INSERT
                // Se sua tabela tiver coluna 'username', adicione aqui. Se não, remova.
                // Vou assumir que tem 'username' baseado no dump original, se não tiver, remova do SQL.
                try {
                    $author = $acc['name'];
                    $sql = "INSERT INTO site_news (title, body, date, image, username) VALUES (?, ?, ?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    if($stmt->execute([$title, $body, $date, $image_path, $author])) {
                        $msg = '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-plus-circle me-2"></i> Notícia publicada com sucesso!</div>';
                    }
                } catch (Exception $e) {
                    // Fallback sem username caso a tabela não tenha
                    $sql = "INSERT INTO site_news (title, body, date, image) VALUES (?, ?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$title, $body, $date, $image_path]);
                    $msg = '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-plus-circle me-2"></i> Notícia publicada!</div>';
                }
            }
        }
    }
}

// --- 2. MODO EDIÇÃO ---
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM site_news WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $newsData = $stmt->fetch();
    if($newsData) $editMode = true;
}

// --- 3. LISTAGEM COM PAGINAÇÃO ---
$limit = 5; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;

// Contar total
$totalResults = $pdo->query("SELECT COUNT(*) FROM site_news")->fetchColumn();
$totalPages = ceil($totalResults / $limit);

// Buscar itens
$newsList = $pdo->query("SELECT * FROM site_news ORDER BY date DESC LIMIT $start, $limit")->fetchAll();
?>

<style>
    /* Estilo Dark Admin */
    body { background-color: #0f172a; color: #f8fafc; font-family: 'Poppins', sans-serif; }
    
    .card { background-color: #1e293b; border: 1px solid rgba(255,255,255,0.1); color: #fff; border-radius: 12px; }
    
    .form-control { background-color: #0f172a; border: 1px solid rgba(255,255,255,0.2); color: #fff; }
    .form-control:focus { background-color: #0f172a; color: #fff; border-color: #3b82f6; box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25); }
    .form-label { color: #cbd5e1; font-weight: 600; text-transform: uppercase; font-size: 0.85rem; }
    
    .list-group-item { background-color: transparent; border-color: rgba(255,255,255,0.05); color: #cbd5e1; transition: background 0.2s; }
    .list-group-item:hover { background-color: rgba(255,255,255,0.02); color: #fff; }
    
    .pagination .page-link { background-color: #1e293b; border-color: rgba(255,255,255,0.1); color: #fff; }
    .pagination .page-item.active .page-link { background-color: #3b82f6; border-color: #3b82f6; }
    .pagination .page-item.disabled .page-link { background-color: #0f172a; color: #64748b; }

    /* TinyMCE Dark Mode Override (CSS básico para a área ao redor) */
    .tox-tinymce { border: 1px solid rgba(255,255,255,0.2) !important; border-radius: 8px !important; }
</style>

<div class="container my-5">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold text-white mb-0"><i class="fas fa-newspaper text-primary me-2"></i>Gestão de Notícias</h2>
            <p class="text-white-50 m-0">Publique atualizações, eventos e patch notes.</p>
        </div>
        <div>
            <?php if($editMode): ?>
                <a href="news_add.php" class="btn btn-secondary btn-sm"><i class="fas fa-times me-1"></i> Cancelar Edição</a>
            <?php else: ?>
                <a href="../index.php" target="_blank" class="btn btn-outline-light btn-sm"><i class="fas fa-external-link-alt me-1"></i> Ver Site</a>
            <?php endif; ?>
        </div>
    </div>

    <?php echo $msg; ?>

    <div class="row g-4">
        
        <div class="col-lg-8">
            <div class="card shadow border-top border-4 <?php echo $editMode ? 'border-warning' : 'border-primary'; ?>">
                <div class="card-header bg-transparent fw-bold py-3 text-white border-bottom border-secondary">
                    <i class="fas <?php echo $editMode ? 'fa-edit text-warning' : 'fa-pen-fancy text-primary'; ?> me-2"></i> 
                    <?php echo $editMode ? 'Editando: ' . htmlspecialchars($newsData['title']) : 'Escrever Nova Notícia'; ?>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="action" value="save">
                        <?php if($editMode): ?>
                            <input type="hidden" name="id" value="<?php echo $newsData['id']; ?>">
                            <input type="hidden" name="current_image" value="<?php echo $newsData['image']; ?>">
                        <?php endif; ?>

                        <div class="mb-3">
                            <label class="form-label">Título</label>
                            <input type="text" name="title" class="form-control form-control-lg" placeholder="Ex: Grande Update de Natal!" required value="<?php echo $newsData['title'] ?? ''; ?>">
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Imagem de Capa</label>
                            <div class="input-group">
                                <input type="file" name="news_image" class="form-control" accept="image/*">
                            </div>
                            <?php if($editMode && !empty($newsData['image'])): ?>
                                <div class="mt-2 d-flex align-items-center p-2 rounded bg-dark border border-secondary" style="width: fit-content;">
                                    <img src="../<?php echo $newsData['image']; ?>" style="height: 40px; width: 40px; object-fit: cover; border-radius: 4px;" class="me-2">
                                    <span class="text-white-50 small">Imagem Atual</span>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Conteúdo</label>
                            <textarea id="editor" name="body" rows="20" placeholder="Escreva aqui..."><?php echo $newsData['body'] ?? ''; ?></textarea>
                        </div>

                        <div class="d-grid">
                            <button type="submit" class="btn btn-lg fw-bold <?php echo $editMode ? 'btn-warning text-dark' : 'btn-success'; ?>">
                                <i class="fas fa-save me-2"></i> <?php echo $editMode ? 'SALVAR ALTERAÇÕES' : 'PUBLICAR NOTÍCIA'; ?>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card shadow h-100">
                <div class="card-header bg-dark text-white fw-bold d-flex justify-content-between align-items-center border-secondary">
                    <span><i class="fas fa-history me-2 text-info"></i> Últimas Publicações</span>
                    <span class="badge bg-primary rounded-pill"><?php echo $totalResults; ?></span>
                </div>
                <div class="list-group list-group-flush">
                    <?php if(count($newsList) > 0): ?>
                        <?php foreach($newsList as $news): 
                            $imgThumb = "../" . ($news['image'] ?: 'images/default_news.jpg');
                            $isActive = ($editMode && $newsData['id'] == $news['id']);
                        ?>
                        <div class="list-group-item p-3 <?php echo $isActive ? 'bg-primary bg-opacity-10 border-start border-4 border-primary' : ''; ?>">
                            <div class="d-flex align-items-start mb-2">
                                <img src="<?php echo $imgThumb; ?>" class="rounded me-3 border border-secondary" style="width: 60px; height: 60px; object-fit: cover; background: #000;" onerror="this.src='https://via.placeholder.com/60'">
                                <div class="flex-grow-1 overflow-hidden">
                                    <h6 class="mb-1 text-truncate fw-bold text-white" title="<?php echo htmlspecialchars($news['title']); ?>">
                                        <?php echo htmlspecialchars($news['title']); ?>
                                    </h6>
                                    <div class="small text-white-50">
                                        <i class="far fa-clock me-1"></i> <?php echo date('d/m/y H:i', $news['date']); ?>
                                    </div>
                                </div>
                            </div>
                            <div class="d-flex gap-2">
                                <a href="?edit=<?php echo $news['id']; ?>" class="btn btn-sm btn-outline-primary w-50 fw-bold"><i class="fas fa-pen me-1"></i> Editar</a>
                                <form method="POST" class="w-50" onsubmit="return confirm('Tem certeza que deseja apagar esta notícia?');">
                                    <input type="hidden" name="delete_id" value="<?php echo $news['id']; ?>">
                                    <button class="btn btn-sm btn-outline-danger w-100 fw-bold"><i class="fas fa-trash me-1"></i> Apagar</button>
                                </form>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="p-5 text-center text-white-50">
                            <i class="fas fa-inbox fa-3x mb-3 opacity-25"></i>
                            <p>Nenhuma notícia encontrada.</p>
                        </div>
                    <?php endif; ?>
                </div>
                
                <?php if($totalPages > 1): ?>
                <div class="card-footer bg-dark border-secondary">
                    <nav>
                        <ul class="pagination pagination-sm justify-content-center mb-0">
                            <li class="page-item <?php echo ($page <= 1) ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $page-1; ?>">&laquo;</a>
                            </li>
                            <?php for($i = 1; $i <= $totalPages; $i++): ?>
                                <li class="page-item <?php echo ($page == $i) ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            <li class="page-item <?php echo ($page >= $totalPages) ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $page+1; ?>">&raquo;</a>
                            </li>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php if(file_exists('../includes/admin_footer.php')) include '../includes/admin_footer.php'; else include '../includes/footer.php'; ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/6.8.2/tinymce.min.js"></script>
<script>
    tinymce.init({
        selector: '#editor',
        height: 500,
        skin: "oxide-dark", // Tema Escuro
        content_css: "dark", // Conteúdo Escuro
        menubar: true,
        branding: false,
        plugins: 'advlist autolink lists link image charmap preview anchor searchreplace visualblocks code fullscreen insertdatetime media table help wordcount',
        toolbar: 'undo redo | blocks | ' +
        'bold italic underline forecolor backcolor | alignleft aligncenter ' +
        'alignright alignjustify | bullist numlist outdent indent | ' +
        'removeformat | help',
        content_style: 'body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 16px; color: #e2e8f0; background-color: #1e293b; }'
    });
</script>
</body>
</html>