<?php
/**
 * api/tag_assign.php
 * ------------------------------------------------------------------
 * REST‑ähnlicher Endpunkt, um Tags anhand der E‑Mail‑Adresse
 * externen Systemen zuzuordnen.
 *
 * ▸ Auth per X‑API‑Key (konfiguriert in config.php → $config['api']['key'])
 * ▸ Request‑Methode: POST, Content‑Type: application/json
 * ▸ Payload: { "email": "max@example.com", "tags": ["VIP", "Newsletter"] }
 * ▸ Antwort: JSON mit Zähler der zugeordneten / übersprungenen Tags
 *
 * Alle SQL‑Operationen werden geloggt (Erfolg & Fehler) und Änderungen via
 * logSettingChange() dokumentiert.
 *
 * Beispiel‑Aufruf:
 * curl -X POST https://mr9.mrsend.de/api/tag_assign.php \\
 *      -H "Content-Type: application/json" \\
 *      -H "X-API-Key: YOUR_API_KEY" \\
 *      -d '{"email":"max@example.com","tags":["VIP","Newsletter"]}'
 */

require_once __DIR__ . '/../includes/init.php';

header('Content-Type: application/json');

$config = include __DIR__ . '/../includes/config.php';
$db     = Database::getInstance();
$recipientAutomationService = new RecipientAutomationService($db);
new AutomationRuleEngine($db, $recipientAutomationService);

// ---------------------------------------------------------------------------
// 1) Authentifizierung über X-API-Key
// ---------------------------------------------------------------------------
$apiKeyHeader = $_SERVER['HTTP_X_API_KEY'] ?? '';
if ($apiKeyHeader !== ($config['api']['key'] ?? '')) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

// ---------------------------------------------------------------------------
// 2) Nur POST zulassen
// ---------------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

// ---------------------------------------------------------------------------
// 3) Input validieren
// ---------------------------------------------------------------------------
$payload = json_decode(file_get_contents('php://input'), true);
$email   = trim($payload['email'] ?? '');
$tags    = $payload['tags'] ?? [];

if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid or missing e‑mail']);
    exit;
}
if (!is_array($tags) || count($tags) === 0) {
    http_response_code(400);
    echo json_encode(['error' => 'No tags specified']);
    exit;
}

try {
    // -----------------------------------------------------------------------
    // 4) Empfänger ermitteln
    // -----------------------------------------------------------------------
    $stmt = $db->prepare('SELECT id FROM recipients WHERE email = :email LIMIT 1');
    $stmt->bindValue(':email', $email);
    $stmt->execute();
    ErrorLogger::logSqlSuccess($stmt->queryString);

    $recipientId = (int)$stmt->fetchColumn();
    if (!$recipientId) {
        http_response_code(404);
        echo json_encode(['error' => 'Recipient not found']);
        exit;
    }

    // -----------------------------------------------------------------------
    // 5) Tags zuordnen
    // -----------------------------------------------------------------------
    $tagLookup = $db->prepare('SELECT id FROM tags WHERE name = :name LIMIT 1');

    $assigned = 0;
    $skipped  = 0;

    foreach ($tags as $rawTag) {
        $name = trim($rawTag);
        if ($name === '') { // leere Strings ignorieren
            $skipped++;
            continue;
        }

        // Tag‑ID suchen
        $tagLookup->bindValue(':name', $name);
        $tagLookup->execute();
        ErrorLogger::logSqlSuccess($tagLookup->queryString);
        $tagId = (int)$tagLookup->fetchColumn();

        if (!$tagId) { // Tag existiert nicht → überspringen (oder hier anlegen?)
            $skipped++;
            continue;
        }

        if ($recipientAutomationService->assignTagToRecipient($recipientId, $tagId, [
            'source' => 'api_tag_assign',
        ])) {
            $assigned++;
        } else {
            $skipped++; // bereits vorhanden
        }
    }

    // -----------------------------------------------------------------------
    // 6) Änderung protokollieren & Antwort
    // -----------------------------------------------------------------------
    logSettingChange($recipientId, 'assign', 'recipient_tags', json_encode(['tags' => $tags]));

    echo json_encode([
        'assigned' => $assigned,
        'skipped'  => $skipped,
        'message'  => $assigned ? 'Tags zugeordnet.' : 'Keine neuen Zuordnungen.'
    ]);
} catch (Throwable $e) {
    ErrorLogger::logSqlError('tag_assign API | error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Internal Server Error']);
}
