<?php
/**
 * Página de Notificações - MontaLoja
 * Lista completa de todas as notificações da loja
 */
require_once __DIR__ . '/../includes/config.php';

if (!isset($_SESSION['user_id']) || !isset($_SESSION['store_id'])) {
    header('Location: /pages/login.php');
    exit;
}

$pdo = getDB();
$storeId = $_SESSION['store_id'];

// Buscar dados do usuário e loja
$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$_SESSION['user_id']]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT s.*, p.name as plan_name FROM stores s LEFT JOIN plans p ON s.plan_id = p.id WHERE s.id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Paginação
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filtro
$filter = $_GET['filter'] ?? 'all';
$whereClause = "store_id = ?";
$params = [$storeId];

if ($filter === 'unread') {
    $whereClause .= " AND is_read = 0";
} elseif ($filter === 'read') {
    $whereClause .= " AND is_read = 1";
}

// Contar total
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE $whereClause");
$countStmt->execute($params);
$totalNotifications = $countStmt->fetchColumn();
$totalPages = ceil($totalNotifications / $perPage);

// Buscar notificações
$stmt = $pdo->prepare("
    SELECT * FROM notifications 
    WHERE $whereClause 
    ORDER BY created_at DESC 
    LIMIT ? OFFSET ?
");
$params[] = $perPage;
$params[] = $offset;
$stmt->execute($params);
$notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Contar não lidas
$unreadStmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE store_id = ? AND is_read = 0");
$unreadStmt->execute([$storeId]);
$unreadCount = $unreadStmt->fetchColumn();

$pageTitle = 'Notificações';
include __DIR__ . '/../includes/dashboard-header.php';

// Função para tempo relativo
function notifTimeAgo($datetime) {
    $time = strtotime($datetime);
    $diff = time() - $time;
    if ($diff < 60) return 'Agora';
    if ($diff < 3600) return floor($diff / 60) . ' min atrás';
    if ($diff < 86400) return floor($diff / 3600) . 'h atrás';
    if ($diff < 604800) return floor($diff / 86400) . ' dias atrás';
    return date('d/m/Y H:i', $time);
}
?>

<style>
.notifications-page {
    max-width: 800px;
    margin: 0 auto;
}

.notifications-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.notifications-filters {
    display: flex;
    gap: 0.5rem;
    flex-wrap: wrap;
}

.filter-btn {
    padding: 0.5rem 1rem;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 8px;
    color: var(--text-secondary);
    font-size: 0.85rem;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.filter-btn:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.filter-btn.active {
    background: var(--primary);
    border-color: var(--primary);
    color: #000;
}

.notifications-actions {
    display: flex;
    gap: 0.5rem;
}

.action-btn {
    padding: 0.5rem 1rem;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 8px;
    color: var(--text-secondary);
    font-size: 0.85rem;
    cursor: pointer;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.action-btn:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.action-btn.danger:hover {
    border-color: var(--error);
    color: var(--error);
}

.notification-card {
    display: flex;
    gap: 1rem;
    padding: 1rem 1.25rem;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 12px;
    margin-bottom: 0.75rem;
    transition: all 0.2s;
    text-decoration: none;
    color: inherit;
    cursor: pointer;
}

.notification-card:hover {
    border-color: var(--primary);
    transform: translateX(4px);
}

.notification-card.unread {
    background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.1) 0%, var(--bg-card) 100%);
    border-left: 3px solid var(--primary);
}

.notification-card .icon-wrapper {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.notification-card .icon-wrapper.order { background: rgba(34, 197, 94, 0.15); color: #22C55E; }
.notification-card .icon-wrapper.stock { background: rgba(245, 158, 11, 0.15); color: #F59E0B; }
.notification-card .icon-wrapper.payment { background: rgba(59, 130, 246, 0.15); color: #3B82F6; }
.notification-card .icon-wrapper.system { background: rgba(168, 85, 247, 0.15); color: #A855F7; }
.notification-card .icon-wrapper.info { background: var(--primary-light); color: var(--primary); }

.notification-card .icon-wrapper.has-image {
    background: transparent;
    padding: 0;
    overflow: hidden;
}

.notification-card .icon-wrapper.has-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 12px;
}

.notification-card .content {
    flex: 1;
    min-width: 0;
}

.notification-card .title {
    font-weight: 600;
    font-size: 0.95rem;
    margin-bottom: 4px;
    color: var(--text-primary);
}

.notification-card .message {
    font-size: 0.85rem;
    color: var(--text-secondary);
    margin-bottom: 6px;
    line-height: 1.4;
}

.notification-card .meta {
    display: flex;
    align-items: center;
    gap: 1rem;
    font-size: 0.75rem;
    color: var(--text-muted);
}

.notification-card .actions {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
    flex-shrink: 0;
}

.notification-card .card-action-btn {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    border: 1px solid var(--border);
    background: var(--bg-darker);
    color: var(--text-muted);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.notification-card .card-action-btn:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.notification-card .card-action-btn.delete:hover {
    border-color: var(--error);
    color: var(--error);
}

.empty-notifications {
    text-align: center;
    padding: 4rem 2rem;
    color: var(--text-muted);
}

.empty-notifications iconify-icon {
    font-size: 4rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.empty-notifications h3 {
    font-size: 1.25rem;
    margin-bottom: 0.5rem;
    color: var(--text-secondary);
}

.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 0.5rem;
    margin-top: 2rem;
    flex-wrap: wrap;
}

.pagination a, .pagination span {
    padding: 0.5rem 1rem;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 8px;
    color: var(--text-secondary);
    text-decoration: none;
    font-size: 0.85rem;
    transition: all 0.2s;
}

.pagination a:hover {
    border-color: var(--primary);
    color: var(--primary);
}

.pagination .current {
    background: var(--primary);
    border-color: var(--primary);
    color: #000;
}

.pagination .disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

@media (max-width: 640px) {
    .notifications-toolbar {
        flex-direction: column;
        align-items: stretch;
    }
    
    .notifications-filters {
        justify-content: center;
    }
    
    .notifications-actions {
        justify-content: center;
    }
    
    .notification-card {
        flex-wrap: wrap;
    }
    
    .notification-card .actions {
        flex-direction: row;
        width: 100%;
        justify-content: flex-end;
        padding-top: 0.5rem;
        border-top: 1px solid var(--border);
        margin-top: 0.5rem;
    }
}
</style>

<main class="main-content">
    <div class="page-header">
        <h1>
            <iconify-icon icon="solar:bell-bold"></iconify-icon>
            Notificações
        </h1>
        <p>Gerencie todas as suas notificações</p>
    </div>

    <div class="notifications-page">
        <div class="notifications-toolbar">
            <div class="notifications-filters">
                <a href="?filter=all" class="filter-btn <?php echo $filter === 'all' ? 'active' : ''; ?>">
                    <iconify-icon icon="solar:list-bold"></iconify-icon>
                    Todas (<?php echo $totalNotifications; ?>)
                </a>
                <a href="?filter=unread" class="filter-btn <?php echo $filter === 'unread' ? 'active' : ''; ?>">
                    <iconify-icon icon="solar:bell-bing-bold"></iconify-icon>
                    Não lidas (<?php echo $unreadCount; ?>)
                </a>
                <a href="?filter=read" class="filter-btn <?php echo $filter === 'read' ? 'active' : ''; ?>">
                    <iconify-icon icon="solar:check-read-bold"></iconify-icon>
                    Lidas
                </a>
            </div>
            
            <div class="notifications-actions">
                <?php if ($unreadCount > 0): ?>
                <button class="action-btn" onclick="markAllReadPage()">
                    <iconify-icon icon="solar:check-read-bold"></iconify-icon>
                    Marcar todas como lidas
                </button>
                <?php endif; ?>
                <?php if ($totalNotifications > 0): ?>
                <button class="action-btn danger" onclick="clearAllNotificationsPage()">
                    <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                    Limpar todas
                </button>
                <?php endif; ?>
            </div>
        </div>

        <?php if (empty($notifications)): ?>
        <div class="empty-notifications card">
            <iconify-icon icon="solar:bell-off-bold"></iconify-icon>
            <h3>Nenhuma notificação</h3>
            <p>Você não tem notificações <?php echo $filter !== 'all' ? 'nesta categoria' : ''; ?></p>
        </div>
        <?php else: ?>
            <?php foreach ($notifications as $notif): ?>
            <div class="notification-card <?php echo $notif['is_read'] ? '' : 'unread'; ?>" 
                 data-id="<?php echo $notif['id']; ?>"
                 onclick="handleNotificationClick(event, <?php echo $notif['id']; ?>, '<?php echo htmlspecialchars($notif['link'] ?? '', ENT_QUOTES); ?>')">
                
                <?php if (!empty($notif['image_url'])): ?>
                <div class="icon-wrapper has-image">
                    <img src="<?php echo htmlspecialchars($notif['image_url']); ?>" alt="">
                </div>
                <?php else: ?>
                <div class="icon-wrapper <?php echo htmlspecialchars($notif['type'] ?? 'info'); ?>">
                    <iconify-icon icon="<?php echo htmlspecialchars($notif['icon'] ?? 'solar:bell-bold'); ?>" width="24"></iconify-icon>
                </div>
                <?php endif; ?>
                
                <div class="content">
                    <div class="title"><?php echo htmlspecialchars($notif['title']); ?></div>
                    <div class="message"><?php echo htmlspecialchars($notif['message']); ?></div>
                    <div class="meta">
                        <span>
                            <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                            <?php echo notifTimeAgo($notif['created_at']); ?>
                        </span>
                        <?php if ($notif['is_read']): ?>
                        <span>
                            <iconify-icon icon="solar:check-read-bold"></iconify-icon>
                            Lida
                        </span>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="actions">
                    <?php if (!$notif['is_read']): ?>
                    <button class="card-action-btn" onclick="event.stopPropagation(); markSingleRead(<?php echo $notif['id']; ?>)" title="Marcar como lida">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    </button>
                    <?php endif; ?>
                    <button class="card-action-btn delete" onclick="event.stopPropagation(); deleteSingleNotification(<?php echo $notif['id']; ?>)" title="Excluir">
                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                    </button>
                </div>
            </div>
            <?php endforeach; ?>

            <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                <a href="?filter=<?php echo $filter; ?>&page=<?php echo $page - 1; ?>">
                    <iconify-icon icon="solar:alt-arrow-left-bold"></iconify-icon> Anterior
                </a>
                <?php endif; ?>
                
                <?php
                $startPage = max(1, $page - 2);
                $endPage = min($totalPages, $page + 2);
                
                if ($startPage > 1) {
                    echo '<a href="?filter=' . $filter . '&page=1">1</a>';
                    if ($startPage > 2) echo '<span class="disabled">...</span>';
                }
                
                for ($i = $startPage; $i <= $endPage; $i++):
                ?>
                    <?php if ($i == $page): ?>
                    <span class="current"><?php echo $i; ?></span>
                    <?php else: ?>
                    <a href="?filter=<?php echo $filter; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                    <?php endif; ?>
                <?php endfor;
                
                if ($endPage < $totalPages) {
                    if ($endPage < $totalPages - 1) echo '<span class="disabled">...</span>';
                    echo '<a href="?filter=' . $filter . '&page=' . $totalPages . '">' . $totalPages . '</a>';
                }
                ?>
                
                <?php if ($page < $totalPages): ?>
                <a href="?filter=<?php echo $filter; ?>&page=<?php echo $page + 1; ?>">
                    Próxima <iconify-icon icon="solar:alt-arrow-right-bold"></iconify-icon>
                </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>
</main>

<script>
function handleNotificationClick(event, id, link) {
    // Marcar como lida
    fetch('/api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ action: 'mark_read', id: id })
    });
    
    // Navegar se tiver link
    if (link && link !== '#' && link !== '') {
        window.location.href = link;
    }
}

function markSingleRead(id) {
    fetch('/api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ action: 'mark_read', id: id })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const card = document.querySelector('.notification-card[data-id="' + id + '"]');
            if (card) {
                card.classList.remove('unread');
                const markBtn = card.querySelector('.card-action-btn:not(.delete)');
                if (markBtn) markBtn.remove();
            }
        }
    });
}

function deleteSingleNotification(id) {
    if (!confirm('Deseja excluir esta notificação?')) return;
    
    fetch('/api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ action: 'delete', id: id })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const card = document.querySelector('.notification-card[data-id="' + id + '"]');
            if (card) {
                card.style.opacity = '0';
                card.style.transform = 'translateX(-20px)';
                setTimeout(() => card.remove(), 300);
            }
        }
    });
}

function markAllReadPage() {
    fetch('/api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ action: 'mark_all_read' })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        }
    });
}

function clearAllNotificationsPage() {
    if (!confirm('Tem certeza que deseja limpar TODAS as notificações? Esta ação não pode ser desfeita.')) return;
    
    fetch('/api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ action: 'clear_all' })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        }
    });
}
</script>

<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
