<?php
// ============================================================
// come2canada.life — Marketing API
// Pfad: /c2c/api/marketing.php
// Methoden: GET, POST, PATCH, DELETE
// Auth: X-C2C-Token gegen hq_sessions
// ============================================================

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, X-C2C-Token');
header('Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204); exit;
}

function jsonOut(array $data, int $code = 200): void {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// ── DATENBANK ─────────────────────────────────────────────

try {
    $pdo = new PDO(
        'mysql:host=localhost;dbname=neubad_c2c;charset=utf8mb4',
        'neubad_c2c_chris',
        getenv('C2C_DB_PASS') ?: '',
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
         PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
    );
} catch (PDOException $e) {
    jsonOut(['ok' => false, 'error' => 'DB-Verbindung fehlgeschlagen'], 500);
}

// ── AUTH ──────────────────────────────────────────────────

$token = $_SERVER['HTTP_X_C2C_TOKEN'] ?? '';
if (!$token) {
    jsonOut(['ok' => false, 'error' => 'Nicht autorisiert'], 401);
}

$stmt = $pdo->prepare("SELECT id FROM hq_sessions WHERE token = ? AND expires_at > NOW()");
$stmt->execute([$token]);
if (!$stmt->fetch()) {
    jsonOut(['ok' => false, 'error' => 'Nicht autorisiert'], 401);
}

// ── ROUTING ───────────────────────────────────────────────

$method  = $_SERVER['REQUEST_METHOD'];
$segment = trim($_GET['s'] ?? '', '/');   // ?s=milestones oder leer = tasks

// Unterscheide Tasks vs. Milestones
if ($segment === 'milestones') {
    handleMilestones($pdo, $method);
} else {
    handleTasks($pdo, $method);
}

// ── TASKS ─────────────────────────────────────────────────

function handleTasks(PDO $pdo, string $method): void {

    if ($method === 'GET') {
        $where = '1=1';
        $params = [];
        if (!empty($_GET['status'])) {
            $where .= ' AND status = ?'; $params[] = $_GET['status'];
        }
        if (!empty($_GET['kategorie'])) {
            $where .= ' AND kategorie = ?'; $params[] = $_GET['kategorie'];
        }
        $rows = $pdo->prepare(
            "SELECT * FROM marketing_tasks WHERE $where ORDER BY woche ASC, prioritaet DESC, erstellt_am ASC"
        );
        $rows->execute($params);
        jsonOut(['ok' => true, 'tasks' => $rows->fetchAll()]);
    }

    if ($method === 'POST') {
        $b = json_decode(file_get_contents('php://input'), true) ?? [];
        if (empty($b['titel'])) {
            jsonOut(['ok' => false, 'error' => 'Titel fehlt'], 422);
        }
        $stmt = $pdo->prepare(
            "INSERT INTO marketing_tasks (titel, kategorie, beschreibung, status, prioritaet, woche, faellig)
             VALUES (?, ?, ?, ?, ?, ?, ?)"
        );
        $stmt->execute([
            $b['titel'],
            $b['kategorie']   ?? 'allgemein',
            $b['beschreibung'] ?? null,
            $b['status']      ?? 'offen',
            $b['prioritaet']  ?? 'mittel',
            $b['woche']       ?? null,
            $b['faellig']     ?? null,
        ]);
        jsonOut(['ok' => true, 'id' => $pdo->lastInsertId()]);
    }

    if ($method === 'PATCH') {
        $id = (int)($_GET['id'] ?? 0);
        $b  = json_decode(file_get_contents('php://input'), true) ?? [];
        if (!$id) jsonOut(['ok' => false, 'error' => 'ID fehlt'], 422);

        $allowed = ['titel','kategorie','beschreibung','status','prioritaet','woche','faellig'];
        $sets = []; $params = [];
        foreach ($allowed as $f) {
            if (array_key_exists($f, $b)) {
                $sets[]   = "$f = ?";
                $params[] = $b[$f];
            }
        }
        if (!$sets) jsonOut(['ok' => false, 'error' => 'Nichts zu aktualisieren'], 422);
        $params[] = $id;
        $pdo->prepare("UPDATE marketing_tasks SET " . implode(', ', $sets) . " WHERE id = ?")
            ->execute($params);
        jsonOut(['ok' => true]);
    }

    if ($method === 'DELETE') {
        $id = (int)($_GET['id'] ?? 0);
        if (!$id) jsonOut(['ok' => false, 'error' => 'ID fehlt'], 422);
        $pdo->prepare("DELETE FROM marketing_tasks WHERE id = ?")->execute([$id]);
        jsonOut(['ok' => true]);
    }

    jsonOut(['ok' => false, 'error' => 'Methode nicht erlaubt'], 405);
}

// ── MILESTONES ────────────────────────────────────────────

function handleMilestones(PDO $pdo, string $method): void {

    if ($method === 'GET') {
        $rows = $pdo->query(
            "SELECT * FROM marketing_milestones ORDER BY monat ASC, id ASC"
        );
        jsonOut(['ok' => true, 'milestones' => $rows->fetchAll()]);
    }

    if ($method === 'PATCH') {
        $id = (int)($_GET['id'] ?? 0);
        $b  = json_decode(file_get_contents('php://input'), true) ?? [];
        if (!$id) jsonOut(['ok' => false, 'error' => 'ID fehlt'], 422);
        $pdo->prepare("UPDATE marketing_milestones SET erledigt = ? WHERE id = ?")
            ->execute([(int)(bool)$b['erledigt'], $id]);
        jsonOut(['ok' => true]);
    }

    if ($method === 'POST') {
        $b = json_decode(file_get_contents('php://input'), true) ?? [];
        if (empty($b['titel']) || empty($b['monat'])) {
            jsonOut(['ok' => false, 'error' => 'Titel und Monat erforderlich'], 422);
        }
        $pdo->prepare("INSERT INTO marketing_milestones (monat, titel) VALUES (?, ?)")
            ->execute([(int)$b['monat'], $b['titel']]);
        jsonOut(['ok' => true, 'id' => $pdo->lastInsertId()]);
    }

    jsonOut(['ok' => false, 'error' => 'Methode nicht erlaubt'], 405);
}
