<?php
/**
 * Government API Connection Test
 * Tests database connection, seller data, and government API connectivity
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

$results = [
    'timestamp' => date('Y-m-d H:i:s'),
    'tests' => []
];

// Test 1: Include db.php
try {
    require_once 'db.php';
    $results['tests']['db_include'] = [
        'status' => 'OK',
        'message' => 'db.php included successfully'
    ];
} catch (Exception $e) {
    $results['tests']['db_include'] = [
        'status' => 'FAIL',
        'error' => $e->getMessage()
    ];
    echo json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

// Test 2: Check if $pdo exists and is valid
global $pdo;
$results['tests']['pdo_exists'] = [
    'status' => (isset($pdo) && $pdo !== null) ? 'OK' : 'FAIL',
    'is_set' => isset($pdo),
    'is_null' => $pdo === null,
    'type' => isset($pdo) ? get_class($pdo) : 'not set'
];

// Test 3: Test database query
if (isset($pdo) && $pdo !== null) {
    try {
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM sellers");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $results['tests']['db_query'] = [
            'status' => 'OK',
            'sellers_count' => $row['count'],
            'message' => 'Database query successful'
        ];
    } catch (Exception $e) {
        $results['tests']['db_query'] = [
            'status' => 'FAIL',
            'error' => $e->getMessage()
        ];
    }
    
    // Test 4: Get seller credentials (without exposing full values)
    try {
        $stmt = $pdo->query("SELECT id, seller_name, client_id, secret_key FROM sellers LIMIT 1");
        $seller = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($seller) {
            $results['tests']['seller_credentials'] = [
                'status' => 'OK',
                'seller_id' => $seller['id'],
                'seller_name' => $seller['seller_name'],
                'has_client_id' => !empty($seller['client_id']),
                'client_id_length' => strlen($seller['client_id'] ?? ''),
                'has_secret_key' => !empty($seller['secret_key']),
                'secret_key_length' => strlen($seller['secret_key'] ?? ''),
                'message' => 'Seller found with credentials'
            ];
        } else {
            $results['tests']['seller_credentials'] = [
                'status' => 'FAIL',
                'message' => 'No sellers found in database'
            ];
        }
    } catch (Exception $e) {
        $results['tests']['seller_credentials'] = [
            'status' => 'FAIL',
            'error' => $e->getMessage()
        ];
    }
} else {
    $results['tests']['db_query'] = [
        'status' => 'SKIP',
        'message' => 'Skipped - PDO not available'
    ];
    $results['tests']['seller_credentials'] = [
        'status' => 'SKIP',
        'message' => 'Skipped - PDO not available'
    ];
}

// Test 5: Test CURL availability
$results['tests']['curl_available'] = [
    'status' => function_exists('curl_init') ? 'OK' : 'FAIL',
    'message' => function_exists('curl_init') ? 'CURL is available' : 'CURL is not available'
];

// Test 6: Test government API connectivity
if (function_exists('curl_init')) {
    $ch = curl_init('https://backend.jofotara.gov.jo/core/invoices/');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_NOBODY => true,
        CURLOPT_HTTPHEADER => ['Accept: application/json']
    ]);
    
    $startTime = microtime(true);
    curl_exec($ch);
    $endTime = microtime(true);
    
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    $errno = curl_errno($ch);
    
    curl_close($ch);
    
    $results['tests']['gov_api_connection'] = [
        'status' => ($httpCode > 0 && $errno === 0) ? 'OK' : 'FAIL',
        'url' => 'https://backend.jofotara.gov.jo/core/invoices/',
        'http_code' => $httpCode,
        'response_time' => round(($endTime - $startTime) * 1000, 2) . 'ms',
        'curl_error' => $error ?: null,
        'curl_errno' => $errno,
        'message' => ($httpCode > 0) ? "API reachable (HTTP $httpCode)" : "API unreachable: $error"
    ];
}

// Test 7: Check PHP configuration
$results['tests']['php_config'] = [
    'status' => 'OK',
    'php_version' => PHP_VERSION,
    'memory_limit' => ini_get('memory_limit'),
    'max_execution_time' => ini_get('max_execution_time'),
    'allow_url_fopen' => ini_get('allow_url_fopen') ? 'yes' : 'no'
];

// Calculate overall status
$allStatuses = array_column($results['tests'], 'status');
$failedCount = count(array_filter($allStatuses, fn($s) => $s === 'FAIL'));
$okCount = count(array_filter($allStatuses, fn($s) => $s === 'OK'));

$results['summary'] = [
    'overall' => $failedCount === 0 ? 'ALL_PASSED' : 'SOME_FAILED',
    'total_tests' => count($results['tests']),
    'passed' => $okCount,
    'failed' => $failedCount,
    'message' => $failedCount === 0 
        ? '✅ All tests passed - System ready for government API'
        : "❌ $failedCount test(s) failed - Check details above"
];

echo json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
