<?php
/**
 * includes/kindamba.php
 * Payment Gateway API Helper — endpoint is configurable from Admin Panel.
 */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/db.php';

/**
 * Resolve the active Payment API base URL.
 * Priority: DB (site_settings.payment_api_url) > KINDAMBA_API_URL constant > fallback.
 */
function get_payment_api_url() {
    global $pdo;
    static $cached_url = null;

    // Allow a temporary override (used by the Test Connection API endpoint)
    if (!empty($GLOBALS['_override_payment_api_url'])) {
        return rtrim($GLOBALS['_override_payment_api_url'], '/');
    }

    if ($cached_url !== null) return $cached_url;
    try {
        $stmt = $pdo->query("SELECT payment_api_url FROM site_settings WHERE id = 1 LIMIT 1");
        $row  = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row && !empty($row['payment_api_url'])) {
            $cached_url = rtrim($row['payment_api_url'], '/');
            return $cached_url;
        }
    } catch (Exception $e) {}
    // Fallback to config.php constant
    $cached_url = defined('KINDAMBA_API_URL') ? rtrim(KINDAMBA_API_URL, '/') : 'https://www.pesagate.online/api';
    return $cached_url;
}


/**
 * Resolve the active Payment API public key.
 * Priority: caller-supplied > DB (site_settings.payment_api_public_key) > KINDAMBA_PUBLIC_KEY constant.
 */
function get_payment_api_key() {
    global $pdo;
    static $cached_key = null;
    if ($cached_key !== null) return $cached_key;
    try {
        $stmt = $pdo->query("SELECT payment_api_public_key FROM site_settings WHERE id = 1 LIMIT 1");
        $row  = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row && !empty($row['payment_api_public_key'])) {
            $cached_key = $row['payment_api_public_key'];
            return $cached_key;
        }
    } catch (Exception $e) {}
    $cached_key = defined('KINDAMBA_PUBLIC_KEY') ? KINDAMBA_PUBLIC_KEY : '';
    return $cached_key;
}

/**
 * Internal helper to send requests to the Payment API
 */
function kindamba_request($method, $endpoint, $body = [], $public_key = null) {
    // Resolve the key: caller > DB > config.php constant
    if (!$public_key) {
        $public_key = get_payment_api_key();
    }

    // Warn if the key looks unusual (informational only — does not block)
    if ($public_key && stripos($public_key, 'pk_') !== 0) {
        error_log("[PaymentAPI] Warning: Key does not start with 'pk_': " . substr($public_key, 0, 10) . "...");
    }

    // Resolve API base URL dynamically from DB / config
    $api_base = get_payment_api_url();
    $url = $api_base . '/' . ltrim($endpoint, '/');

    $headers = [
        'X-Public-Key: ' . $public_key,
        'Accept: application/json',
        'Content-Type: application/json',
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 45); // Increased timeout for shared hosting
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects if any

    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);
    $curlNo   = curl_errno($ch);

    // Common shared hosting fallback: if SSL cert fail (60) or other SSL issues, retry without verification
    if ($curlNo === 60 || $curlNo === 77 || $curlNo === 35) {
        error_log("[PaymentAPI] SSL Error ($curlNo). Retrying without verification.");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlErr  = curl_error($ch);
    }
    
    curl_close($ch);

    if ($curlErr && !$response) {
        error_log("[PaymentAPI] cURL Error ($curlNo): $curlErr");
        return ['code' => 0, 'data' => ['success' => false, 'message' => "Connection Error ($curlNo): $curlErr"]];
    }

    $data = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("[PaymentAPI] Invalid JSON from API (HTTP $httpCode): " . substr($response, 0, 100));
        return ['code' => $httpCode, 'data' => ['success' => false, 'message' => 'API returned invalid response.', 'raw' => $response]];
    }

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

/**
 * Initiate a new payment
 */
function kindamba_initiate_payment($phone, $amount, $name = 'Guest Customer', $email = 'guest@kindamba.site', $reference = '', $callback_url = '', $public_key = null) {
    // Normalize phone number to 255XXXXXXXXX format
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (strlen($phone) == 10 && substr($phone, 0, 1) === '0') {
        $phone = '255' . substr($phone, 1);
    }

    return kindamba_request('POST', 'initiate', [
        "buyer_name"         => $name,
        "buyer_email"        => $email,
        "buyer_phone"        => $phone,
        "amount"             => (int)$amount,
        "currency"           => "TZS",
        "external_reference" => $reference,
        "callback_url"       => $callback_url
    ], $public_key);
}

/**
 * Verify transaction status
 */
function kindamba_verify_status($transaction_id, $public_key = null) {
    // Append a timestamp to prevent proxy/Cloudflare caching of the GET request
    return kindamba_request('GET', 'status?id=' . urlencode($transaction_id) . '&_=' . time(), [], $public_key);
}
?>
