<?php
declare(strict_types=1);

/**
 * POST /c2c/payments/capture-order.php
 *
 * Captured eine genehmigte PayPal Order und setzt den Status auf "paid".
 * Wird vom Frontend nach onApprove aufgerufen. Webhook ist Backup.
 *
 * Request (JSON):
 *   { "order_id": "5O190127TN364715T" }
 *
 * Response (JSON):
 *   { "success": true,  "status": "COMPLETED", "capture_id": "..." }
 *   { "success": false, "status": "..." }
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: https://come2canada.life');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-C2C-Token');
header('Vary: Origin');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

require_once __DIR__ . '/paypal-client.php';
require_once __DIR__ . '/../includes/rcic-matcher.php';
$config = require __DIR__ . '/_config.php';

$pdo = null;

try {
    $body    = json_decode(file_get_contents('php://input'), true) ?: [];
    $orderId = (string)($body['order_id'] ?? '');

    if ($orderId === '') {
        throw new InvalidArgumentException('order_id fehlt');
    }

    $pdo = new PDO(
        "mysql:host={$config['db']['host']};dbname={$config['db']['name']};charset=utf8mb4",
        $config['db']['user'],
        $config['db']['password'],
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
    );

    // Pending Payment laden — nur pending darf captured werden
    $stmt = $pdo->prepare(
        'SELECT id, client_id, service_type, amount_chf, status
         FROM payments
         WHERE paypal_order_id = ?
         LIMIT 1'
    );
    $stmt->execute([$orderId]);
    $payment = $stmt->fetch();

    if (!$payment) {
        http_response_code(404);
        echo json_encode(['error' => 'Order nicht gefunden']);
        exit;
    }

    // Idempotenz: schon completed → einfach bestätigen
    if ($payment['status'] === 'completed') {
        echo json_encode([
            'success'    => true,
            'status'     => 'COMPLETED',
            'capture_id' => null,
            'note'       => 'bereits captured',
        ]);
        exit;
    }

    if ($payment['status'] !== 'pending') {
        http_response_code(409);
        echo json_encode(['error' => 'Payment ist nicht im Status pending (' . $payment['status'] . ')']);
        exit;
    }

    // PayPal capturen
    $sandbox = (bool)$config['paypal']['sandbox'];
    $paypal  = new PayPalClient(
        $sandbox ? $config['paypal']['sandbox_client_id']     : $config['paypal']['live_client_id'],
        $sandbox ? $config['paypal']['sandbox_client_secret'] : $config['paypal']['live_client_secret'],
        $sandbox
    );

    $captureResponse = $paypal->captureOrder($orderId);

    $captureId     = $captureResponse['purchase_units'][0]['payments']['captures'][0]['id'] ?? null;
    $captureStatus = (string)($captureResponse['status'] ?? '');

    if ($captureStatus !== 'COMPLETED') {
        $pdo->prepare('UPDATE payments SET status = "failed", raw_response = ? WHERE id = ?')
            ->execute([json_encode($captureResponse, JSON_UNESCAPED_UNICODE), $payment['id']]);

        $pdo->prepare('INSERT INTO aktivitaeten (klient_id, aktion, beschreibung, erstellt_am) VALUES (?, ?, ?, NOW())')
            ->execute([$payment['client_id'], 'zahlung_fehlgeschlagen', "Order $orderId · Status: $captureStatus"]);

        echo json_encode([
            'success' => false,
            'status'  => $captureStatus,
        ]);
        exit;
    }

    // Erfolg — Transaktion: Payment + Client gemeinsam aktualisieren
    $pdo->beginTransaction();

    $pdo->prepare('UPDATE payments SET status = "completed", paypal_capture_id = ?, raw_response = ? WHERE id = ?')
        ->execute([$captureId, json_encode($captureResponse, JSON_UNESCAPED_UNICODE), $payment['id']]);

    $pdo->prepare('UPDATE clients SET status = "paid", updated_at = NOW() WHERE id = ?')
        ->execute([$payment['client_id']]);

    $pdo->prepare('INSERT INTO aktivitaeten (klient_id, aktion, beschreibung, erstellt_am) VALUES (?, ?, ?, NOW())')
        ->execute([
            $payment['client_id'],
            'zahlung_eingegangen',
            'CHF ' . number_format((float)$payment['amount_chf'], 2) . ' · ' . $payment['service_type'] . ' · Capture: ' . $captureId,
        ]);

    $pdo->commit();

    // Auto-Match RCICs nach erfolgreichem Capture (best effort, blockiert nicht).
    // Fehler werden nur geloggt — der Capture an sich ist erfolgreich,
    // RCIC-Match ist nice-to-have und kann auch manuell im HQ ausgelöst werden.
    try {
        $matchResult = c2c_auto_match_for_client($pdo, (int)$payment['client_id'], 3);

        $logMsg = sprintf(
            '%d Berater zugeordnet · Provinzen erkannt: %s',
            $matchResult['written'],
            count($matchResult['provinces_detected']) > 0
                ? implode(', ', $matchResult['provinces_detected'])
                : 'keine'
        );

        $pdo->prepare('INSERT INTO aktivitaeten (klient_id, aktion, beschreibung, erstellt_am) VALUES (?, ?, ?, NOW())')
            ->execute([$payment['client_id'], 'rcic_zugeordnet', $logMsg]);

    } catch (Throwable $matchError) {
        error_log('[c2c rcic-match] client_id=' . $payment['client_id'] . ' · ' . $matchError->getMessage());
        try {
            $pdo->prepare('INSERT INTO aktivitaeten (klient_id, aktion, beschreibung, erstellt_am) VALUES (?, ?, ?, NOW())')
                ->execute([$payment['client_id'], 'rcic_match_fehlgeschlagen', $matchError->getMessage()]);
        } catch (Throwable $_) {
            // Auch das Log-Insert kann fehlschlagen — wir machen weiter.
        }
    }

    echo json_encode([
        'success'    => true,
        'status'     => 'COMPLETED',
        'capture_id' => $captureId,
    ]);

} catch (Throwable $e) {
    if ($pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    error_log('[c2c capture-order] ' . $e->getMessage());
    echo json_encode(['error' => $e->getMessage()]);
}
