<?php
// ─────────────────────────────────────────────
// api/payment.php
// PayPal-Zahlungsabwicklung
// Erstellt Order + verarbeitet Webhook
// ─────────────────────────────────────────────

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

c2c_cors_headers();

$action = $_GET['action'] ?? '';

switch ($action) {
    case 'create':  paypal_create_order();  break;
    case 'capture': paypal_capture_order(); break;
    case 'webhook': paypal_webhook();       break;
    default:
        json_response(['error' => 'Unbekannte Aktion'], 400);
}

// ─────────────────────────────────────────────
// SCHRITT 1: PayPal Order erstellen
// ─────────────────────────────────────────────
function paypal_create_order(): void {
    $input = json_decode(file_get_contents('php://input'), true) ?? [];

    $clientId    = (int)($input['client_id'] ?? 0);
    $serviceType = $input['service_type'] ?? 'portfolio';

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

    $amount = match($serviceType) {
        'starter' => PRICE_STARTER,
        'family'  => PRICE_FAMILY,
        default   => PRICE_PORTFOLIO,
    };

    // Schweizer Franken → USD Conversion (PayPal akzeptiert CHF nicht direkt via JS SDK)
    // Wir rechnen direkt in CHF ab (PayPal unterstützt CHF)
    $accessToken = paypal_get_token();
    if (!$accessToken) json_response(['error' => 'PayPal Auth fehlgeschlagen'], 500);

    $orderData = [
        'intent' => 'CAPTURE',
        'purchase_units' => [[
            'reference_id' => "C2C-{$clientId}-{$serviceType}",
            'description'  => "come2canada.life — " . service_label($serviceType),
            'amount'       => [
                'currency_code' => 'CHF',
                'value'         => number_format($amount, 2, '.', ''),
            ],
            'payee' => ['email_address' => 'christian@christianwehrli.ca'],
        ]],
        'application_context' => [
            'brand_name'          => 'come2canada.life',
            'landing_page'        => 'NO_PREFERENCE',
            'user_action'         => 'PAY_NOW',
            'return_url'          => C2C_PUBLIC_URL . 'danke.php?client=' . $clientId,
            'cancel_url'          => C2C_PUBLIC_URL . 'formular.php?cancel=1',
        ],
    ];

    $response = paypal_request('POST', '/v2/checkout/orders', $accessToken, $orderData);

    if (empty($response['id'])) {
        error_log('PayPal create order failed: ' . json_encode($response));
        json_response(['error' => 'PayPal Order konnte nicht erstellt werden'], 500);
    }

    // Order in DB speichern
    C2CDatabase::get()->prepare("
        INSERT INTO payments (client_id, amount_chf, service_type, method, status, paypal_order_id)
        VALUES (?,?,?,'paypal','pending',?)
    ")->execute([$clientId, $amount, $serviceType, $response['id']]);

    json_response(['orderID' => $response['id']]);
}

// ─────────────────────────────────────────────
// SCHRITT 2: Zahlung abschliessen
// ─────────────────────────────────────────────
function paypal_capture_order(): void {
    $input   = json_decode(file_get_contents('php://input'), true) ?? [];
    $orderId = $input['orderID'] ?? '';
    $clientId= (int)($input['client_id'] ?? 0);

    if (!$orderId) json_response(['error' => 'orderID fehlt'], 422);

    $accessToken = paypal_get_token();
    $response    = paypal_request('POST', "/v2/checkout/orders/{$orderId}/capture", $accessToken);

    $captureId = $response['purchase_units'][0]['payments']['captures'][0]['id'] ?? null;
    $status    = $response['status'] ?? 'UNKNOWN';

    $db = C2CDatabase::get();

    if ($status === 'COMPLETED' && $captureId) {
        // Zahlung als abgeschlossen markieren
        $db->prepare("
            UPDATE payments SET status='completed', paypal_capture_id=?, raw_response=?
            WHERE paypal_order_id=?
        ")->execute([$captureId, json_encode($response), $orderId]);

        // Client-Status aktualisieren
        if ($clientId) {
            $db->prepare("UPDATE clients SET status='analyzing' WHERE id=?")->execute([$clientId]);
            $client = C2CDatabase::getClient($clientId);

            // Zahlungsbestätigung senden
            $payment = $db->prepare("SELECT * FROM payments WHERE paypal_order_id=?")->execute([$orderId]);
            $pmt     = $db->query("SELECT * FROM payments WHERE paypal_order_id='$orderId' LIMIT 1")->fetch();
            if ($client && $pmt) {
                C2CMailer::sendPaymentConfirmation($client, (float)$pmt['amount_chf']);
            }
        }

        json_response(['success' => true, 'status' => 'COMPLETED', 'captureId' => $captureId]);
    } else {
        $db->prepare("UPDATE payments SET status='failed', raw_response=? WHERE paypal_order_id=?")
           ->execute([json_encode($response), $orderId]);
        json_response(['success' => false, 'status' => $status], 400);
    }
}

// ─────────────────────────────────────────────
// WEBHOOK (optional, für server-seitige Bestätigung)
// ─────────────────────────────────────────────
function paypal_webhook(): void {
    $raw    = file_get_contents('php://input');
    $event  = json_decode($raw, true);
    $type   = $event['event_type'] ?? '';

    if ($type === 'PAYMENT.CAPTURE.COMPLETED') {
        $orderId = $event['resource']['supplementary_data']['related_ids']['order_id'] ?? '';
        if ($orderId) {
            C2CDatabase::get()->prepare("UPDATE payments SET status='completed' WHERE paypal_order_id=?")
                              ->execute([$orderId]);
        }
    }

    http_response_code(200);
    echo 'OK';
}

// ─────────────────────────────────────────────
// HELPERS
// ─────────────────────────────────────────────
function paypal_get_token(): ?string {
    $ch = curl_init(PAYPAL_API_BASE . '/v1/oauth2/token');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => 'grant_type=client_credentials',
        CURLOPT_USERPWD        => PAYPAL_CLIENT_ID . ':' . PAYPAL_CLIENT_SECRET,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/x-www-form-urlencoded'],
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    return $data['access_token'] ?? null;
}

function paypal_request(string $method, string $path, string $token, array $body = []): array {
    $ch = curl_init(PAYPAL_API_BASE . $path);
    $opts = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            "Authorization: Bearer $token",
            'PayPal-Request-Id: C2C-' . uniqid(),
        ],
    ];
    if ($method === 'POST') {
        $opts[CURLOPT_POST]       = true;
        $opts[CURLOPT_POSTFIELDS] = json_encode($body);
    }
    curl_setopt_array($ch, $opts);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true) ?? [];
}

function service_label(string $type): string {
    return match($type) {
        'starter' => 'Geschichte Starter (CHF 299)',
        'family'  => 'Familien-Geschichte (CHF 799)',
        default   => 'Vollständiges Portfolio (CHF 599)',
    };
}
