<?php
session_start();

// Verifica se usuário está logado
if (!isset($_SESSION['logado']) || $_SESSION['logado'] !== true) {
    header('Location: login.php');
    exit;
}

// APENAS SUPER_ADMIN pode gerenciar avisos
if ($_SESSION['permissao'] !== 'super_admin') {
    header('Location: index.php');
    exit;
}

require_once 'conexao.php';

$tenant_id = $_SESSION['tenant_id'] ?? 0;
$usuario_id = $_SESSION['usuario_id'] ?? 0;
$mensagem = '';
$erro = '';

// Processar exclusão
if (isset($_GET['excluir']) && is_numeric($_GET['excluir'])) {
    $aviso_id = (int)$_GET['excluir'];
    
    // Buscar imagens para excluir
    $stmt_img = $conn->prepare("SELECT imagens FROM avisos_sistema WHERE id = ?");
    $stmt_img->bind_param("i", $aviso_id);
    $stmt_img->execute();
    $result_img = $stmt_img->get_result();
    
    if ($row_img = $result_img->fetch_assoc()) {
        if ($row_img['imagens']) {
            $imagens = json_decode($row_img['imagens'], true);
            if (is_array($imagens)) {
                foreach ($imagens as $img) {
                    if (file_exists($img)) {
                        unlink($img);
                    }
                }
            }
        }
    }
    
    $stmt = $conn->prepare("DELETE FROM avisos_sistema WHERE id = ?");
    $stmt->bind_param("i", $aviso_id);
    
    if ($stmt->execute()) {
        $mensagem = "Aviso excluído com sucesso!";
    } else {
        $erro = "Erro ao excluir aviso.";
    }
}

// Processar formulário de novo aviso
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['criar_aviso'])) {
    $titulo = trim($_POST['titulo'] ?? '');
    $conteudo = $_POST['conteudo'] ?? '';
    $data_expiracao = !empty($_POST['data_expiracao']) ? $_POST['data_expiracao'] : null;
    $global = isset($_POST['global']) ? 1 : 0;
    
    if (empty($titulo)) {
        $erro = "O título é obrigatório.";
    } elseif (empty($conteudo)) {
        $erro = "O conteúdo é obrigatório.";
    } else {
        // Processar upload de imagens
        $imagens = [];
        $upload_dir = 'uploads/avisos/globais/';
        
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        if (!empty($_FILES['imagens']['name'][0])) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            $max_size = 5 * 1024 * 1024; // 5MB
            
            foreach ($_FILES['imagens']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['imagens']['error'][$key] === UPLOAD_ERR_OK) {
                    $file_type = $_FILES['imagens']['type'][$key];
                    if (!in_array($file_type, $allowed_types)) {
                        $erro = "Tipo de arquivo não permitido. Use apenas imagens.";
                        break;
                    }
                    
                    $file_size = $_FILES['imagens']['size'][$key];
                    if ($file_size > $max_size) {
                        $erro = "Arquivo muito grande. Máximo 5MB por imagem.";
                        break;
                    }
                    
                    $ext = pathinfo($_FILES['imagens']['name'][$key], PATHINFO_EXTENSION);
                    $nome_arquivo = uniqid() . '.' . $ext;
                    $caminho = $upload_dir . $nome_arquivo;
                    
                    if (move_uploaded_file($tmp_name, $caminho)) {
                        $imagens[] = $caminho;
                    }
                }
            }
        }
        
        if (empty($erro)) {
            // Inserir aviso - para super_admin, tenant_id pode ser NULL se for global
            $tenant_id_db = $global ? null : $tenant_id;
            
            $stmt = $conn->prepare("INSERT INTO avisos_sistema (tenant_id, global, titulo, conteudo, imagens, data_expiracao, criado_por) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $imagens_json = !empty($imagens) ? json_encode($imagens) : null;
            $stmt->bind_param("iissssi", $tenant_id_db, $global, $titulo, $conteudo, $imagens_json, $data_expiracao, $usuario_id);
            
            if ($stmt->execute()) {
                $mensagem = "Aviso criado com sucesso!";
            } else {
                $erro = "Erro ao criar aviso.";
            }
        }
    }
}

// Buscar avisos existentes (todos, para super_admin)
$avisos = [];
$stmt = $conn->prepare("
    SELECT a.*, u.nome as criado_por_nome,
           (SELECT COUNT(*) FROM avisos_lidos WHERE aviso_id = a.id) as total_lidos
    FROM avisos_sistema a
    LEFT JOIN usuarios u ON a.criado_por = u.id
    ORDER BY a.global DESC, a.data_criacao DESC
");
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    $avisos[] = $row;
}

// Contar total de usuários (para estatísticas)
$total_usuarios = 0;
$stmt_users = $conn->query("SELECT COUNT(*) as total FROM usuarios WHERE ativo = 'sim'");
if ($stmt_users) {
    $total_usuarios = $stmt_users->fetch_assoc()['total'];
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Avisos Globais</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            background: white;
            padding: 25px 30px;
            border-radius: 12px;
            margin-bottom: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            color: #333;
            font-size: 24px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .header h1 i { color: #667eea; }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        .btn-danger {
            background: #e53e3e;
            color: white;
        }
        .btn-danger:hover { background: #c53030; }
        .btn-success {
            background: #48bb78;
            color: white;
        }
        .btn-success:hover { background: #38a169; }
        .btn-voltar {
            background: #718096;
            color: white;
        }
        .btn-voltar:hover { background: #4a5568; }
        .btn-sm { padding: 5px 10px; font-size: 12px; }
        
        .message {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 25px;
            font-weight: 500;
        }
        .message.success {
            background: #c6f6d5;
            color: #22543d;
            border-left: 4px solid #48bb78;
        }
        .message.error {
            background: #fed7d7;
            color: #742a2a;
            border-left: 4px solid #f56565;
        }
        
        .form-container {
            background: white;
            padding: 30px;
            border-radius: 12px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .form-container h2 {
            color: #333;
            margin-bottom: 25px;
            font-size: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #4a5568;
        }
        .form-group input[type="text"],
        .form-group input[type="datetime-local"],
        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
            box-sizing: border-box;
        }
        .form-group input[type="text"]:focus,
        .form-group input[type="datetime-local"]:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }
        .form-group textarea {
            min-height: 200px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            resize: vertical;
        }
        .form-group.checkbox {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .form-group.checkbox input {
            width: 20px;
            height: 20px;
        }
        .form-group small {
            display: block;
            margin-top: 5px;
            color: #718096;
            font-size: 12px;
        }
        
        .avisos-list {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .avisos-list h2 {
            color: #333;
            margin-bottom: 25px;
            font-size: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .aviso-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s;
        }
        .aviso-item:hover {
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
        }
        .aviso-item.global {
            border-left: 4px solid #667eea;
            background: #f0f4ff;
        }
        
        .aviso-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .aviso-title {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .badge {
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }
        .badge-success { background: #c6f6d5; color: #22543d; }
        .badge-warning { background: #feebc8; color: #744210; }
        .badge-danger { background: #fed7d7; color: #742a2a; }
        .badge-info { background: #667eea; color: white; }
        
        .aviso-meta {
            display: flex;
            gap: 25px;
            color: #718096;
            font-size: 13px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        .aviso-meta span {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .aviso-preview {
            background: white;
            padding: 15px;
            border-radius: 6px;
            margin-top: 15px;
            font-size: 14px;
            color: #4a5568;
            border-left: 3px solid #667eea;
        }
        
        .image-preview {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            margin-top: 15px;
        }
        .image-preview-item {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 6px;
            border: 2px solid #e2e8f0;
            transition: transform 0.3s;
            cursor: pointer;
        }
        .image-preview-item:hover {
            transform: scale(1.1);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .empty-state {
            text-align: center;
            padding: 50px;
            color: #a0aec0;
        }
        .empty-state i {
            font-size: 50px;
            margin-bottom: 15px;
        }
        
        @media (max-width: 768px) {
            body { padding: 10px; }
            .header { flex-direction: column; gap: 15px; text-align: center; }
            .aviso-meta { gap: 15px; }
            .aviso-header { flex-direction: column; gap: 10px; align-items: flex-start; }
            .aviso-actions { width: 100%; justify-content: flex-end; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>
                <i class="fas fa-bullhorn"></i>
                Gerenciar Avisos Globais
            </h1>
            <a href="index.php" class="btn btn-voltar">
                <i class="fas fa-arrow-left"></i>
                Voltar ao Painel
            </a>
        </div>
        
        <?php if ($mensagem): ?>
            <div class="message success">
                <i class="fas fa-check-circle"></i>
                <?php echo htmlspecialchars($mensagem); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($erro): ?>
            <div class="message error">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo htmlspecialchars($erro); ?>
            </div>
        <?php endif; ?>
        
        <div class="form-container">
            <h2>
                <i class="fas fa-plus-circle"></i>
                Criar Novo Aviso (Global)
            </h2>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="criar_aviso" value="1">
                
                <div class="form-group">
                    <label for="titulo">Título do Aviso *</label>
                    <input type="text" id="titulo" name="titulo" required 
                           placeholder="Ex: Manutenção Programada, Novo Recurso, Aviso Importante...">
                </div>
                
                <div class="form-group">
                    <label for="conteudo">Conteúdo *</label>
                    <textarea id="conteudo" name="conteudo" required 
                              placeholder="Digite o conteúdo do aviso..."></textarea>
                    <small>Você pode usar tags HTML para formatar o texto.</small>
                </div>
                
                <div class="form-group">
                    <label for="imagens">Imagens (opcional - múltiplas permitidas)</label>
                    <input type="file" id="imagens" name="imagens[]" multiple accept="image/*">
                    <small>Formatos: JPG, PNG, GIF, WEBP. Máx: 5MB por imagem.</small>
                </div>
                
                <div class="form-group">
                    <label for="data_expiracao">Data de Expiração (opcional)</label>
                    <input type="datetime-local" id="data_expiracao" name="data_expiracao">
                    <small>Se definido, o aviso deixará de ser exibido após esta data.</small>
                </div>
                
                <div class="form-group checkbox">
                    <input type="checkbox" id="global" name="global" checked>
                    <label for="global">Aviso Global (para todos os tenants)</label>
                </div>
                
                <button type="submit" class="btn btn-success">
                    <i class="fas fa-paper-plane"></i>
                    Publicar Aviso
                </button>
            </form>
        </div>
        
        <div class="avisos-list">
            <h2>
                <i class="fas fa-list"></i>
                Avisos Publicados
            </h2>
            
            <?php if (empty($avisos)): ?>
                <div class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <p>Nenhum aviso publicado ainda.</p>
                </div>
            <?php else: ?>
                <?php foreach ($avisos as $aviso): ?>
                    <div class="aviso-item <?php echo $aviso['global'] ? 'global' : ''; ?>">
                        <div class="aviso-header">
                            <div class="aviso-title">
                                <?php echo htmlspecialchars($aviso['titulo']); ?>
                                <?php if ($aviso['global']): ?>
                                    <span class="badge badge-info">GLOBAL</span>
                                <?php else: ?>
                                    <span class="badge badge-warning">Tenant #<?php echo $aviso['tenant_id']; ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="aviso-actions">
                                <a href="?excluir=<?php echo $aviso['id']; ?>" 
                                   class="btn btn-danger btn-sm"
                                   onclick="return confirm('Tem certeza que deseja excluir este aviso?')">
                                    <i class="fas fa-trash"></i>
                                    Excluir
                                </a>
                            </div>
                        </div>
                        
                        <div class="aviso-meta">
                            <span><i class="fas fa-calendar"></i> <?php echo date('d/m/Y H:i', strtotime($aviso['data_criacao'])); ?></span>
                            <span><i class="fas fa-user"></i> <?php echo htmlspecialchars($aviso['criado_por_nome'] ?? 'Sistema'); ?></span>
                            <?php if ($aviso['data_expiracao']): ?>
                                <span><i class="fas fa-hourglass-end"></i> Expira: <?php echo date('d/m/Y H:i', strtotime($aviso['data_expiracao'])); ?></span>
                            <?php endif; ?>
                            <span><i class="fas fa-eye"></i> Lido: <?php echo $aviso['total_lidos']; ?>/<?php echo $total_usuarios; ?></span>
                        </div>
                        
                        <div class="aviso-preview">
                            <?php 
                                $preview = strip_tags($aviso['conteudo']);
                                echo nl2br(htmlspecialchars(substr($preview, 0, 200))) . (strlen($preview) > 200 ? '...' : '');
                            ?>
                        </div>
                        
                        <?php if ($aviso['imagens']): 
                            $imagens = json_decode($aviso['imagens'], true);
                            if (!empty($imagens)): ?>
                                <div class="image-preview">
                                    <?php foreach ($imagens as $img): ?>
                                        <img src="<?php echo htmlspecialchars($img); ?>" 
                                             class="image-preview-item"
                                             onclick="window.open(this.src, '_blank')"
                                             title="Clique para ampliar">
                                    <?php endforeach; ?>
                                </div>
                        <?php endif; endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
    document.getElementById('imagens')?.addEventListener('change', function(e) {
        const oldPreview = document.querySelector('.image-preview-upload');
        if (oldPreview) oldPreview.remove();
        
        if (this.files.length > 0) {
            const previewDiv = document.createElement('div');
            previewDiv.className = 'image-preview image-preview-upload';
            previewDiv.style.marginTop = '10px';
            
            for (let i = 0; i < this.files.length; i++) {
                const file = this.files[i];
                if (!file.type.startsWith('image/')) continue;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.createElement('img');
                    img.src = e.target.result;
                    img.className = 'image-preview-item';
                    img.title = file.name;
                    previewDiv.appendChild(img);
                }
                reader.readAsDataURL(file);
            }
            
            if (previewDiv.children.length > 0) {
                this.parentNode.appendChild(previewDiv);
            }
        }
    });
    </script>
</body>
</html>