<?php
/**
 * includes/sonicpesa.php
 * Refined SonicPesa API Helper
 */
require_once __DIR__ . '/../config.php';

/**
 * Internal helper to send requests to SonicPesa API
 */
function sonicpesa_request($method, $endpoint, $body = [], $api_token = null) {
    if (!$api_token && defined('SONICPESA_API_TOKEN')) {
        $api_token = SONICPESA_API_TOKEN;
    }

    $url = rtrim(SONICPESA_API_URL, '/') . $endpoint;

    $headers = [
        'X-API-KEY: ' . $api_token,
        'Accept: application/json',
        'Content-Type: application/json',
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

    if ($method === 'POST') {
        $json = json_encode($body);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    } else {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    }

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr  = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        return ['code' => 0, 'data' => ['success' => false, 'message' => "cURL Error: $curlErr"]];
    }

    $data = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return ['code' => $httpCode, 'data' => ['success' => false, 'message' => 'Invalid JSON from API', 'raw' => $response]];
    }

    return ['code' => $httpCode, 'data' => $data];
}

/**
 * Create a new payment transaction (Create Order)
 */
function sonicpesa_create_transaction($number, $amount, $name = 'Guest Customer', $email = 'guest@sonicpesa.com', $currency = 'TZS', $api_token = null) {
    // Normalize phone number to 255XXXXXXXXX format if needed
    if (preg_match('/^0([0-9]{9})$/', $number, $matches)) {
        $number = '255' . $matches[1];
    }

    return sonicpesa_request('POST', '/payment/create_order', [
        "buyer_name"  => $name,
        "buyer_email" => $email,
        "buyer_phone" => $number,
        "amount"      => $amount,
        "currency"    => $currency
    ], $api_token);
}

/**
 * Check transaction status (Order Status)
 */
function sonicpesa_check_status($order_id, $api_token = null) {
    return sonicpesa_request('POST', '/payment/order_status', [
        'order_id' => $order_id
    ], $api_token);
}

/**
 * List transactions
 */
function sonicpesa_list_transactions($api_token = null) {
    return sonicpesa_request('POST', '/transactions/readbyId', ['page' => 1], $api_token);
}

/**
 * Verify Webhook Signature
 */
function sonicpesa_verify_signature($payload, $signature, $secret = null) {
    if (!$secret && defined('SONICPESA_API_SECRET')) {
        $secret = SONICPESA_API_SECRET;
    }
    if (!$secret) return false;
    
    $expected = hash_hmac('sha256', $payload, $secret);
    return hash_equals($expected, $signature);
}
?>
