<?php
/**
 * Direct eTIMS API Test
 * Access via: https://ent.nelcare.co.ke/test_etims_direct.php
 */

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

// Test configuration
$config = [
    'environment' => 'sandbox',
    'tin' => 'P052077586R',
    'api_key' => 'etims-fc-2025-secure-api-key-9ffhksorghjlys',
    'branch_code' => '00'
];

// Possible sandbox URLs to try
$urls_to_test = [
    'http://62.169.23.132:4122/selectInitInfo',
    'https://sbx.etims.kra.go.ke/api/selectInitInfo',
    'https://sandbox.etims.kra.go.ke/api/selectInitInfo'
];

$results = [];

foreach ($urls_to_test as $url) {
    echo "Testing: $url\n\n";
    
    $data = [
        'tin' => $config['tin'],
        'bhfId' => $config['branch_code']
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'key: ' . $config['api_key']
        ],
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_VERBOSE => true
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    $curl_info = curl_getinfo($ch);
    curl_close($ch);
    
    $result = [
        'url' => $url,
        'http_code' => $http_code,
        'success' => empty($curl_error) && $http_code == 200,
        'error' => $curl_error,
        'response' => $response,
        'connection_time' => $curl_info['connect_time'] ?? 0,
        'total_time' => $curl_info['total_time'] ?? 0
    ];
    
    $results[] = $result;
    
    echo "HTTP Code: $http_code\n";
    echo "Error: " . ($curl_error ?: 'None') . "\n";
    echo "Response: " . substr($response, 0, 200) . "\n";
    echo "---\n\n";
}

// Summary
echo "\n=== SUMMARY ===\n";
$working_url = null;
foreach ($results as $result) {
    $status = $result['success'] ? '✓ SUCCESS' : '✗ FAILED';
    echo "$status - {$result['url']}\n";
    if ($result['success']) {
        $working_url = $result['url'];
    }
}

if ($working_url) {
    echo "\n✓ Found working URL: $working_url\n";
    echo "\nUpdate your system_settings with this URL.\n";
} else {
    echo "\n✗ All URLs failed. The eTIMS sandbox is currently unavailable.\n";
    echo "Recommendation: Enable Mock Mode in System Settings.\n";
}

// Return JSON response
echo "\n\n=== JSON RESPONSE ===\n";
echo json_encode([
    'tested_urls' => count($urls_to_test),
    'working_url' => $working_url,
    'all_results' => $results
], JSON_PRETTY_PRINT);
?>