<?php
// ─────────────────────────────────────────────
// api/send_portfolio.php
// Löst die Portfolio-Lieferungs-E-Mail aus
// Aufruf: aus HQ client.php via JS
// ─────────────────────────────────────────────

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/email_portfolio_delivery.php';

c2c_cors_headers();
require_api_token();

$clientId = (int)($_GET['client_id'] ?? 0);
if (!$clientId) json_response(['error' => 'client_id fehlt'], 422);

$client = C2CDatabase::getClient($clientId);
if (!$client) json_response(['error' => 'Klient nicht gefunden'], 404);

// Prüfen ob Portfolio bereit
$db   = C2CDatabase::get();
$stmt = $db->prepare("SELECT id FROM portfolios WHERE client_id=?");
$stmt->execute([$clientId]);
if (!$stmt->fetch()) {
    json_response(['error' => 'Kein Portfolio vorhanden. Bitte zuerst Portfolio generieren.'], 422);
}

try {
    $success = send_portfolio_delivery($clientId);

    if ($success) {
        json_response([
            'success' => true,
            'message' => 'Portfolio-E-Mail an ' . $client['email'] . ' gesendet.',
            'email'   => $client['email'],
        ]);
    } else {
        json_response(['error' => 'E-Mail konnte nicht gesendet werden.'], 500);
    }
} catch (Exception $e) {
    error_log('Portfolio Send Error: ' . $e->getMessage());
    json_response(['error' => $e->getMessage()], 500);
}
