<?php
declare(strict_types=1);

/* ================= AUTH ================= */
require_once __DIR__ . '/../security/auth_guard_web.php';
require_once __DIR__ . '/../partials/main.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Subscribers']); ?>
<?php include '../partials/head-css.php'; ?>
</head>

<body>
<div id="layout-wrapper">

<?php include '../partials/header.php'; ?>
<?php include '../partials/sidebar.php'; ?>
<?php include '../partials/horizontal.php'; ?>

<main class="app-wrapper">
<div class="container-fluid">

<?php includeFileWithVariables('../partials/page-title.php', [
    'title_sub' => 'Marketing',
    'title'     => 'Subscribers'
]); ?>

<!-- ================= FILTERS ================= -->
<div class="card mb-4">
<div class="card-body">

<div class="row g-3 align-items-end">

<div class="col-md-3">
    <label class="form-label">Search</label>
    <input type="text" id="search" class="form-control"
           placeholder="Name or Email">
</div>

<div class="col-md-2">
    <label class="form-label">Status</label>
    <select id="status" class="form-select">
        <option value="">All</option>
        <option value="active">Active</option>
        <option value="inactive">Inactive</option>
    </select>
</div>

<div class="col-md-2">
    <label class="form-label">From Date</label>
    <input type="date" id="from_date" class="form-control">
</div>

<div class="col-md-2">
    <label class="form-label">To Date</label>
    <input type="date" id="to_date" class="form-control">
</div>

<div class="col-md-3 d-flex gap-2">
    <button class="btn btn-primary w-100" onclick="loadSubscribers(1)">
        <i class="bi bi-search"></i> Filter
    </button>
    <button class="btn btn-light w-100" onclick="resetFilters()">
        Reset
    </button>
</div>

</div>

<div class="row mt-3">
<div class="col text-end">
    <button class="btn btn-success" onclick="exportCSV()">
        <i class="bi bi-download me-1"></i> Export CSV
    </button>
</div>
</div>

</div>
</div>

<!-- ================= LIST ================= -->
<div class="card">
<div class="card-body table-responsive">

<table class="table align-middle text-nowrap">
<thead>
<tr>
    <th>#</th>
    <th>Name</th>
    <th>Email</th>
    <th>Status</th>
    <th>Source</th>
    <th>IP Address</th>
    <th>Subscribed At ↓</th>
</tr>
</thead>

<tbody id="subscriberRows">
<tr>
    <td colspan="7" class="text-center text-muted">
        Loading subscribers…
    </td>
</tr>
</tbody>
</table>

<!-- ================= PAGINATION ================= -->
<div class="d-flex justify-content-between align-items-center mt-3">
    <div id="paginationInfo" class="text-muted small"></div>

    <div class="btn-group">
        <button class="btn btn-outline-secondary btn-sm"
                id="prevBtn"
                onclick="changePage(-1)">
            Previous
        </button>
        <button class="btn btn-outline-secondary btn-sm"
                id="nextBtn"
                onclick="changePage(1)">
            Next
        </button>
    </div>
</div>

</div>
</div>

</div>
</main>

<?php include '../partials/footer.php'; ?>
</div>

<?php include '../partials/vendor-scripts.php'; ?>

<script>
const API_LIST =
    "<?= ADMIN_BASE_URL ?>api/subscribers/list.php";
const API_EXPORT =
    "<?= ADMIN_BASE_URL ?>api/subscribers/export-csv.php";

let currentPage = 1;
const LIMIT = 10;

/* ================= LOAD ================= */
function loadSubscribers(page = 1) {

    currentPage = page;

    const params = new URLSearchParams({
        page: page,
        limit: LIMIT,
        search: document.getElementById('search').value,
        status: document.getElementById('status').value,
        from_date: document.getElementById('from_date').value,
        to_date: document.getElementById('to_date').value
    });

    fetch(API_LIST + '?' + params.toString(), {
        credentials: 'include'
    })
    .then(r => r.json())
    .then(res => {

        const tbody = document.getElementById('subscriberRows');
        tbody.innerHTML = '';

        if (res.status !== 'success' || !res.data.items.length) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center text-muted">
                        No subscribers found
                    </td>
                </tr>`;
            updatePagination(0, 0);
            return;
        }

        const { pagination, items } = res.data;

        items.forEach((s, i) => {

            const statusBadge = `
                <span class="badge bg-${s.is_active == 1 ? 'success' : 'secondary'}">
                    ${s.is_active == 1 ? 'Active' : 'Inactive'}
                </span>`;

            const sourceInfo = `
                <small>
                    ${s.source ?? '-'}<br>
                    <span class="text-muted">${s.medium ?? ''}</span>
                </small>`;

            tbody.innerHTML += `
<tr>
<td>${(pagination.page - 1) * pagination.limit + i + 1}</td>
<td>${s.name ?? '-'}</td>
<td><strong>${s.email}</strong></td>
<td>${statusBadge}</td>
<td>${sourceInfo}</td>
<td>${s.ip_address}</td>
<td>${s.subscribed_at}</td>
</tr>`;
        });

        updatePagination(pagination.total, pagination.page);
    });
}

/* ================= PAGINATION ================= */
function updatePagination(total, page) {

    const totalPages = Math.ceil(total / LIMIT);

    document.getElementById('paginationInfo').innerText =
        total
            ? `Page ${page} of ${totalPages} • ${total} subscribers`
            : '';

    document.getElementById('prevBtn').disabled = page <= 1;
    document.getElementById('nextBtn').disabled = page >= totalPages;
}

function changePage(step) {
    loadSubscribers(currentPage + step);
}

/* ================= RESET ================= */
function resetFilters() {
    document.getElementById('search').value = '';
    document.getElementById('status').value = '';
    document.getElementById('from_date').value = '';
    document.getElementById('to_date').value = '';
    loadSubscribers(1);
}

/* ================= EXPORT CSV ================= */
function exportCSV() {

    const params = new URLSearchParams({
        search: document.getElementById('search').value,
        status: document.getElementById('status').value,
        from_date: document.getElementById('from_date').value,
        to_date: document.getElementById('to_date').value
    });

    window.location.href =
        API_EXPORT + '?' + params.toString();
}

document.addEventListener('DOMContentLoaded', () => {
    loadSubscribers(1);
});
</script>

</body>
</html>
