<?php
/**
 * Admin Subscribers Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Subscribers';

// Handle delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM subscribers WHERE id = ?");
        $stmt->execute([$id]);
        set_flash_message('Subscriber removed successfully!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to remove subscriber.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle toggle status
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    try {
        $stmt = $pdo->prepare("UPDATE subscribers SET is_active = NOT is_active WHERE id = ?");
        $stmt->execute([$id]);
        set_flash_message('Subscriber status updated!', 'success');
    } catch (PDOException $e) {
        set_flash_message('Failed to update status.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Pagination
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Get total count
$stmt = $pdo->query("SELECT COUNT(*) FROM subscribers");
$total_subscribers = $stmt->fetchColumn();
$total_pages = ceil($total_subscribers / $per_page);

// Get subscribers
$stmt = $pdo->prepare("SELECT * FROM subscribers ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->execute([$per_page, $offset]);
$subscribers = $stmt->fetchAll();

// Get stats
$stmt = $pdo->query("SELECT COUNT(*) as total, SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active FROM subscribers");
$stats = $stmt->fetch();

include __DIR__ . '/includes/header.php';
?>

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-envelope me-2"></i>Subscribers</h1>
        <div>
            <span class="badge bg-primary me-2">Total: <?php echo number_format($stats['total']); ?></span>
            <span class="badge bg-success">Active: <?php echo number_format($stats['active']); ?></span>
        </div>
    </div>
    
    <!-- Subscribers Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Email</th>
                            <th>Name</th>
                            <th>Source</th>
                            <th>Status</th>
                            <th>Subscribed</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($subscribers as $subscriber): ?>
                        <tr>
                            <td><strong><?php echo sanitize($subscriber['email']); ?></strong></td>
                            <td><?php echo sanitize($subscriber['name'] ?? '-'); ?></td>
                            <td><span class="badge bg-secondary"><?php echo $subscriber['source']; ?></span></td>
                            <td>
                                <a href="?toggle=<?php echo $subscriber['id']; ?>" class="badge bg-<?php echo $subscriber['is_active'] ? 'success' : 'secondary'; ?> text-decoration-none">
                                    <?php echo $subscriber['is_active'] ? 'Active' : 'Inactive'; ?>
                                </a>
                            </td>
                            <td><?php echo format_date($subscriber['created_at']); ?></td>
                            <td>
                                <a href="?delete=<?php echo $subscriber['id']; ?>" class="btn btn-sm btn-danger confirm-delete" title="Remove">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="card-footer">
            <nav>
                <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; ?>">
                            <i class="fas fa-chevron-left"></i>
                        </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 $i; ?></a>
                    </li>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?php echo $page + 1; ?>">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

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