<?php
// api/ping.php — visit this in your browser to diagnose any issues
// https://yourdomain.com/api/ping.php

header('Content-Type: application/json');

$configPath = dirname(__DIR__) . '/config.php';
if (!file_exists($configPath)) {
    echo json_encode([
        'ok'    => false,
        'error' => 'config.php not found',
        'looked_in' => dirname(__DIR__),
    ]); exit;
}

require_once $configPath;

$apiToken   = defined('SONICPESA_API_TOKEN') ? SONICPESA_API_TOKEN : null;
$apiBaseUrl = defined('SONICPESA_API_URL')   ? SONICPESA_API_URL   : null;

$missing = [];
if (!$apiToken)   $missing[] = 'SONICPESA_API_TOKEN';
if (!$apiBaseUrl) $missing[] = 'SONICPESA_API_URL';

if (!empty($missing)) {
    echo json_encode(['ok' => false, 'missing_constants' => $missing]); exit;
}

// Test SonicPesa connectivity
$ch = curl_init(rtrim($apiBaseUrl, '/') . '/transactions/readbyId');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode(['page' => 1]),
    CURLOPT_HTTPHEADER => [
        'X-API-KEY: ' . $apiToken,
        'Content-Type: application/json',
        'Accept: application/json'
    ],
    CURLOPT_FOLLOWLOCATION => true,
]);
$raw  = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err  = curl_error($ch);
curl_close($ch);

echo json_encode([
    'ok'                    => true,
    'php'                   => PHP_VERSION,
    'site_url'              => defined('SITE_URL') ? SITE_URL : 'not defined',
    'sonicpesa_url'         => $apiBaseUrl,
    'token_looks_valid'     => strlen($apiToken) > 10,
    'sonicpesa_http_code'   => $code,
    'sonicpesa_curl_error'  => $err ?: null,
    'sonicpesa_response'    => $code === 200 ? json_decode($raw, true) : $raw,
]);
