<?php
/**
 * Admin - Newsletter Subscribers
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Newsletter Subscribers';

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        redirect(BASE_URL . 'admin/newsletter-subscribers.php', 'error', 'Invalid security token');
    }
    
    $ids = $_POST['selected_ids'] ?? [];
    $action = $_POST['bulk_action'];
    
    if (!empty($ids)) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        try {
            if ($action === 'delete') {
                $stmt = db()->prepare("DELETE FROM newsletter_subscribers WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/newsletter-subscribers.php', 'success', count($ids) . ' subscribers deleted');
            } elseif ($action === 'activate') {
                $stmt = db()->prepare("UPDATE newsletter_subscribers SET status = 'active' WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/newsletter-subscribers.php', 'success', count($ids) . ' subscribers activated');
            } elseif ($action === 'deactivate') {
                $stmt = db()->prepare("UPDATE newsletter_subscribers SET status = 'unsubscribed' WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                redirect(BASE_URL . 'admin/newsletter-subscribers.php', 'success', count($ids) . ' subscribers deactivated');
            } elseif ($action === 'export') {
                $stmt = db()->prepare("SELECT * FROM newsletter_subscribers WHERE id IN ($placeholders)");
                $stmt->execute($ids);
                $subscribers = $stmt->fetchAll();
                
                $data = array_map(fn($s) => [$s['email'], $s['name'], $s['status'], $s['created_at']], $subscribers);
                export_to_csv($data, ['Email', 'Name', 'Status', 'Subscribed At'], 'newsletter-subscribers-' . date('Y-m-d') . '.csv');
            }
        } catch (PDOException $e) {
            redirect(BASE_URL . 'admin/newsletter-subscribers.php', 'error', 'Action failed');
        }
    }
}

// Get subscribers with search/filter
$subscribers = [];
$search = sanitize($_GET['search'] ?? '');
$status = sanitize($_GET['status'] ?? '');
$conditions = [];
$params = [];

if ($search) {
    $conditions[] = '(email LIKE ? OR name LIKE ?)';
    $params[] = '%' . $search . '%';
    $params[] = '%' . $search . '%';
}
if ($status) {
    $conditions[] = 'status = ?';
    $params[] = $status;
}

$sql = "SELECT * FROM newsletter_subscribers";
if ($conditions) {
    $sql .= " WHERE " . implode(' AND ', $conditions);
}
$sql .= " ORDER BY created_at DESC";

try {
    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $subscribers = $stmt->fetchAll();
} catch (PDOException $e) {}

// Get stats
$stats = [];
try {
    $stmt = db()->query("SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN status = 'unsubscribed' THEN 1 ELSE 0 END) as unsubscribed,
        SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today
        FROM newsletter_subscribers");
    $stats = $stmt->fetch();
} catch (PDOException $e) {}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Newsletter Subscribers</h2>
    <a href="newsletter-send.php" class="btn btn-primary"><i class="bi bi-send me-2"></i>Send Newsletter</a>
</div>

<!-- Stats -->
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="card border-0 bg-primary text-white">
            <div class="card-body">
                <h4 class="mb-0"><?php echo $stats['total'] ?? 0; ?></h4>
                <small>Total Subscribers</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 bg-success text-white">
            <div class="card-body">
                <h4 class="mb-0"><?php echo $stats['active'] ?? 0; ?></h4>
                <small>Active</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 bg-warning text-white">
            <div class="card-body">
                <h4 class="mb-0"><?php echo $stats['unsubscribed'] ?? 0; ?></h4>
                <small>Unsubscribed</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 bg-info text-white">
            <div class="card-body">
                <h4 class="mb-0"><?php echo $stats['today'] ?? 0; ?></h4>
                <small>New Today</small>
            </div>
        </div>
    </div>
</div>

<form method="GET" class="row g-3 mb-4">
    <div class="col-md-4">
        <input type="text" name="search" class="form-control" placeholder="Search by email or name..." value="<?php echo $search; ?>">
    </div>
    <div class="col-md-3">
        <select name="status" class="form-select">
            <option value="">All Status</option>
            <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
            <option value="unsubscribed" <?php echo $status === 'unsubscribed' ? 'selected' : ''; ?>>Unsubscribed</option>
            <option value="bounced" <?php echo $status === 'bounced' ? 'selected' : ''; ?>>Bounced</option>
        </select>
    </div>
    <div class="col-md-2">
        <button type="submit" class="btn btn-outline-primary w-100"><i class="bi bi-search"></i></button>
    </div>
    <div class="col-md-2">
        <a href="newsletter-subscribers.php" class="btn btn-outline-secondary w-100">Clear</a>
    </div>
</form>

<form method="POST">
    <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
    
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <span class="fw-bold">Subscribers</span>
            <div class="d-flex gap-2">
                <select name="bulk_action" class="form-select form-select-sm" style="width: auto;">
                    <option value="">Bulk Actions</option>
                    <option value="activate">Activate</option>
                    <option value="deactivate">Deactivate</option>
                    <option value="delete">Delete</option>
                    <option value="export">Export CSV</option>
                </select>
                <button type="submit" class="btn btn-sm btn-outline-secondary">Apply</button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th><input type="checkbox" class="form-check-input" id="selectAll"></th>
                        <th>Email</th>
                        <th>Name</th>
                        <th>Status</th>
                        <th>Source</th>
                        <th>Subscribed</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($subscribers as $sub): ?>
                    <tr>
                        <td><input type="checkbox" name="selected_ids[]" value="<?php echo $sub['id']; ?>" class="form-check-input row-checkbox"></td>
                        <td><?php echo $sub['email']; ?></td>
                        <td><?php echo $sub['name'] ?? '-'; ?></td>
                        <td>
                            <span class="badge bg-<?php 
                                echo $sub['status'] === 'active' ? 'success' : 
                                     ($sub['status'] === 'unsubscribed' ? 'secondary' : 'danger'); 
                            ?>">
                                <?php echo ucfirst($sub['status']); ?>
                            </span>
                        </td>
                        <td><?php echo $sub['source']; ?></td>
                        <td><?php echo date('d M Y', strtotime($sub['created_at'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($subscribers)): ?>
                    <tr><td colspan="6" class="text-center py-4 text-muted">No subscribers found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</form>

<script>
document.getElementById('selectAll').addEventListener('change', function() {
    document.querySelectorAll('.row-checkbox').forEach(cb => cb.checked = this.checked);
});
</script>

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