<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../inc/payment_helpers.php';

$input         = json_decode(file_get_contents('php://input'), true) ?? [];
$tracking_code = trim($input['tracking_code'] ?? '');
$amount        = $input['amount']   ?? '';
$currency      = strtoupper($input['currency'] ?? 'USD');

if (!$tracking_code || !$amount) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing parameters']);
    exit;
}

try {
    // Get submission_id using BINARY to avoid collation issues
    $stmt = db()->prepare("SELECT submission_id FROM submissions WHERE BINARY tracking_code = ?");
    $stmt->execute([$tracking_code]);
    $sub = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$sub) { throw new RuntimeException('Submission not found'); }
    $submission_id = (int)$sub['submission_id'];

    // Create PayPal order
    $ch = curl_init(PAYPAL_API_URL . '/v2/checkout/orders');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Authorization: Basic ' . base64_encode(PAYPAL_CLIENT_ID . ':' . PAYPAL_SECRET),
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'intent' => 'CAPTURE',
            'purchase_units' => [[
                'reference_id' => 'CGBL-' . $tracking_code,
                'amount'       => [
                    'currency_code' => $currency,
                    'value'         => number_format((float)$amount, 2, '.', ''),
                ],
                'description' => 'Publication Fee',
            ]],
            'application_context' => [
                'brand_name'  => 'Communeglobal',
                'user_action' => 'PAY_NOW',
                'return_url'  => SITE_URL . '/author/payment_success.php',
                'cancel_url'  => SITE_URL . '/author/pay.php?tracking_code=' . urlencode($tracking_code),
            ],
        ]),
    ]);
    $response  = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code !== 201) {
        $err    = json_decode($response, true);
        $detail = $err['details'][0]['description'] ?? ($err['message'] ?? $response);
        throw new RuntimeException("PayPal create HTTP $http_code: $detail");
    }

    $order    = json_decode($response, true);
    $order_id = $order['id'] ?? null;
    if (!$order_id) { throw new RuntimeException('No order ID in PayPal response'); }

    // INSERT using submission_id (integer) — completely avoids string collation on insert
    db()->prepare("
        INSERT INTO payments
            (submission_id, tracking_code, invoice_no, gateway, gateway_order_id, status, amount, currency, raw_response)
        VALUES (?, ?, ?, 'paypal', ?, 'CREATED', ?, ?, ?)
    ")->execute([
        $submission_id,
        $tracking_code,
        'CGBL-' . $tracking_code,
        $order_id,
        $amount,
        $currency,
        $response,
    ]);

    echo json_encode(['order_id' => $order_id]);

} catch (Throwable $e) {
    logPaymentError('PayPal create: ' . $e->getMessage(), $tracking_code);
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}