<?php
/**
 * api/test_kindamba.php
 * Tests Payment API connectivity for a given Public Key and optional base URL.
 * Used by Admin Panel "Test Connection" button.
 */
header('Content-Type: application/json');

$baseDir = dirname(__DIR__);
require_once $baseDir . '/config.php';
require_once $baseDir . '/includes/db.php';
require_once $baseDir . '/includes/kindamba.php';

$input     = json_decode(file_get_contents('php://input'), true);
$publicKey = trim($input['api_key'] ?? '');
$testUrl   = trim($input['api_url'] ?? '');

if (!$publicKey) {
    echo json_encode(['success' => false, 'message' => 'Public Key is required for testing.']);
    exit;
}

// If a test URL was supplied, temporarily override what get_payment_api_url() returns
// by injecting it into the DB session (read-only override via a global variable).
if (!empty($testUrl)) {
    // Validate it looks like a URL
    if (!filter_var($testUrl, FILTER_VALIDATE_URL)) {
        echo json_encode(['success' => false, 'message' => 'The API URL you entered is not a valid URL.']);
        exit;
    }
    // Store in a global so get_payment_api_url() can pick it up
    $GLOBALS['_override_payment_api_url'] = rtrim($testUrl, '/');
}

// We test by sending a status check with a dummy transaction ID.
// Any response (even 404/422) means the API endpoint is reachable.
$result = kindamba_verify_status('test-connection-check-' . time(), $publicKey);

$httpCode = $result['code'] ?? 0;
$resolvedUrl = get_payment_api_url();

if ($httpCode === 0) {
    echo json_encode([
        'success' => false,
        'message' => 'Could not reach the Payment API at: ' . $resolvedUrl . '. Check the URL and your server\'s internet connection.',
        'url_tested' => $resolvedUrl
    ]);
} elseif ($httpCode === 401) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid Public Key \u2014 the API responded with 401 Unauthorized.',
        'url_tested' => $resolvedUrl
    ]);
} else {
    echo json_encode([
        'success'    => true,
        'message'    => 'Connection successful! API is reachable (HTTP ' . $httpCode . ').',
        'url_tested' => $resolvedUrl,
        'http_code'  => $httpCode
    ]);
}
