<?php

require __DIR__ . '/../bootstrap.php';

use KeyLair\ApiToken;
use KeyLair\Database;
use KeyLair\Helpers;

header('Content-Type: application/json; charset=utf-8');

// Server-to-server only -- a bearer token from admin/api_access.php, not
// an admin session cookie. No CSRF check: there's no cookie-based session
// for a cross-site request to ride along on in the first place.
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? (function_exists('apache_request_headers') ? (apache_request_headers()['Authorization'] ?? '') : '');
if (!preg_match('/^Bearer\s+(.+)$/i', trim($authHeader), $matches)) {
    http_response_code(401);
    echo json_encode(['error' => 'Missing or malformed Authorization header. Expected: Bearer <token>']);
    exit;
}
$token = ApiToken::verify($matches[1]);
if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid or revoked token.']);
    exit;
}

$email = trim($_GET['email'] ?? '');
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['error' => 'A valid ?email= query parameter is required.']);
    exit;
}

$pdo = Database::connection();
$baseUrl = Helpers::baseUrl();

// Not deduplicated by design (see UserFactory) -- two different people can
// share an email, so every matching user's own claim links are returned
// separately rather than merged into one.
$userStmt = $pdo->prepare('SELECT id, name FROM users WHERE email = :email');
$userStmt->execute(['email' => $email]);
$users = $userStmt->fetchAll();

$linksStmt = $pdo->prepare(
    "SELECT l.id, l.token, l.status, l.expires_at, c.name AS campaign_name
     FROM claim_links l
     LEFT JOIN campaigns c ON c.id = l.campaign_id
     WHERE l.user_id = :user_id
     ORDER BY l.created_at DESC"
);
$productsStmt = $pdo->prepare(
    'SELECT p.name, p.slug, clp.max_claims, clp.claims_used
     FROM claim_link_products clp
     JOIN products p ON p.id = clp.product_id
     WHERE clp.claim_link_id = :link_id
     ORDER BY clp.id'
);

$results = [];
foreach ($users as $user) {
    $linksStmt->execute(['user_id' => $user['id']]);
    $links = [];
    foreach ($linksStmt->fetchAll() as $link) {
        $overviewUrl = $baseUrl . '/claim/' . $link['token'];
        $productsStmt->execute(['link_id' => $link['id']]);
        $products = array_map(static function (array $p) use ($overviewUrl) {
            return [
                'name' => $p['name'],
                'url' => $overviewUrl . '/' . $p['slug'],
                'max_claims' => (int) $p['max_claims'],
                'claims_used' => (int) $p['claims_used'],
            ];
        }, $productsStmt->fetchAll());

        $links[] = [
            'status' => $link['status'],
            'campaign' => $link['campaign_name'],
            'expires_at' => $link['expires_at'],
            'overview_url' => $overviewUrl,
            'products' => $products,
        ];
    }
    $results[] = [
        'user_id' => (int) $user['id'],
        'name' => $user['name'],
        'claim_links' => $links,
    ];
}

echo json_encode(['email' => $email, 'users' => $results], JSON_UNESCAPED_SLASHES);
