<?php
/**
 * Admin — Newsletter Subscribers Listing
 *
 * @var array $subscribers
 * @var array $counts
 * @var string $search
 * @var string $statusFilter
 * @var string $dbError
 * @var bool $tableExists
 * @var int $rawRowCount
 */
$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$csrf = htmlspecialchars($csrfToken ?? '', ENT_QUOTES, 'UTF-8');
$dbError = $dbError ?? '';
$tableExists = $tableExists ?? false;
$rawRowCount = $rawRowCount ?? 0;
$hasStudentIdCol = $hasStudentIdCol ?? false;
?>

<?php if (!empty($dbError)): ?>
<div class="admin-alert admin-alert-error" style="margin-bottom:1.5rem;">
    <strong>Database Error:</strong> <?= htmlspecialchars($dbError, ENT_QUOTES, 'UTF-8') ?>
</div>
<?php endif; ?>

<?php if (!$tableExists): ?>
<div class="admin-alert admin-alert-error" style="margin-bottom:1.5rem;">
    <strong>Table Missing!</strong> The <code>newsletter_subscribers</code> table does not exist in the database.
    Please run the migration SQL in phpMyAdmin. 
    <a href="#" onclick="document.getElementById('migrationSql').style.display='block';return false;" style="color:inherit;text-decoration:underline;">Show SQL</a>
    <pre id="migrationSql" style="display:none;background:#fff;padding:10px;border-radius:4px;font-size:0.75rem;overflow-x:auto;margin-top:0.5rem;border:1px solid #ddd;">CREATE TABLE IF NOT EXISTS `newsletter_subscribers` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `email` VARCHAR(255) NOT NULL,
    `name` VARCHAR(150) DEFAULT NULL,
    `student_id` INT UNSIGNED DEFAULT NULL,
    `status` ENUM('active','unsubscribed','bounced') NOT NULL DEFAULT 'active',
    `verification_token` VARCHAR(64) DEFAULT NULL,
    `is_verified` TINYINT(1) NOT NULL DEFAULT 1,
    `source` VARCHAR(50) DEFAULT 'homepage',
    `subscribed_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `unsubscribed_at` TIMESTAMP NULL DEFAULT NULL,
    `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_newsletter_email` (`email`),
    INDEX `idx_newsletter_status` (`status`, `subscribed_at`),
    INDEX `idx_student_id` (`student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;</pre>
</div>
<?php endif; ?>

<div class="admin-toolbar">
    <div class="admin-toolbar-left">
        <a href="<?= $bp ?>/admin/newsletter/compose" class="admin-btn admin-btn-primary">
            <svg class="admin-btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
            Send Newsletter
        </a>
        <a href="<?= $bp ?>/admin/newsletter/logs" class="admin-btn admin-btn-secondary">
            <svg class="admin-btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
            Email Logs
        </a>
    </div>
    <div class="admin-toolbar-right">
        <span class="admin-badge admin-badge-success">Active: <?= (int) ($counts['active'] ?? 0) ?></span>
        <span class="admin-badge admin-badge-secondary">Unsubscribed: <?= (int) ($counts['unsubscribed'] ?? 0) ?></span>
        <span class="admin-badge admin-badge-warning">Bounced: <?= (int) ($counts['bounced'] ?? 0) ?></span>
        <span class="admin-badge admin-badge-info">Total: <?= (int) ($counts['total'] ?? 0) ?></span>
    </div>
</div>

<!-- Search & Filter -->
<div class="admin-card" style="margin-bottom:1.5rem;">
    <div class="admin-card-body">
        <form method="GET" action="<?= $bp ?>/admin/newsletter" class="admin-filter-form" style="display:flex;gap:1rem;align-items:flex-end;flex-wrap:wrap;">
            <div class="admin-form-group" style="flex:1;min-width:200px;">
                <label for="search">Search Email / Name</label>
                <input type="text" id="search" name="search" value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>" placeholder="Search by email or name..." class="admin-form-control">
            </div>
            <div class="admin-form-group" style="min-width:150px;">
                <label for="status">Status</label>
                <select id="status" name="status" class="admin-form-control">
                    <option value="">All Status</option>
                    <option value="active" <?= $statusFilter === 'active' ? 'selected' : '' ?>>Active</option>
                    <option value="unsubscribed" <?= $statusFilter === 'unsubscribed' ? 'selected' : '' ?>>Unsubscribed</option>
                    <option value="bounced" <?= $statusFilter === 'bounced' ? 'selected' : '' ?>>Bounced</option>
                </select>
            </div>
            <button type="submit" class="admin-btn admin-btn-secondary">Filter</button>
            <?php if (!empty($search) || !empty($statusFilter)): ?>
            <a href="<?= $bp ?>/admin/newsletter" class="admin-btn admin-btn-outline">Clear</a>
            <?php endif; ?>
        </form>
    </div>
</div>

<!-- Debug Info (collapsible) -->
<div class="admin-card" style="margin-bottom:1.5rem;border-color:#9c27b0;">
    <div class="admin-card-header" style="background:#f3e5f5;cursor:pointer;" onclick="document.getElementById('debugSection').style.display = document.getElementById('debugSection').style.display === 'none' ? 'block' : 'none'">
        <h3 class="admin-card-title" style="color:#6a1b9a;">Debug Info (click to expand)</h3>
    </div>
    <div class="admin-card-body" id="debugSection" style="display:none;">
        <table style="width:100%;font-size:0.8rem;border-collapse:collapse;">
            <tr style="background:#f5f5f5;">
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">Table Exists</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;"><?= $tableExists ? '<span style="color:#43a047;font-weight:600;">YES</span>' : '<span style="color:#e53935;font-weight:600;">NO</span>' ?></td>
            </tr>
            <tr>
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">Total Rows in DB</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;"><?= $rawRowCount ?></td>
            </tr>
            <tr style="background:#f5f5f5;">
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">Query Returned</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;"><?= count($subscribers) ?> subscribers</td>
            </tr>
            <tr>
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">DB Error</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;"><?= empty($dbError) ? '<span style="color:#43a047;">None</span>' : '<span style="color:#e53935;">' . htmlspecialchars($dbError, ENT_QUOTES, 'UTF-8') . '</span>' ?></td>
            </tr>
            <tr style="background:#f5f5f5;">
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">Subscribe URL</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;font-family:monospace;"><?= $bp ?>/newsletter/subscribe</td>
            </tr>
            <tr>
                <td style="padding:6px 10px;font-weight:600;border:1px solid #e0e0e0;">Admin Route</td>
                <td style="padding:6px 10px;border:1px solid #e0e0e0;font-family:monospace;"><?= $bp ?>/admin/newsletter</td>
            </tr>
        </table>
    </div>
</div>

<!-- Subscribers Table -->
<div class="admin-card">
    <div class="admin-card-header">
        <h3 class="admin-card-title">Subscribers (<?= count($subscribers) ?>)</h3>
    </div>
    <div class="admin-card-body">
        <?php if (empty($subscribers)): ?>
        <div class="admin-empty-state">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="48" height="48" style="margin-bottom:1rem;opacity:0.4;"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
            <?php if ($rawRowCount > 0): ?>
                <p style="color:#e53935;"><strong>There are <?= $rawRowCount ?> rows in the database but the query returned 0 results.</strong></p>
                <p>This usually means the query has a filter or error. Check the Debug Info section above.</p>
            <?php else: ?>
                <p>No subscribers found. Subscribers will appear here when visitors subscribe from the homepage newsletter form.</p>
                <p style="font-size:0.85rem;color:#666;margin-top:0.5rem;">Make sure the subscription form on the home page is working. Try subscribing yourself and check if you see a real success message (not a server error).</p>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <div class="admin-table-responsive">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Email</th>
                        <th>Name</th>
                        <?php if ($hasStudentIdCol): ?><th>Student</th><?php endif; ?>
                        <th>Status</th>
                        <th>Source</th>
                        <th>Subscribed At</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($subscribers as $i => $sub): ?>
                    <tr>
                        <td><?= $i + 1 ?></td>
                        <td>
                            <strong><?= htmlspecialchars($sub['email'], ENT_QUOTES, 'UTF-8') ?></strong>
                        </td>
                        <td><?= htmlspecialchars($sub['name'] ?? '-', ENT_QUOTES, 'UTF-8') ?></td>
                        <?php if ($hasStudentIdCol): ?>
                        <td>
                            <?php if (!empty($sub['student_id'])): ?>
                                <a href="<?= $bp ?>/admin/students/<?= (int) $sub['student_id'] ?>" class="admin-badge admin-badge-info" title="View Student">ID: <?= (int) $sub['student_id'] ?></a>
                            <?php else: ?>
                                <span class="admin-text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <?php endif; ?>
                        <td>
                            <?php
                            $statusClass = match($sub['status'] ?? '') {
                                'active' => 'admin-badge-success',
                                'unsubscribed' => 'admin-badge-secondary',
                                'bounced' => 'admin-badge-warning',
                                default => 'admin-badge-info'
                            };
                            ?>
                            <span class="admin-badge <?= $statusClass ?>"><?= ucfirst($sub['status'] ?? 'active') ?></span>
                        </td>
                        <td><?= htmlspecialchars($sub['source'] ?? 'homepage', ENT_QUOTES, 'UTF-8') ?></td>
                        <td><?= date('M d, Y h:i A', strtotime($sub['subscribed_at'] ?? 'now')) ?></td>
                        <td>
                            <div class="admin-action-group">
                                <!-- Toggle Status -->
                                <form method="POST" action="<?= $bp ?>/admin/newsletter/<?= (int) $sub['id'] ?>/toggle-status" style="display:inline" onsubmit="return confirm('Toggle status for this subscriber?')">
                                    <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                                    <button type="submit" class="admin-btn-icon-only" title="<?= ($sub['status'] ?? '') === 'active' ? 'Unsubscribe' : 'Activate' ?>">
                                        <?php if (($sub['status'] ?? '') === 'active'): ?>
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>
                                        <?php else: ?>
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                                        <?php endif; ?>
                                    </button>
                                </form>
                                <!-- Delete -->
                                <form method="POST" action="<?= $bp ?>/admin/newsletter/<?= (int) $sub['id'] ?>/delete" style="display:inline" onsubmit="return confirm('Are you sure you want to delete this subscriber?')">
                                    <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                                    <button type="submit" class="admin-btn-icon-only admin-text-danger" title="Delete">
                                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>
