<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';

if (!isset($_SESSION['admin_id']) || !in_array($_SESSION['admin_role'], ['manager','superadmin'])) {
    die("Access denied");
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo SITE_TITLE . ' | Affiliate Tags'; ?></title>
    <link rel="stylesheet" href="css/admin.css">
</head>
<body>
<div class="container">
<?php
$adminId = $_SESSION['admin_id'];
$affiliateId = $_GET['affiliate_id'] ?? null;
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 25;
$offset = ($page - 1) * $limit;

// Handle new tag
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['affiliate_id'], $_POST['tag'])) {
    $stmt = $pdo->prepare("INSERT IGNORE INTO affiliate_tags (affiliate_id, tag, added_by_admin) VALUES (?, ?, ?)");
    $stmt->execute([$_POST['affiliate_id'], $_POST['tag'], $adminId]);
    log_admin_action($pdo, 'add_affiliate_tag', "Tagged affiliate #{$_POST['affiliate_id']} with '{$_POST['tag']}'");
    echo "<p class='success'>✅ Tag added.</p>";
}

// Build query
$query = "SELECT t.*, a.name AS affiliate_name, u.username AS admin_name 
          FROM affiliate_tags t 
          JOIN affiliates a ON t.affiliate_id = a.id 
          JOIN admin_users u ON t.added_by_admin = u.id";
$params = [];

if ($affiliateId) {
    $query .= " WHERE t.affiliate_id = ?";
    $params[] = $affiliateId;
}

$countQuery = str_replace("t.*, a.name AS affiliate_name, u.username AS admin_name", "COUNT(*)", $query);
$countStmt = $pdo->prepare($countQuery);
$countStmt->execute($params);
$totalTags = $countStmt->fetchColumn();
$totalPages = ceil($totalTags / $limit);

$query .= " ORDER BY t.created_at DESC LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$tags = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Export CSV
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=affiliate_tags.csv');
    echo "Affiliate,Tag,Added By,Time\n";
    foreach ($tags as $t) {
        echo "\"{$t['affiliate_name']}\",\"{$t['tag']}\",\"{$t['admin_name']}\",\"{$t['created_at']}\"\n";
    }
    exit;
}

// UI
echo "<h2>📌 Affiliate Tags</h2>
<form method='post'>
    <input name='affiliate_id' placeholder='Affiliate ID' required>
    <input name='tag' placeholder='Tag (e.g. VIP, Crypto)' required>
    <button type='submit'>Add Tag</button>
</form>";

echo "<form method='get'>
    <input name='affiliate_id' placeholder='Affiliate ID' value='" . htmlspecialchars($affiliateId) . "'>
    <button type='submit'>Filter</button>
    <button onclick=\"window.location='?affiliate_id=$affiliateId&export=1';return false;\">Export CSV</button>
</form>";

echo "<table><tr>
    <th>Affiliate</th><th>Tag</th><th>Added By</th><th>Time</th>
</tr>";
foreach ($tags as $t) {
    echo "<tr>
        <td>" . htmlspecialchars($t['affiliate_name']) . " (#" . htmlspecialchars($t['affiliate_id']) . ")</td>
        <td>" . htmlspecialchars($t['tag']) . "</td>
        <td>" . htmlspecialchars($t['admin_name']) . "</td>
        <td>{$t['created_at']}</td>
    </tr>";
}
echo "</table>";

// Pagination
if ($totalPages > 1) {
    echo "<div style='margin-top:20px'><strong>Pages:</strong> ";
    for ($i = 1; $i <= $totalPages; $i++) {
        $link = "?affiliate_id=$affiliateId&page=$i";
        echo "<a href='$link' style='margin-right:10px'>" . ($i == $page ? "<strong>$i</strong>" : $i) . "</a>";
    }
    echo "</div>";
}
?>
</div>
</body>
</html>