<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
define('BASE_URL', '');

include __DIR__ . '/config/db.php';
include __DIR__ . '/config/auth.php';
require_page_access();

$success = '';
$error   = '';

// ── Handle actions ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id     = (int)($_POST['id'] ?? 0);
    try {
        if ($action === 'toggle' && $id) {
            $pdo->prepare("UPDATE subscribe SET is_active = IF(is_active=1,0,1) WHERE id=?")->execute([$id]);
            $success = 'Status updated.';
        } elseif ($action === 'delete' && $id) {
            $pdo->prepare("DELETE FROM subscribe WHERE id=?")->execute([$id]);
            $success = 'Subscriber deleted.';
        } elseif ($action === 'delete_all_unsubscribed') {
            $pdo->exec("DELETE FROM subscribe WHERE is_active = 0");
            $success = 'All unsubscribed emails removed.';
        }
    } catch (PDOException $e) {
        $error = $e->getMessage();
    }
    header('Location: subscribers.php?msg=' . urlencode($success ?: $error));
    exit;
}

if (isset($_GET['msg'])) $success = $_GET['msg'];

// ── Search & filter ───────────────────────────────────────────────────────
$search  = trim($_GET['q']      ?? '');
$filter  = $_GET['status']      ?? '';
$page    = max(1, (int)($_GET['p'] ?? 1));
$perPage = 20;

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

if ($search)      { $where[] = 'email LIKE ?';   $params[] = "%$search%"; }
if ($filter !== '') { $where[] = 'is_active = ?'; $params[] = (int)$filter; }

$sql = "SELECT * FROM subscribe" . ($where ? " WHERE " . implode(' AND ', $where) : "") . " ORDER BY subscribed_at DESC";

try {
    $all = $pdo->prepare($sql);
    $all->execute($params);
    $rows  = $all->fetchAll(PDO::FETCH_ASSOC);
    $total = count($rows);

    // Stats
    $statsRow = $pdo->query("SELECT COUNT(*) total, SUM(is_active=1) active, SUM(is_active=0) inactive FROM subscribe")->fetch();

    // Paginate
    $totalPages = max(1, ceil($total / $perPage));
    $page       = min($page, $totalPages);
    $rows       = array_slice($rows, ($page - 1) * $perPage, $perPage);

} catch (PDOException $e) {
    $error    = $e->getMessage();
    $rows     = []; $total = 0; $totalPages = 1;
    $statsRow = ['total' => 0, 'active' => 0, 'inactive' => 0];
}

$user_name = $_SESSION['username'] ?? 'Admin';
$user_role = $_SESSION['role']     ?? 'admin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscribers — Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family:'Roboto',sans-serif; margin:0; height:100vh; overflow:hidden; }
        body.dark { background-color:#1a202c; color:#e2e8f0; }
        .sidebar { width:250px; background:#2d3748; color:white; transition:all .3s; height:100%; position:fixed; top:0; left:0; z-index:10; overflow-y:auto; }
        .sidebar.collapsed { width:70px; }
        .sidebar.collapsed .sidebar-title { display:none; }
        .content { margin-left:250px; transition:margin-left .3s; height:100vh; overflow-y:auto; }
        .content.collapsed-sidebar { margin-left:70px; }
        .nav-item { padding:10px 12px; cursor:pointer; transition:background .2s; display:flex; align-items:center; }
        .nav-item:hover { background:#4a5568; }
        .nav-item.active { background:#4a5568; border-left:4px solid #4299e1; }
        body.dark .bg-white { background-color:#2d3748; }
        body.dark input,body.dark select { background-color:#374151; color:#e5e7eb; border-color:#4b5563; }
        body.dark table { color:#e2e8f0; }
        body.dark .border-gray-200 { border-color:#4a5568; }
        body.dark .bg-gray-50 { background-color:#374151; }
        @media(max-width:768px){ .sidebar{transform:translateX(-250px);} .sidebar.mobile-open{transform:translateX(0);} .content{margin-left:0;} }
    </style>
</head>
<body class="bg-gray-100">

<button onclick="toggleMobileSidebar()" class="fixed top-3 left-3 z-20 bg-gray-800 text-white px-3 py-2 rounded-md md:hidden">☰</button>
<?php include __DIR__ . '/include/sidebar.php'; ?>

<div class="content" id="content">

    <!-- Topbar -->
    <div class="bg-white border-b border-gray-200 px-6 py-4 flex items-center justify-between sticky top-0 z-10 shadow-sm">
        <div class="flex items-center gap-3">
            <button onclick="toggleSidebar()" class="text-gray-500 hover:text-gray-700 hidden md:block"><i class="fas fa-bars text-lg"></i></button>
            <div class="flex items-center gap-2 text-sm text-gray-500">
                <a href="pages.php" class="hover:text-blue-600"><i class="fas fa-home"></i></a>
                <i class="fas fa-chevron-right text-xs text-gray-300"></i>
                <span class="text-gray-800 font-semibold">Newsletter Subscribers</span>
            </div>
        </div>
        <div class="flex items-center gap-3">
            <button id="darkModeToggle" class="text-gray-500 w-9 h-9 rounded-lg border border-gray-200 flex items-center justify-center"><i class="fas fa-moon"></i></button>
            <a href="?export=csv<?= $search ? '&q='.urlencode($search) : '' ?><?= $filter !== '' ? '&status='.$filter : '' ?>"
               class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition">
                <i class="fas fa-download"></i> Export CSV
            </a>
        </div>
    </div>

    <?php
    // ── CSV Export ─────────────────────────────────────────────────────────
    if (isset($_GET['export']) && $_GET['export'] === 'csv') {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="subscribers_' . date('Y-m-d') . '.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['ID', 'Email', 'Status', 'Subscribed At', 'IP Address']);
        $expStmt = $pdo->prepare($sql);
        $expStmt->execute($params);
        foreach ($expStmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            fputcsv($out, [
                $r['id'],
                $r['email'],
                $r['is_active'] ? 'Active' : 'Unsubscribed',
                $r['subscribed_at'],
                $r['ip_address'] ?? ''
            ]);
        }
        fclose($out);
        exit;
    }
    ?>

    <main class="p-6">

        <?php if ($success): ?>
        <div class="bg-green-50 border-l-4 border-green-500 text-green-700 p-4 mb-5 rounded-lg flex items-center gap-2" id="flash">
            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success) ?>
        </div>
        <?php endif; ?>
        <?php if ($error): ?>
        <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-5 rounded-lg">
            <i class="fas fa-exclamation-circle mr-2"></i><?= htmlspecialchars($error) ?>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="grid grid-cols-3 gap-4 mb-6">
            <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 text-center">
                <div class="text-3xl font-bold text-blue-600"><?= number_format($statsRow['total']) ?></div>
                <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Total</div>
            </div>
            <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 text-center">
                <div class="text-3xl font-bold text-green-600"><?= number_format($statsRow['active']) ?></div>
                <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Active</div>
            </div>
            <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 text-center">
                <div class="text-3xl font-bold text-gray-400"><?= number_format($statsRow['inactive']) ?></div>
                <div class="text-xs text-gray-500 mt-1 font-medium uppercase tracking-wide">Unsubscribed</div>
            </div>
        </div>

        <!-- Table Card -->
        <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">

            <!-- Toolbar -->
            <div class="p-4 border-b border-gray-100 flex flex-wrap gap-3 items-center">
                <form method="GET" class="flex flex-wrap gap-3 flex-1">
                    <div class="relative flex-1 min-w-[200px] max-w-sm">
                        <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                        <input type="text" name="q" placeholder="Search email…"
                            value="<?= htmlspecialchars($search) ?>"
                            class="w-full border border-gray-300 rounded-lg pl-9 pr-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <select name="status" onchange="this.form.submit()"
                        class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="">All Status</option>
                        <option value="1" <?= $filter === '1' ? 'selected' : '' ?>>Active</option>
                        <option value="0" <?= $filter === '0' ? 'selected' : '' ?>>Unsubscribed</option>
                    </select>
                    <?php if ($search || $filter !== ''): ?>
                    <a href="subscribers.php" class="border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 flex items-center gap-1">
                        <i class="fas fa-times"></i> Clear
                    </a>
                    <?php endif; ?>
                </form>
                <span class="text-sm text-gray-400"><?= $total ?> result<?= $total !== 1 ? 's' : '' ?></span>
                <?php if ($statsRow['inactive'] > 0): ?>
                <form method="POST" onsubmit="return confirm('Delete all <?= $statsRow['inactive'] ?> unsubscribed emails?')">
                    <input type="hidden" name="action" value="delete_all_unsubscribed">
                    <button type="submit" class="text-xs bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 px-3 py-2 rounded-lg flex items-center gap-1 transition">
                        <i class="fas fa-trash"></i> Clear Unsubscribed
                    </button>
                </form>
                <?php endif; ?>
            </div>

            <!-- Table -->
            <div class="overflow-x-auto">
                <?php if (empty($rows)): ?>
                <div class="text-center py-16">
                    <i class="fas fa-envelope text-4xl text-gray-200 mb-3 block"></i>
                    <p class="text-gray-500 font-medium">No subscribers found</p>
                </div>
                <?php else: ?>
                <table class="w-full text-sm text-left text-gray-600">
                    <thead class="bg-gray-50 border-b border-gray-200">
                        <tr>
                            <th class="px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">#</th>
                            <th class="px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Email</th>
                            <th class="px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Status</th>
                            <th class="px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">Subscribed At</th>
                            <th class="px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide">IP Address</th>
                            <th class="px-5 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wide text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100">
                        <?php foreach ($rows as $i => $r): ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-5 py-3 text-gray-400 font-mono text-xs"><?= ($page - 1) * $perPage + $i + 1 ?></td>
                            <td class="px-5 py-3 font-medium text-gray-800">
                                <div class="flex items-center gap-2">
                                    <div class="w-7 h-7 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center text-xs font-bold flex-shrink-0">
                                        <?= strtoupper(substr($r['email'], 0, 1)) ?>
                                    </div>
                                    <?= htmlspecialchars($r['email']) ?>
                                </div>
                            </td>
                            <td class="px-5 py-3">
                                <?php if ($r['is_active'] == 1): ?>
                                <span class="inline-flex items-center gap-1.5 bg-green-100 text-green-700 text-xs font-semibold px-2.5 py-1 rounded-full">
                                    <span class="w-1.5 h-1.5 rounded-full bg-green-500"></span> Active
                                </span>
                                <?php else: ?>
                                <span class="inline-flex items-center gap-1.5 bg-gray-100 text-gray-500 text-xs font-semibold px-2.5 py-1 rounded-full">
                                    <span class="w-1.5 h-1.5 rounded-full bg-gray-400"></span> Unsubscribed
                                </span>
                                <?php endif; ?>
                            </td>
                            <td class="px-5 py-3 text-xs text-gray-500 font-mono whitespace-nowrap">
                                <?= date('d M Y', strtotime($r['subscribed_at'])) ?><br>
                                <span class="text-gray-400"><?= date('H:i', strtotime($r['subscribed_at'])) ?></span>
                            </td>
                            <td class="px-5 py-3 text-xs text-gray-400 font-mono">
                                <?= htmlspecialchars($r['ip_address'] ?? '—') ?>
                            </td>
                            <td class="px-5 py-3">
                                <div class="flex items-center justify-center gap-2">
                                    <!-- Toggle status -->
                                    <form method="POST">
                                        <input type="hidden" name="action" value="toggle">
                                        <input type="hidden" name="id"     value="<?= $r['id'] ?>">
                                        <button type="submit" title="<?= $r['is_active'] ? 'Deactivate' : 'Activate' ?>"
                                            class="text-xs px-3 py-1.5 rounded-lg border font-medium flex items-center gap-1 transition
                                                   <?= $r['is_active'] ? 'bg-yellow-50 hover:bg-yellow-100 text-yellow-700 border-yellow-200' : 'bg-green-50 hover:bg-green-100 text-green-700 border-green-200' ?>">
                                            <i class="fas <?= $r['is_active'] ? 'fa-pause' : 'fa-play' ?>"></i>
                                            <?= $r['is_active'] ? 'Deactivate' : 'Activate' ?>
                                        </button>
                                    </form>
                                    <!-- Delete -->
                                    <form method="POST" onsubmit="return confirm('Delete <?= htmlspecialchars(addslashes($r['email'])) ?>?')">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id"     value="<?= $r['id'] ?>">
                                        <button type="submit" class="text-xs bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 px-3 py-1.5 rounded-lg flex items-center gap-1 transition">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($totalPages > 1): ?>
            <div class="px-5 py-4 border-t border-gray-100 flex items-center justify-between text-sm text-gray-600">
                <span>Page <?= $page ?> of <?= $totalPages ?></span>
                <div class="flex gap-1">
                    <?php for ($pg = 1; $pg <= $totalPages; $pg++): ?>
                    <a href="?p=<?= $pg ?><?= $search ? '&q='.urlencode($search) : '' ?><?= $filter !== '' ? '&status='.$filter : '' ?>"
                       class="w-8 h-8 flex items-center justify-center rounded-lg text-xs font-medium transition
                              <?= $pg === $page ? 'bg-blue-600 text-white' : 'bg-gray-100 hover:bg-gray-200 text-gray-600' ?>">
                        <?= $pg ?>
                    </a>
                    <?php endfor; ?>
                </div>
            </div>
            <?php endif; ?>

        </div>
    </main>
</div>

<script>
var fl = document.getElementById('flash');
if (fl) setTimeout(function(){ fl.style.transition='opacity .5s'; fl.style.opacity='0'; setTimeout(function(){ fl.remove(); },500); }, 3500);

function toggleMobileSidebar(){ document.getElementById('sidebar').classList.toggle('mobile-open'); }
var sc = false;
function toggleSidebar(){
    sc = !sc;
    document.getElementById('sidebar').classList.toggle('collapsed', sc);
    document.getElementById('content').classList.toggle('collapsed-sidebar', sc);
}
document.getElementById('darkModeToggle').addEventListener('click', function(){
    document.body.classList.toggle('dark');
    this.querySelector('i').classList.toggle('fa-moon');
    this.querySelector('i').classList.toggle('fa-sun');
    localStorage.setItem('darkMode', document.body.classList.contains('dark') ? 'enabled' : 'disabled');
});
if (localStorage.getItem('darkMode') === 'enabled'){
    document.body.classList.add('dark');
    document.getElementById('darkModeToggle').querySelector('i').classList.replace('fa-moon','fa-sun');
}
</script>
</body>
</html>