<?php
/**
 * Admin Notifications - COMPLETE FIXED VERSION
 * Digital Product Store
 */

require_once __DIR__ . '/includes/header.php';

$page_title = 'Notifications';

// Handle mark as read
if (isset($_GET['action']) && $_GET['action'] === 'mark_read' && isset($_GET['id'])) {
    $notification_id = intval($_GET['id']);
    $stmt = $pdo->prepare("UPDATE admin_notifications SET is_read = 1 WHERE id = ?");
    $stmt->execute([$notification_id]);
    
    // Redirect to the link if provided
    if (isset($_GET['redirect']) && !empty($_GET['redirect'])) {
        header('Location: ' . ADMIN_URL . '/' . $_GET['redirect']);
        exit;
    }
    
    set_flash_message('Notification marked as read', 'success');
    header('Location: ' . ADMIN_URL . '/notifications.php');
    exit;
}

// Handle mark all as read
if (isset($_GET['action']) && $_GET['action'] === 'mark_all_read') {
    $pdo->query("UPDATE admin_notifications SET is_read = 1");
    set_flash_message('All notifications marked as read', 'success');
    header('Location: ' . ADMIN_URL . '/notifications.php');
    exit;
}

// Handle delete
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    if (verify_csrf_token($_GET['csrf_token'] ?? '')) {
        $notification_id = intval($_GET['id']);
        $stmt = $pdo->prepare("DELETE FROM admin_notifications WHERE id = ?");
        $stmt->execute([$notification_id]);
        set_flash_message('Notification deleted', 'success');
    } else {
        set_flash_message('Invalid request', 'error');
    }
    header('Location: ' . ADMIN_URL . '/notifications.php');
    exit;
}

$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filter by read status
$filter = isset($_GET['filter']) ? sanitize($_GET['filter']) : '';
$where_clause = '';
$params = [];

if ($filter === 'unread') {
    $where_clause = "WHERE is_read = 0";
} elseif ($filter === 'read') {
    $where_clause = "WHERE is_read = 1";
}

// Get total count
$count_sql = "SELECT COUNT(*) FROM admin_notifications $where_clause";
$stmt = $pdo->prepare($count_sql);
$stmt->execute($params);
$total_notifications = $stmt->fetchColumn();
$total_pages = ceil($total_notifications / $per_page);

// Get notifications
$sql = "
    SELECT * FROM admin_notifications
    $where_clause
    ORDER BY created_at DESC
    LIMIT ? OFFSET ?
";

$stmt = $pdo->prepare($sql);
$param_index = 1;
foreach ($params as $param) {
    $stmt->bindValue($param_index++, $param);
}
$stmt->bindValue($param_index++, $per_page, PDO::PARAM_INT);
$stmt->bindValue($param_index, $offset, PDO::PARAM_INT);
$stmt->execute();
$notifications = $stmt->fetchAll();

// Get counts
$unread_count = $pdo->query("SELECT COUNT(*) FROM admin_notifications WHERE is_read = 0")->fetchColumn();
$read_count = $pdo->query("SELECT COUNT(*) FROM admin_notifications WHERE is_read = 1")->fetchColumn();
?>

<div class="page-header">
    <div>
        <h1>Notifications</h1>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo ADMIN_URL; ?>/index.php">Dashboard</a></li>
                <li class="breadcrumb-item active">Notifications</li>
            </ol>
        </nav>
    </div>
    <?php if ($unread_count > 0): ?>
        <a href="<?php echo ADMIN_URL; ?>/notifications.php?action=mark_all_read" class="btn btn-primary">
            <i class="fas fa-check-double me-2"></i>Mark All as Read
        </a>
    <?php endif; ?>
</div>

<!-- Filter Tabs -->
<div class="card mb-4">
    <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs">
            <li class="nav-item">
                <a class="nav-link <?php echo !$filter ? 'active' : ''; ?>" 
                   href="<?php echo ADMIN_URL; ?>/notifications.php">All (<?php echo $total_notifications; ?>)</a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $filter === 'unread' ? 'active' : ''; ?>" 
                   href="<?php echo ADMIN_URL; ?>/notifications.php?filter=unread">
                    Unread <?php if ($unread_count > 0): ?><span class="badge bg-danger ms-1"><?php echo $unread_count; ?></span><?php endif; ?>
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $filter === 'read' ? 'active' : ''; ?>" 
                   href="<?php echo ADMIN_URL; ?>/notifications.php?filter=read">Read (<?php echo $read_count; ?>)</a>
            </li>
        </ul>
    </div>
    <div class="card-body p-0">
        <div class="list-group list-group-flush">
            <?php if (empty($notifications)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-bell-slash fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No notifications found</p>
                </div>
            <?php else: ?>
                <?php foreach ($notifications as $notification): ?>
                    <div class="list-group-item list-group-item-action d-flex align-items-start py-3 <?php echo $notification['is_read'] ? '' : 'bg-light'; ?>">
                        <div class="flex-shrink-0 me-3">
                            <div class="rounded-circle d-flex align-items-center justify-content-center" 
                                 style="width: 45px; height: 45px; background: <?php 
                                     echo $notification['type'] == 'order' ? 'rgba(28, 200, 138, 0.1)' : 
                                         ($notification['type'] == 'negotiation' ? 'rgba(246, 194, 62, 0.1)' : 
                                         ($notification['type'] == 'review' ? 'rgba(54, 185, 204, 0.1)' : 'rgba(78, 115, 223, 0.1)')); 
                                 ?>;">
                                <i class="fas fa-<?php 
                                    echo $notification['type'] == 'order' ? 'shopping-cart text-success' : 
                                        ($notification['type'] == 'negotiation' ? 'handshake text-warning' : 
                                        ($notification['type'] == 'review' ? 'star text-info' : 'user text-primary')); 
                                ?>"></i>
                            </div>
                        </div>
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h6 class="mb-1 <?php echo $notification['is_read'] ? '' : 'fw-bold'; ?>">
                                        <?php echo htmlspecialchars($notification['title']); ?>
                                        <?php if (!$notification['is_read']): ?>
                                            <span class="badge bg-danger ms-2" style="font-size: 0.6rem;">NEW</span>
                                        <?php endif; ?>
                                    </h6>
                                    <p class="mb-1 text-muted"><?php echo htmlspecialchars($notification['message']); ?></p>
                                    <small class="text-muted">
                                        <i class="far fa-clock me-1"></i><?php echo time_ago($notification['created_at']); ?>
                                    </small>
                                </div>
                                <div class="btn-group">
                                    <?php if (!$notification['is_read']): ?>
                                        <a href="<?php echo ADMIN_URL; ?>/notifications.php?action=mark_read&id=<?php echo $notification['id']; ?>&redirect=<?php echo urlencode($notification['link'] ?? ''); ?>" 
                                           class="btn btn-sm btn-outline-primary" title="Mark as Read">
                                            <i class="fas fa-check"></i>
                                        </a>
                                    <?php endif; ?>
                                    <?php if ($notification['link']): ?>
                                        <a href="<?php echo ADMIN_URL; ?>/<?php echo $notification['link']; ?>" 
                                           class="btn btn-sm btn-outline-info" title="View">
                                            <i class="fas fa-external-link-alt"></i>
                                        </a>
                                    <?php endif; ?>
                                    <a href="<?php echo ADMIN_URL; ?>/notifications.php?action=delete&id=<?php echo $notification['id']; ?>&csrf_token=<?php echo generate_csrf_token(); ?>" 
                                       class="btn btn-sm btn-outline-danger" 
                                       onclick="return confirm('Are you sure you want to delete this notification?')"
                                       title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Pagination -->
<?php if ($total_pages > 1): ?>
    <nav aria-label="Notifications pagination">
        <ul class="pagination justify-content-center">
            <?php if ($page > 1): ?>
                <li class="page-item">
                    <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo $filter ? '&filter=' . $filter : ''; ?>">Previous</a>
                </li>
            <?php endif; ?>
            
            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $i; ?><?php echo $filter ? '&filter=' . $filter : ''; ?>"><?php echo $i; ?></a>
                </li>
            <?php endfor; ?>
            
            <?php if ($page < $total_pages): ?>
                <li class="page-item">
                    <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo $filter ? '&filter=' . $filter : ''; ?>">Next</a>
                </li>
            <?php endif; ?>
        </ul>
    </nav>
<?php endif; ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
