<?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'] ?? '');
$order_id      = trim($input['orderID']       ?? '');

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

try {
    // Capture via PayPal API
    $ch = curl_init(PAYPAL_API_URL . '/v2/checkout/orders/' . $order_id . '/capture');
    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),
        ],
    ]);
    $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 capture HTTP $http_code: $detail");
    }

    $data        = json_decode($response, true);
    $status      = $data['status'] ?? 'UNKNOWN';
    $capture_id  = $data['purchase_units'][0]['payments']['captures'][0]['id'] ?? null;
    $payer_email = $data['payer']['email_address'] ?? '';
    $payer_name  = trim(($data['payer']['name']['given_name'] ?? '') . ' ' . ($data['payer']['name']['surname'] ?? ''));
    $actual_amt  = $data['purchase_units'][0]['payments']['captures'][0]['amount']['value'] ?? 0;
    $actual_cur  = $data['purchase_units'][0]['payments']['captures'][0]['amount']['currency_code'] ?? 'USD';

    // Find by primary key lookup using BINARY — zero collation risk
    $find = db()->prepare("SELECT payment_id FROM payments WHERE BINARY gateway_order_id = ? LIMIT 1");
    $find->execute([$order_id]);
    $row = $find->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        db()->prepare("
            UPDATE payments SET
                gateway_capture_id = ?,
                status             = ?,
                payer_email        = ?,
                payer_name         = ?,
                amount             = ?,
                currency           = ?,
                raw_response       = ?,
                paid_at            = IF(? = 'COMPLETED', NOW(), paid_at)
            WHERE payment_id = ?
        ")->execute([
            $capture_id, $status, $payer_email, $payer_name,
            $actual_amt, $actual_cur, $response, $status,
            $row['payment_id'],
        ]);
    }

    if ($status === 'COMPLETED') {
        db()->prepare("UPDATE submissions SET submission_status = 'submitted' WHERE BINARY tracking_code = ?")
            ->execute([$tracking_code]);
    }

    logPaymentError("PayPal OK | order=$order_id | capture=$capture_id | status=$status", $tracking_code, 'info');
    echo json_encode(['success' => true, 'capture_id' => $capture_id, 'status' => $status]);

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