<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/activity.php';

require_admin();

$pageTitle = 'Newsletter Subscribers';
$success = '';
$error = '';

if (isset($_GET['updated'])) {
    $success = 'Subscriber updated successfully.';
}

if (isset($_GET['deleted'])) {
    $success = 'Subscriber deleted successfully.';
}

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    $subscribers = $pdo->query("
        SELECT email, first_name, source, discount_code, status, subscribed_at
        FROM newsletter_subscribers
        ORDER BY subscribed_at DESC
    ")->fetchAll();

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="newsletter-subscribers-' . date('Y-m-d') . '.csv"');

    $output = fopen('php://output', 'w');

    fputcsv($output, [
        'Email',
        'First Name',
        'Source',
        'Discount Code',
        'Status',
        'Subscribed At'
    ]);

    foreach ($subscribers as $subscriber) {
        fputcsv($output, [
            $subscriber['email'],
            $subscriber['first_name'],
            $subscriber['source'],
            $subscriber['discount_code'],
            $subscriber['status'],
            $subscriber['subscribed_at']
        ]);
    }

    fclose($output);
    exit;
}

if (isset($_GET['toggle'])) {
    $subscriberId = (int) $_GET['toggle'];

    $stmt = $pdo->prepare("SELECT * FROM newsletter_subscribers WHERE id = ? LIMIT 1");
    $stmt->execute([$subscriberId]);
    $subscriber = $stmt->fetch();

    if ($subscriber) {
        $newStatus = $subscriber['status'] === 'subscribed' ? 'unsubscribed' : 'subscribed';

        $stmt = $pdo->prepare("
            UPDATE newsletter_subscribers
            SET status = ?
            WHERE id = ?
        ");
        $stmt->execute([$newStatus, $subscriberId]);

        log_admin_activity(
            'newsletter_status_updated',
            'Newsletter subscriber status updated: ' . $subscriber['email'] .
            ' | ' . $subscriber['status'] . ' → ' . $newStatus
        );
    }

    redirect(ADMIN_URL . '/newsletter-subscribers.php?updated=1');
}

if (isset($_GET['delete'])) {
    $subscriberId = (int) $_GET['delete'];

    $stmt = $pdo->prepare("SELECT * FROM newsletter_subscribers WHERE id = ? LIMIT 1");
    $stmt->execute([$subscriberId]);
    $subscriber = $stmt->fetch();

    if ($subscriber) {
        $stmt = $pdo->prepare("DELETE FROM newsletter_subscribers WHERE id = ?");
        $stmt->execute([$subscriberId]);

        log_admin_activity(
            'newsletter_subscriber_deleted',
            'Newsletter subscriber deleted: ' . $subscriber['email']
        );
    }

    redirect(ADMIN_URL . '/newsletter-subscribers.php?deleted=1');
}

$statusFilter = $_GET['status'] ?? '';
$search = trim($_GET['search'] ?? '');

$where = [];
$params = [];

if ($statusFilter !== '' && in_array($statusFilter, ['subscribed', 'unsubscribed'], true)) {
    $where[] = "status = ?";
    $params[] = $statusFilter;
}

if ($search !== '') {
    $where[] = "(email LIKE ? OR first_name LIKE ? OR source LIKE ? OR discount_code LIKE ?)";
    $searchTerm = '%' . $search . '%';
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$stmt = $pdo->prepare("
    SELECT *
    FROM newsletter_subscribers
    $whereSql
    ORDER BY subscribed_at DESC, id DESC
");
$stmt->execute($params);
$subscribers = $stmt->fetchAll();

$totalSubscribers = (int) $pdo->query("SELECT COUNT(*) FROM newsletter_subscribers")->fetchColumn();
$activeSubscribers = (int) $pdo->query("SELECT COUNT(*) FROM newsletter_subscribers WHERE status = 'subscribed'")->fetchColumn();
$unsubscribedSubscribers = (int) $pdo->query("SELECT COUNT(*) FROM newsletter_subscribers WHERE status = 'unsubscribed'")->fetchColumn();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Newsletter Subscribers</h1>
            <div class="admin-user">Manage newsletter leads, subscriber status, and marketing exports.</div>
        </div>

        <a href="<?= e(ADMIN_URL); ?>/newsletter-subscribers.php?export=csv" class="admin-btn">
            Export CSV
        </a>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-cards" style="margin-bottom:24px;">
        <div class="admin-card">
            <span>Total Subscribers</span>
            <strong><?= e($totalSubscribers); ?></strong>
        </div>

        <div class="admin-card">
            <span>Subscribed</span>
            <strong><?= e($activeSubscribers); ?></strong>
        </div>

        <div class="admin-card">
            <span>Unsubscribed</span>
            <strong><?= e($unsubscribedSubscribers); ?></strong>
        </div>
    </section>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2>Filter Subscribers</h2>

        <form method="GET" class="admin-form-grid">
            <div class="admin-field">
                <label>Search</label>
                <input
                    type="text"
                    name="search"
                    value="<?= e($search); ?>"
                    placeholder="Search email, name, source, discount code"
                >
            </div>

            <div class="admin-field">
                <label>Status</label>
                <select name="status">
                    <option value="">All Statuses</option>
                    <option value="subscribed" <?= $statusFilter === 'subscribed' ? 'selected' : ''; ?>>Subscribed</option>
                    <option value="unsubscribed" <?= $statusFilter === 'unsubscribed' ? 'selected' : ''; ?>>Unsubscribed</option>
                </select>
            </div>

            <div class="admin-field" style="align-self:end;">
                <button type="submit" class="admin-btn">Filter</button>
                <a href="<?= e(ADMIN_URL); ?>/newsletter-subscribers.php" class="admin-btn admin-btn-light">Reset</a>
            </div>
        </form>
    </section>

    <section class="admin-panel">
        <h2>All Newsletter Subscribers</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Email</th>
                    <th>First Name</th>
                    <th>Source</th>
                    <th>Discount Code</th>
                    <th>Status</th>
                    <th>Subscribed At</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$subscribers): ?>
                    <tr>
                        <td colspan="7">No subscribers found.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($subscribers as $subscriber): ?>
                    <tr>
                        <td><strong><?= e($subscriber['email']); ?></strong></td>

                        <td><?= e($subscriber['first_name'] ?? '-'); ?></td>

                        <td><?= e($subscriber['source'] ?? '-'); ?></td>

                        <td><?= e($subscriber['discount_code'] ?? '-'); ?></td>

                        <td>
                            <strong><?= e(ucfirst($subscriber['status'])); ?></strong>
                        </td>

                        <td>
                            <?= !empty($subscriber['subscribed_at'])
                                ? e(date('d M Y, h:i A', strtotime($subscriber['subscribed_at'])))
                                : '-'; ?>
                        </td>

                        <td>
                            <a
                                class="admin-btn admin-btn-light"
                                href="<?= e(ADMIN_URL); ?>/newsletter-subscribers.php?toggle=<?= e($subscriber['id']); ?>"
                                onclick="return confirm('Change subscriber status?');"
                            >
                                <?= $subscriber['status'] === 'subscribed' ? 'Unsubscribe' : 'Subscribe'; ?>
                            </a>

                            <a
                                class="admin-btn"
                                href="<?= e(ADMIN_URL); ?>/newsletter-subscribers.php?delete=<?= e($subscriber['id']); ?>"
                                onclick="return confirm('Delete this subscriber?');"
                            >
                                Delete
                            </a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

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