<?php
/**
 * SMART API Connection Test Endpoint
 * Handles various SMART API connection tests
 */
session_start();
require_once '../../layouts/dbconn.php';
require_once '../../layouts/session.php';

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

// Check permission
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

// Get test type
$test_type = $_POST['test_type'] ?? '';

// Fetch SMART settings
$settings_query = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'smart'";
$settings_result = mysqli_query($conn, $settings_query);
$smart_settings = [];
while ($row = mysqli_fetch_assoc($settings_result)) {
    $smart_settings[$row['setting_key']] = $row['setting_value'];
}

// Check if SMART is enabled
$enabled = ($smart_settings['smart_enabled'] ?? '0') === '1';
if (!$enabled) {
    echo json_encode([
        'success' => false,
        'message' => 'SMART integration is disabled. Enable it in System Settings.'
    ]);
    exit();
}

// Get configuration
$environment = $smart_settings['smart_environment'] ?? 'development';
$api_url = $smart_settings['smart_api_url'] ?? '';
if (empty($api_url)) {
    // Auto-detect based on environment
    $api_url = $environment === 'production' 
        ? 'https://data.smartapplicationsgroup.com/providerapi'
        : 'https://data.smartapplicationsgroup.com/providerapi-dev';
}

$provider_key = $smart_settings['smart_provider_key'] ?? '';
$username = $smart_settings['smart_username'] ?? '';
$password = $smart_settings['smart_password'] ?? '';
$client_id = $smart_settings['smart_client_id'] ?? '';
$client_secret = $smart_settings['smart_client_secret'] ?? '';

// Validate required settings
if (empty($provider_key) || empty($username) || empty($password)) {
    echo json_encode([
        'success' => false,
        'message' => 'SMART API credentials are not properly configured. Please check System Settings.'
    ]);
    exit();
}

/**
 * Generate OAuth Token
 */
function generateToken($api_url, $provider_key, $username, $password, $client_id = null, $client_secret = null) {
    $token_url = $api_url . '/oauth/token';
    
    $ch = curl_init();
    
    // Prepare headers
    $headers = [
        'provider-key: ' . $provider_key,
        'accept-language: en'
    ];
    
    // Prepare POST data
    $post_data = [
        'grant_type' => 'password',
        'username' => $username,
        'password' => $password
    ];
    
    // Set curl options
    curl_setopt($ch, CURLOPT_URL, $token_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    
    // Add HTTP Basic Auth if client credentials are provided
    if (!empty($client_id) && !empty($client_secret)) {
        curl_setopt($ch, CURLOPT_USERPWD, $client_id . ':' . $client_secret);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    }
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    
    curl_close($ch);
    
    if ($response === false) {
        return [
            'success' => false,
            'message' => 'Connection failed: ' . $curl_error,
            'http_code' => 0
        ];
    }
    
    $response_data = json_decode($response, true);
    
    return [
        'success' => $http_code === 200,
        'message' => $http_code === 200 ? 'Token generated successfully' : ($response_data['error_description'] ?? 'Token generation failed'),
        'http_code' => $http_code,
        'data' => $response_data,
        'raw_response' => $response
    ];
}

/**
 * Test server connection
 */
function testServerConnection($api_url) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true); // HEAD request
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    
    curl_close($ch);
    
    if ($response === false) {
        return [
            'success' => false,
            'message' => 'Cannot reach SMART server: ' . $curl_error
        ];
    }
    
    return [
        'success' => true,
        'message' => 'Server is reachable (HTTP ' . $http_code . ')'
    ];
}

/**
 * Test member endpoint
 */
function testMemberEndpoint($api_url, $provider_key, $token) {
    $member_url = $api_url . '/api/member?PatientNumber=TEST001&sessionId=1';
    
    $ch = curl_init();
    
    $headers = [
        'provider-key: ' . $provider_key,
        'Authorization: Bearer ' . $token,
        'accept-language: en'
    ];
    
    curl_setopt($ch, CURLOPT_URL, $member_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    
    curl_close($ch);
    
    if ($response === false) {
        return [
            'success' => false,
            'message' => 'Member endpoint connection failed: ' . $curl_error
        ];
    }
    
    $response_data = json_decode($response, true);
    
    // Even 404 is acceptable as it means the endpoint is accessible
    if ($http_code === 200 || $http_code === 404) {
        return [
            'success' => true,
            'message' => 'Member endpoint is accessible (HTTP ' . $http_code . ')'
        ];
    }
    
    return [
        'success' => false,
        'message' => 'Member endpoint returned HTTP ' . $http_code
    ];
}

/**
 * Test visit endpoint
 */
function testVisitEndpoint($api_url, $provider_key, $token) {
    $visit_url = $api_url . '/api/visit?patientNumber=TEST001&sessionStatus=PENDING';
    
    $ch = curl_init();
    
    $headers = [
        'provider-key: ' . $provider_key,
        'Authorization: Bearer ' . $token,
        'accept-language: en'
    ];
    
    curl_setopt($ch, CURLOPT_URL, $visit_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    
    curl_close($ch);
    
    if ($response === false) {
        return [
            'success' => false,
            'message' => 'Visit endpoint connection failed: ' . $curl_error
        ];
    }
    
    if ($http_code === 200 || $http_code === 404) {
        return [
            'success' => true,
            'message' => 'Visit endpoint is accessible (HTTP ' . $http_code . ')'
        ];
    }
    
    return [
        'success' => false,
        'message' => 'Visit endpoint returned HTTP ' . $http_code
    ];
}

/**
 * Test benefits endpoint (SBB rules)
 */
function testBenefitsEndpoint($api_url, $provider_key, $token) {
    $benefits_url = $api_url . '/api/sbb-rules';
    
    $ch = curl_init();
    
    $headers = [
        'provider-key: ' . $provider_key,
        'Authorization: Bearer ' . $token,
        'accept-language: en',
        'Content-Type: application/json'
    ];
    
    // Sample payload
    $payload = json_encode([
        'items' => [
            [
                'item_net_amount' => 100,
                'pool_number' => 1,
                'provider_item_code' => 'TEST001'
            ]
        ],
        'medical_aid_code' => 'TEST',
        'medical_aid_number' => 'TEST001',
        'medical_aid_plan' => 'TEST.PLAN',
        'policy_id' => 'TEST001'
    ]);
    
    curl_setopt($ch, CURLOPT_URL, $benefits_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    
    curl_close($ch);
    
    if ($response === false) {
        return [
            'success' => false,
            'message' => 'Benefits endpoint connection failed: ' . $curl_error
        ];
    }
    
    // 400 or 404 is acceptable as test data might not exist
    if ($http_code === 200 || $http_code === 400 || $http_code === 404) {
        return [
            'success' => true,
            'message' => 'Benefits endpoint is accessible (HTTP ' . $http_code . ')'
        ];
    }
    
    return [
        'success' => false,
        'message' => 'Benefits endpoint returned HTTP ' . $http_code
    ];
}

// Handle different test types
switch ($test_type) {
    case 'server':
        $result = testServerConnection($api_url);
        echo json_encode($result);
        break;
        
    case 'auth':
        $result = generateToken($api_url, $provider_key, $username, $password, $client_id, $client_secret);
        
        if ($result['success']) {
            // Store token in session for subsequent tests
            $_SESSION['smart_test_token'] = $result['data']['access_token'] ?? '';
            $_SESSION['smart_test_token_expires'] = time() + ($result['data']['expires_in'] ?? 3600);
            
            echo json_encode([
                'success' => true,
                'message' => 'Authentication successful. Token generated and expires in ' . ($result['data']['expires_in'] ?? 'unknown') . ' seconds.',
                'token_type' => $result['data']['token_type'] ?? 'bearer',
                'expires_in' => $result['data']['expires_in'] ?? null
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => $result['message'] . ' (HTTP ' . $result['http_code'] . ')'
            ]);
        }
        break;
        
    case 'member':
        // First ensure we have a valid token
        if (!isset($_SESSION['smart_test_token']) || time() > ($_SESSION['smart_test_token_expires'] ?? 0)) {
            $token_result = generateToken($api_url, $provider_key, $username, $password, $client_id, $client_secret);
            if (!$token_result['success']) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to generate token for member test'
                ]);
                exit();
            }
            $_SESSION['smart_test_token'] = $token_result['data']['access_token'] ?? '';
            $_SESSION['smart_test_token_expires'] = time() + ($token_result['data']['expires_in'] ?? 3600);
        }
        
        $result = testMemberEndpoint($api_url, $provider_key, $_SESSION['smart_test_token']);
        echo json_encode($result);
        break;
        
    case 'visit':
        // First ensure we have a valid token
        if (!isset($_SESSION['smart_test_token']) || time() > ($_SESSION['smart_test_token_expires'] ?? 0)) {
            $token_result = generateToken($api_url, $provider_key, $username, $password, $client_id, $client_secret);
            if (!$token_result['success']) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to generate token for visit test'
                ]);
                exit();
            }
            $_SESSION['smart_test_token'] = $token_result['data']['access_token'] ?? '';
            $_SESSION['smart_test_token_expires'] = time() + ($token_result['data']['expires_in'] ?? 3600);
        }
        
        $result = testVisitEndpoint($api_url, $provider_key, $_SESSION['smart_test_token']);
        echo json_encode($result);
        break;
        
    case 'benefits':
        // First ensure we have a valid token
        if (!isset($_SESSION['smart_test_token']) || time() > ($_SESSION['smart_test_token_expires'] ?? 0)) {
            $token_result = generateToken($api_url, $provider_key, $username, $password, $client_id, $client_secret);
            if (!$token_result['success']) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Failed to generate token for benefits test'
                ]);
                exit();
            }
            $_SESSION['smart_test_token'] = $token_result['data']['access_token'] ?? '';
            $_SESSION['smart_test_token_expires'] = time() + ($token_result['data']['expires_in'] ?? 3600);
        }
        
        $result = testBenefitsEndpoint($api_url, $provider_key, $_SESSION['smart_test_token']);
        echo json_encode($result);
        break;
        
    case 'latency':
        $start = microtime(true);
        $result = testServerConnection($api_url);
        $duration = (microtime(true) - $start) * 1000; // Convert to milliseconds
        
        echo json_encode([
            'success' => $result['success'],
            'message' => 'Latency: ' . round($duration, 2) . 'ms',
            'latency' => round($duration, 2)
        ]);
        break;
        
    default:
        echo json_encode([
            'success' => false,
            'message' => 'Invalid test type specified'
        ]);
        break;
}
?>