<?php
/**
 * Crownline Global — PHP Integration Example
 *
 * This is a minimal working example showing how to:
 *   1. Create a payment
 *   2. Check a payment's status
 *   3. Receive and verify webhook notifications
 *
 * No external dependencies required (uses cURL, built into PHP).
 */

define('API_BASE_URL', 'https://api.crownlineglobal.co.uk');
define('API_KEY', getenv('CROWNLINE_API_KEY'));

// ---------------------------------------------------------------------
// Helper: make an authenticated request to the Crownline API
// ---------------------------------------------------------------------
function crownlineRequest($method, $path, $body = null) {
    $ch = curl_init(API_BASE_URL . $path);
    $headers = ['Authorization: Bearer ' . API_KEY];

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response, true);
}

// ---------------------------------------------------------------------
// 1. Create a payment (call this when your customer clicks "Pay")
// ---------------------------------------------------------------------
function createPayment($orderId, $amount, $customerName, $customerEmail, $customerPhone) {
    $result = crownlineRequest('POST', '/api/payments/create', [
        'merchantOrderId'   => $orderId,
        'amount'            => $amount,
        'countryCode'       => 'IDN',
        'currency'          => 'Rp',
        'language'          => 'ID',
        'paymentMethodCode' => 'BNIVA',
        'notificationUrl'   => 'https://yourshop.com/webhooks/payment.php',
        'customerName'      => $customerName,
        'customerEmail'     => $customerEmail,
        'customerPhone'     => $customerPhone,
        'productName'       => "Order #$orderId",
    ]);

    if ($result['code'] !== 'SUCCESS') {
        throw new Exception('Payment creation failed: ' . ($result['error'] ?? $result['message'] ?? 'unknown error'));
    }

    return $result;
}

// Example usage:
// $payment = createPayment('ORDER-1001', 150000, 'Jane Doe', 'jane@example.com', '081234567890');
// Show $payment['paymentInfo']['content'] to your customer.

// ---------------------------------------------------------------------
// 2. Check payment status
// ---------------------------------------------------------------------
function checkPaymentStatus($orderId) {
    return crownlineRequest('GET', '/api/payments/status?merchantOrderId=' . urlencode($orderId));
}

// ---------------------------------------------------------------------
// 3. Receive and verify webhook notifications
//    (this part goes in a separate file, e.g. webhooks/payment.php)
// ---------------------------------------------------------------------
/*
$rawBody = file_get_contents('php://input');
$signatureHeader = $_SERVER['HTTP_X_PAYFAC_SIGNATURE'] ?? '';

$expectedSignature = hash_hmac('sha256', $rawBody, API_KEY);

if (!hash_equals($expectedSignature, $signatureHeader)) {
    http_response_code(401);
    exit('invalid signature');
}

$notification = json_decode($rawBody, true);

// $notification['status'] will be "SUCCESS", "PENDING", or "FAILED"
// $notification['paidAmount'] is the ACTUAL amount paid — use this,
// not $notification['amount'], to confirm the order was paid in full.
if ($notification['status'] === 'SUCCESS') {
    // TODO: mark the order as paid in your own database
}

http_response_code(200);
*/