<?php

$passphrase = 'reservit4321';

$data = [
    'merchant_id'      => '10050937',
    'merchant_key'     => '978nbtuc7bnjc',
    'return_url'       => 'http://127.0.0.1:8000/api/payment/return',
    'cancel_url'       => 'http://127.0.0.1:8000/api/payment/cancel',
    'notify_url'       => 'http://127.0.0.1:8000/api/payment/notify',
    'name_first'       => 'Sthembiso',
    'name_last'        => 'Mathebula',
    'email_address'    => 'smathebula.sb11@gmail.com',
    'cell_number'      => '0721496687',
    'm_payment_id'     => '27',
    'amount'           => '100.00',
    'item_name'        => 'Booking for Yoga Class',
    'item_description' => 'Service booking - Date: 2026-07-06',
    //'reference'      => 'BOOKING-41-PAYMENT-27', // Leave commented for now
    'custom_int1'      => '27',
    'custom_str1'      => 'booking_payment',
];

//
// Generate Signature
//
$paramString = '';

foreach ($data as $key => $value) {

    if ($value === '') {
        continue;
    }

    $paramString .= $key . '=' . urlencode(trim($value)) . '&';
}

$paramString = rtrim($paramString, '&');

if ($passphrase !== '') {
    $paramString .= '&passphrase=' . urlencode($passphrase);
}

$signature = md5($paramString);

$data['signature'] = $signature;

echo "==============================\n";
echo "PARAM STRING\n";
echo "==============================\n";
echo $paramString . "\n\n";

echo "==============================\n";
echo "SIGNATURE\n";
echo "==============================\n";
echo $signature . "\n\n";

//
// Send to PayFast
//

$ch = curl_init('https://s...content-available-to-author-only...o.za/eng/process');

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query($data),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/x-www-form-urlencoded'
    ],
]);

$response = curl_exec($ch);

if ($response === false) {
    die(curl_error($ch));
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);

curl_close($ch);

echo "==============================\n";
echo "HTTP STATUS\n";
echo "==============================\n";
echo $httpCode . "\n\n";

echo "==============================\n";
echo "HEADERS\n";
echo "==============================\n";
echo $headers . "\n";

echo "==============================\n";
echo "BODY\n";
echo "==============================\n";
echo $body;
