<?php
// Save this as test-stk.php and run it to test your STK Push setup

// Copy your configuration from main code
const MPESA_CONSUMER_KEY = 'iuqlSSSznmd7xkTrhfqhd0bs69BwGRhs';
const MPESA_CONSUMER_SECRET = 'ZyBbCZrWkmhYS4wH';
const MPESA_PASSKEY = '948e4bb1270ef63ed7c97edf9fcd58e16de93e3a62463399aa584979a6f679ac';
const MPESA_SHORTCODE = '4088127';
const MPESA_CALLBACK_URL = 'https://apis.gnmprimesource.co.ke/apis/mpesa-callback.php';
const MPESA_ENV = 'live'; // Try changing this to 'sandbox' for testing

// Test with a valid Safaricom number
$testPhone = '254722000000'; // Replace with an actual test phone number
$testAmount = 1; // Minimum amount for testing

echo "Running STK Push test...\n";
echo "Environment: " . MPESA_ENV . "\n";
echo "Shortcode: " . MPESA_SHORTCODE . "\n";
echo "Phone: " . $testPhone . "\n";

// Get access token
$accessToken = getMpesaAccessToken();
if (!$accessToken) {
    echo "ERROR: Failed to get access token\n";
    exit;
}

echo "Access token obtained successfully: " . substr($accessToken, 0, 10) . "...\n";

// Initiate STK Push
$response = initiateDirectSTKPush($accessToken, $testPhone, $testAmount);
echo "STK Push Response:\n";
print_r($response);

// Helper functions
function getMpesaAccessToken() {
    $url = (MPESA_ENV == 'live') ? 
        'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials' : 
        'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
    
    $credentials = base64_encode(MPESA_CONSUMER_KEY . ':' . MPESA_CONSUMER_SECRET);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Basic ' . $credentials,
        'Content-Type: application/json'
    ]);
    
    echo "Requesting token from: " . $url . "\n";
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_errno($ch)) {
        echo "CURL ERROR: " . curl_error($ch) . "\n";
        curl_close($ch);
        return null;
    }
    
    curl_close($ch);
    
    echo "Token HTTP Response: " . $httpCode . "\n";
    echo "Token Response: " . $response . "\n";
    
    $data = json_decode($response, true);
    return $data['access_token'] ?? null;
}

function initiateDirectSTKPush($accessToken, $phoneNumber, $amount) {
    $url = (MPESA_ENV == 'live') ? 
        'https://api.safaricom.co.ke/mpesa/stkpush/v1/processrequest' : 
        'https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest';
    
    $timestamp = date('YmdHis');
    $password = base64_encode(MPESA_SHORTCODE . MPESA_PASSKEY . $timestamp);
    
    $data = [
        'BusinessShortCode' => MPESA_SHORTCODE,
        'Password' => $password,
        'Timestamp' => $timestamp,
        'TransactionType' => 'CustomerPayBillOnline',
        'Amount' => (int)$amount,
        'PartyA' => $phoneNumber,
        'PartyB' => MPESA_SHORTCODE,
        'PhoneNumber' => $phoneNumber,
        'CallBackURL' => MPESA_CALLBACK_URL,
        'AccountReference' => 'TestPayment',
        'TransactionDesc' => 'Test STK Push'
    ];
    
    echo "STK Push Request to: " . $url . "\n";
    echo "Request data: " . json_encode($data, JSON_PRETTY_PRINT) . "\n";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_errno($ch)) {
        echo "CURL ERROR: " . curl_error($ch) . "\n";
        curl_close($ch);
        return ['error' => 'Request failed: ' . curl_error($ch)];
    }
    
    curl_close($ch);
    
    echo "STK Push HTTP Response: " . $httpCode . "\n";
    echo "STK Push Raw Response: " . $response . "\n";
    
    return json_decode($response, true) ?: ['error' => 'Invalid response'];
}
?>