<?php
declare(strict_types=1);

/* ================= AUTH ================= */
require_once __DIR__ . '/../../security/auth_guard.php';

/* ================= CORE ================= */
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

/* ================= INPUT (FILTERS) ================= */
$page     = max(1, (int)($_GET['page'] ?? 1));
$limit    = min(100, max(10, (int)($_GET['limit'] ?? 20)));
$offset   = ($page - 1) * $limit;

$status   = $_GET['status'] ?? null;      // active | inactive
$search   = trim($_GET['search'] ?? '');
$fromDate = $_GET['from_date'] ?? null;
$toDate   = $_GET['to_date'] ?? null;

/* ================= CONDITIONS ================= */
$where = [];
$params = [];

if ($status === 'active') {
    $where[] = 's.is_active = 1';
}
if ($status === 'inactive') {
    $where[] = 's.is_active = 0';
}

if ($search !== '') {
    $where[] = '(s.email LIKE :search OR s.name LIKE :search)';
    $params['search'] = '%' . $search . '%';
}

if ($fromDate) {
    $where[] = 'DATE(s.subscribed_at) >= :from_date';
    $params['from_date'] = $fromDate;
}

if ($toDate) {
    $where[] = 'DATE(s.subscribed_at) <= :to_date';
    $params['to_date'] = $toDate;
}

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

/* ================= TOTAL COUNT ================= */
$countStmt = $db->prepare("
    SELECT COUNT(*) 
    FROM website_subscribers s
    $whereSql
");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();

/* ================= LIST ================= */
$stmt = $db->prepare("
    SELECT
        s.id,
        s.name,
        s.email,
        s.is_active,
        s.is_verified,
        s.source_page_url,
        s.referrer_url,
        s.campaign,
        s.medium,
        s.source,
        s.ip_address,
        s.subscribed_at,
        s.unsubscribed_at
    FROM website_subscribers s
    $whereSql
    ORDER BY s.subscribed_at DESC
    LIMIT :limit OFFSET :offset
");

foreach ($params as $k => $v) {
    $stmt->bindValue(':' . $k, $v);
}
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);

$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ================= RESPONSE ================= */
Response::success('Subscribers fetched', [
    'pagination' => [
        'page'  => $page,
        'limit' => $limit,
        'total' => $total
    ],
    'items' => $rows
]);
