<?php
// admin/newsletter-subscribers.php

$pageTitle = 'Inscritos do Newsletter';
$pageHeader = 'Gerenciar Inscritos do Newsletter';
$currentPage = 'newsletter';

// Define BASE_PATH se não estiver definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__FILE__)));
}

require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Requer autenticação
if (!$auth->isLoggedIn()) {
    redirect('admin/login.php');
    exit;
}

// Parâmetros de filtro e paginação
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$source = isset($_GET['source']) ? trim($_GET['source']) : '';
$orderBy = isset($_GET['order']) && in_array($_GET['order'], ['email', 'subscription_date', 'status']) ? $_GET['order'] : 'subscription_date';
$orderDir = isset($_GET['dir']) && $_GET['dir'] === 'asc' ? 'ASC' : 'DESC';

// Processamento de ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'delete' && isset($_POST['subscriber_id'])) {
        try {
            $subscriberId = intval($_POST['subscriber_id']);
            $db->query("DELETE FROM newsletter_subscribers WHERE id = :id");
            $db->bind(':id', $subscriberId);
            $db->execute();
            
            setAlert('Inscrito removido com sucesso!', ALERT_SUCCESS);
        } catch (Exception $e) {
            setAlert('Erro ao remover inscrito: ' . $e->getMessage(), ALERT_ERROR);
        }
    }
    
    if ($action === 'update_status' && isset($_POST['subscriber_id']) && isset($_POST['new_status'])) {
        try {
            $subscriberId = intval($_POST['subscriber_id']);
            $newStatus = $_POST['new_status'];
            
            if (in_array($newStatus, ['active', 'inactive', 'unsubscribed'])) {
                $db->query("UPDATE newsletter_subscribers SET status = :status, updated_at = NOW() WHERE id = :id");
                $db->bind(':status', $newStatus);
                $db->bind(':id', $subscriberId);
                $db->execute();
                
                setAlert('Status atualizado com sucesso!', ALERT_SUCCESS);
            }
        } catch (Exception $e) {
            setAlert('Erro ao atualizar status: ' . $e->getMessage(), ALERT_ERROR);
        }
    }
    
    if ($action === 'bulk_delete' && isset($_POST['selected_subscribers'])) {
        try {
            $ids = array_map('intval', $_POST['selected_subscribers']);
            $placeholders = str_repeat('?,', count($ids) - 1) . '?';
            
            $db->query("DELETE FROM newsletter_subscribers WHERE id IN ($placeholders)");
            foreach ($ids as $index => $id) {
                $db->bind(':id' . $index, $id);
            }
            $db->execute();
            
            setAlert(count($ids) . ' inscritos removidos com sucesso!', ALERT_SUCCESS);
        } catch (Exception $e) {
            setAlert('Erro ao remover inscritos: ' . $e->getMessage(), ALERT_ERROR);
        }
    }
    
    if ($action === 'export') {
        try {
            // Construir query de exportação
            $whereConditions = ['1=1'];
            $params = [];
            
            if (!empty($search)) {
                $whereConditions[] = "(email LIKE :search OR name LIKE :search)";
                $params[':search'] = "%$search%";
            }
            
            if (!empty($status)) {
                $whereConditions[] = "status = :status";
                $params[':status'] = $status;
            }
            
            if (!empty($source)) {
                $whereConditions[] = "source = :source";
                $params[':source'] = $source;
            }
            
            $whereClause = implode(' AND ', $whereConditions);
            
            $db->query("SELECT email, name, status, source, subscription_date 
                       FROM newsletter_subscribers 
                       WHERE $whereClause 
                       ORDER BY $orderBy $orderDir");
            
            foreach ($params as $key => $value) {
                $db->bind($key, $value);
            }
            
            $results = $db->resultSet();
            
            // Gerar CSV
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="newsletter_subscribers_' . date('Y-m-d') . '.csv"');
            
            $output = fopen('php://output', 'w');
            
            // Cabeçalhos do CSV
            fputcsv($output, ['Email', 'Nome', 'Status', 'Origem', 'Data de Inscrição']);
            
            // Dados
            foreach ($results as $row) {
                fputcsv($output, [
                    $row['email'],
                    $row['name'],
                    $row['status'],
                    $row['source'],
                    $row['subscription_date']
                ]);
            }
            
            fclose($output);
            exit;
            
        } catch (Exception $e) {
            setAlert('Erro ao exportar dados: ' . $e->getMessage(), ALERT_ERROR);
        }
    }
    
    redirect('newsletter-subscribers.php');
}

// Construir query com filtros
$whereConditions = ['1=1'];
$params = [];

if (!empty($search)) {
    $whereConditions[] = "(email LIKE :search OR name LIKE :search)";
    $params[':search'] = "%$search%";
}

if (!empty($status)) {
    $whereConditions[] = "status = :status";
    $params[':status'] = $status;
}

if (!empty($source)) {
    $whereConditions[] = "source = :source";
    $params[':source'] = $source;
}

$whereClause = implode(' AND ', $whereConditions);

// Contar total de registros
$db->query("SELECT COUNT(*) as total FROM newsletter_subscribers WHERE $whereClause");
foreach ($params as $key => $value) {
    $db->bind($key, $value);
}
$totalResult = $db->single();
$totalRecords = $totalResult ? $totalResult['total'] : 0;
$totalPages = ceil($totalRecords / $limit);

// Buscar registros da página atual
$params[':limit'] = $limit;
$params[':offset'] = $offset;

$db->query("SELECT * FROM newsletter_subscribers 
           WHERE $whereClause 
           ORDER BY $orderBy $orderDir 
           LIMIT :limit OFFSET :offset");

foreach ($params as $key => $value) {
    $db->bind($key, $value);
}

$subscribers = $db->resultSet();

// Estatísticas rápidas
$db->query("SELECT 
           COUNT(*) as total,
           SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
           SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive,
           SUM(CASE WHEN status = 'unsubscribed' THEN 1 ELSE 0 END) as unsubscribed
           FROM newsletter_subscribers");
$stats = $db->single();

// Buscar origens disponíveis
$db->query("SELECT DISTINCT source FROM newsletter_subscribers ORDER BY source");
$sources = $db->resultSet();

require_once 'inc/header.php';
?>

<div class="container-fluid px-4">
    <!-- Cabeçalho e estatísticas -->
    <div class="row mb-4">
        <div class="col-md-8">
            <h1 class="h3 mb-3"><?php echo $pageHeader; ?></h1>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Newsletter</li>
                </ol>
            </nav>
        </div>
        <div class="col-md-4 text-md-end">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addSubscriberModal">
                <i class="fas fa-plus me-2"></i>Adicionar Inscrito
            </button>
        </div>
    </div>

    <!-- Estatísticas -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <h3 class="text-primary"><?php echo number_format($stats['total']); ?></h3>
                    <p class="text-muted mb-0">Total de Inscritos</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <h3 class="text-success"><?php echo number_format($stats['active']); ?></h3>
                    <p class="text-muted mb-0">Ativos</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <h3 class="text-warning"><?php echo number_format($stats['inactive']); ?></h3>
                    <p class="text-muted mb-0">Inativos</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center">
                    <h3 class="text-danger"><?php echo number_format($stats['unsubscribed']); ?></h3>
                    <p class="text-muted mb-0">Descadastrados</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Filtros e busca -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-4">
                    <label for="search" class="form-label">Buscar</label>
                    <input type="text" class="form-control" id="search" name="search" 
                           value="<?php echo htmlspecialchars($search); ?>" 
                           placeholder="Email ou nome...">
                </div>
                <div class="col-md-2">
                    <label for="status" class="form-label">Status</label>
                    <select class="form-select" id="status" name="status">
                        <option value="">Todos</option>
                        <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Ativo</option>
                        <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inativo</option>
                        <option value="unsubscribed" <?php echo $status === 'unsubscribed' ? 'selected' : ''; ?>>Descadastrado</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="source" class="form-label">Origem</label>
                    <select class="form-select" id="source" name="source">
                        <option value="">Todas</option>
                        <?php foreach ($sources as $src): ?>
                        <option value="<?php echo htmlspecialchars($src['source']); ?>" 
                                <?php echo $source === $src['source'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($src['source']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="order" class="form-label">Ordenar por</label>
                    <select class="form-select" id="order" name="order">
                        <option value="subscription_date" <?php echo $orderBy === 'subscription_date' ? 'selected' : ''; ?>>Data</option>
                        <option value="email" <?php echo $orderBy === 'email' ? 'selected' : ''; ?>>Email</option>
                        <option value="status" <?php echo $orderBy === 'status' ? 'selected' : ''; ?>>Status</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">&nbsp;</label>
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-search me-2"></i>Filtrar
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Lista de inscritos -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Inscritos (<?php echo number_format($totalRecords); ?>)</h5>
            <div class="d-flex gap-2">
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="export">
                    <button type="submit" class="btn btn-outline-success btn-sm">
                        <i class="fas fa-download me-2"></i>Exportar CSV
                    </button>
                </form>
                <button type="button" class="btn btn-outline-danger btn-sm" id="bulkDeleteBtn" disabled>
                    <i class="fas fa-trash me-2"></i>Excluir Selecionados
                </button>
            </div>
        </div>
        <div class="card-body p-0">
            <?php if (empty($subscribers)): ?>
            <div class="text-center py-5">
                <i class="fas fa-envelope fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">Nenhum inscrito encontrado</h5>
                <p class="text-muted">Ajuste os filtros ou adicione novos inscritos.</p>
            </div>
            <?php else: ?>
            <form id="bulkForm" method="POST">
                <input type="hidden" name="action" value="bulk_delete">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="40">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="selectAll">
                                    </div>
                                </th>
                                <th>Email</th>
                                <th>Nome</th>
                                <th>Status</th>
                                <th>Origem</th>
                                <th>Data de Inscrição</th>
                                <th width="120">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($subscribers as $subscriber): ?>
                            <tr>
                                <td>
                                    <div class="form-check">
                                        <input class="form-check-input subscriber-checkbox" type="checkbox" 
                                               name="selected_subscribers[]" value="<?php echo $subscriber['id']; ?>">
                                    </div>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($subscriber['email']); ?></strong>
                                    <?php if ($subscriber['verified']): ?>
                                    <i class="fas fa-check-circle text-success ms-1" title="Email verificado"></i>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($subscriber['name'] ?: '-'); ?></td>
                                <td>
                                    <?php
                                    $statusClass = [
                                        'active' => 'success',
                                        'inactive' => 'warning',
                                        'unsubscribed' => 'danger'
                                    ][$subscriber['status']] ?? 'secondary';
                                    
                                    $statusText = [
                                        'active' => 'Ativo',
                                        'inactive' => 'Inativo',
                                        'unsubscribed' => 'Descadastrado'
                                    ][$subscriber['status']] ?? $subscriber['status'];
                                    ?>
                                    <span class="badge bg-<?php echo $statusClass; ?>"><?php echo $statusText; ?></span>
                                </td>
                                <td><?php echo htmlspecialchars($subscriber['source']); ?></td>
                                <td><?php echo formatDate($subscriber['subscription_date']); ?></td>
                                <td>
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                            Ações
                                        </button>
                                        <ul class="dropdown-menu">
                                            <li>
                                                <a class="dropdown-item" href="#" data-bs-toggle="modal" 
                                                   data-bs-target="#editSubscriberModal" 
                                                   data-id="<?php echo $subscriber['id']; ?>"
                                                   data-email="<?php echo htmlspecialchars($subscriber['email']); ?>"
                                                   data-name="<?php echo htmlspecialchars($subscriber['name']); ?>"
                                                   data-status="<?php echo $subscriber['status']; ?>">
                                                    <i class="fas fa-edit me-2"></i>Editar
                                                </a>
                                            </li>
                                            <li><hr class="dropdown-divider"></li>
                                            <?php if ($subscriber['status'] !== 'active'): ?>
                                            <li>
                                                <form method="POST" style="display: inline;">
                                                    <input type="hidden" name="action" value="update_status">
                                                    <input type="hidden" name="subscriber_id" value="<?php echo $subscriber['id']; ?>">
                                                    <input type="hidden" name="new_status" value="active">
                                                    <button type="submit" class="dropdown-item text-success">
                                                        <i class="fas fa-play me-2"></i>Ativar
                                                    </button>
                                                </form>
                                            </li>
                                            <?php endif; ?>
                                            <?php if ($subscriber['status'] !== 'inactive'): ?>
                                            <li>
                                                <form method="POST" style="display: inline;">
                                                    <input type="hidden" name="action" value="update_status">
                                                    <input type="hidden" name="subscriber_id" value="<?php echo $subscriber['id']; ?>">
                                                    <input type="hidden" name="new_status" value="inactive">
                                                    <button type="submit" class="dropdown-item text-warning">
                                                        <i class="fas fa-pause me-2"></i>Inativar
                                                    </button>
                                                </form>
                                            </li>
                                            <?php endif; ?>
                                            <li><hr class="dropdown-divider"></li>
                                            <li>
                                                <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja excluir este inscrito?')">
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="subscriber_id" value="<?php echo $subscriber['id']; ?>">
                                                    <button type="submit" class="dropdown-item text-danger">
                                                        <i class="fas fa-trash me-2"></i>Excluir
                                                    </button>
                                                </form>
                                            </li>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </form>
            <?php endif; ?>
        </div>
        
        <!-- Paginação -->
        <?php if ($totalPages > 1): ?>
        <div class="card-footer">
            <nav aria-label="Navegação de páginas">
                <ul class="pagination justify-content-center mb-0">
                    <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&source=<?php echo urlencode($source); ?>&order=<?php echo urlencode($orderBy); ?>&dir=<?php echo urlencode($orderDir); ?>">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                    
                    <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                    <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&source=<?php echo urlencode($source); ?>&order=<?php echo urlencode($orderBy); ?>&dir=<?php echo urlencode($orderDir); ?>">
                            <?php echo $i; ?>
                        </a>
                    </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $totalPages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&source=<?php echo urlencode($source); ?>&order=<?php echo urlencode($orderBy); ?>&dir=<?php echo urlencode($orderDir); ?>">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Modal para adicionar inscrito -->
<div class="modal fade" id="addSubscriberModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Adicionar Inscrito</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="/newsletter/subscribe" method="POST">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="add_email" class="form-label">Email <span class="text-danger">*</span></label>
                        <input type="email" class="form-control" id="add_email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="add_name" class="form-label">Nome</label>
                        <input type="text" class="form-control" id="add_name" name="name">
                    </div>
                    <input type="hidden" name="source" value="admin_panel">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Adicionar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal para editar inscrito -->
<div class="modal fade" id="editSubscriberModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Editar Inscrito</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" name="subscriber_id" id="edit_subscriber_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" id="edit_email" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nome</label>
                        <input type="text" class="form-control" id="edit_name" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="edit_status" class="form-label">Status</label>
                        <select class="form-select" id="edit_status" name="new_status">
                            <option value="active">Ativo</option>
                            <option value="inactive">Inativo</option>
                            <option value="unsubscribed">Descadastrado</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Salvar</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Seleção em massa
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.subscriber-checkbox');
    const bulkDeleteBtn = document.getElementById('bulkDeleteBtn');
    
    selectAll.addEventListener('change', function() {
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateBulkDeleteButton();
    });
    
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateBulkDeleteButton);
    });
    
    function updateBulkDeleteButton() {
        const selected = document.querySelectorAll('.subscriber-checkbox:checked');
        bulkDeleteBtn.disabled = selected.length === 0;
    }
    
    // Confirmar exclusão em massa
    bulkDeleteBtn.addEventListener('click', function() {
        const selected = document.querySelectorAll('.subscriber-checkbox:checked');
        if (selected.length > 0 && confirm(`Tem certeza que deseja excluir ${selected.length} inscrito(s)?`)) {
            document.getElementById('bulkForm').submit();
        }
    });
    
    // Modal de edição
    const editModal = document.getElementById('editSubscriberModal');
    editModal.addEventListener('show.bs.modal', function(event) {
        const button = event.relatedTarget;
        const id = button.getAttribute('data-id');
        const email = button.getAttribute('data-email');
        const name = button.getAttribute('data-name');
        const status = button.getAttribute('data-status');
        
        document.getElementById('edit_subscriber_id').value = id;
        document.getElementById('edit_email').value = email;
        document.getElementById('edit_name').value = name;
        document.getElementById('edit_status').value = status;
    });
});
</script>

<?php require_once 'inc/footer.php'; ?>