<?php
// api/test_smart_connection.php
session_start();
require_once '../layouts/dbconn.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Get SMART settings from database or POST data
function getSmartSettings($conn) {
    $settings = [];
    
    // Check if we're saving new settings (POST data takes precedence)
    if (!empty($_POST['smart_provider_key'])) {
        $settings['provider_key'] = $_POST['smart_provider_key'];
        $settings['api_url'] = $_POST['smart_api_url'];
        $settings['username'] = $_POST['smart_username'];
        $settings['password'] = $_POST['smart_password'];
        $settings['accept_language'] = $_POST['smart_accept_language'] ?? 'en';
        $settings['environment'] = $_POST['smart_environment'] ?? 'development';
    } else {
        // Fetch from database
        $sql = "SELECT setting_key, setting_value FROM system_settings WHERE category = 'smart'";
        $result = $conn->query($sql);
        
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $key = str_replace('smart_', '', $row['setting_key']);
                $settings[$key] = $row['setting_value'];
            }
        }
        
        // Set defaults if not found
        if (empty($settings)) {
            $settings = [
                'provider_key' => 'SKSP_6122',
                'api_url' => 'https://data.smartapplicationsgroup.com/providerapi-dev',
                'username' => 'ecare',
                'password' => 'P@S5W00rd',
                'accept_language' => 'en',
                'environment' => 'development'
            ];
        }
    }
    
    return $settings;
}

$settings = getSmartSettings($conn);

// Validate required settings
if (empty($settings['provider_key']) || empty($settings['username']) || empty($settings['password'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Missing required SMART credentials. Please configure settings first.'
    ]);
    exit();
}

// Test SMART API connection
testSmartConnection($settings);

function testSmartConnection($settings) {
    try {
        $tokenUrl = rtrim($settings['api_url'], '/') . '/oauth/token';
        
        // Prepare POST data exactly as in Postman
        $postData = http_build_query([
            'grant_type' => 'password',
            'username' => $settings['username'],
            'password' => $settings['password']
        ]);
        
        // Initialize cURL
        $ch = curl_init($tokenUrl);
        
        // Set cURL options to match Postman collection exactly
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $postData,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_HTTPHEADER => [
                'provider-key: ' . $settings['provider_key'],
                'accept-language: ' . ($settings['accept_language'] ?? 'en'),
                'Content-Type: application/x-www-form-urlencoded'
            ],
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_USERPWD => $settings['username'] . ':' . $settings['password'],
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 3
        ]);
        
        // Execute request
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        $curlErrno = curl_errno($ch);
        $curlInfo = curl_getinfo($ch);
        
        curl_close($ch);
        
        // Handle cURL errors
        if ($curlError) {
            echo json_encode([
                'success' => false,
                'message' => 'Connection failed: ' . $curlError,
                'details' => [
                    'error_type' => 'CONNECTION_ERROR',
                    'error_code' => $curlErrno,
                    'error_message' => $curlError,
                    'suggestion' => getCurlErrorSuggestion($curlErrno)
                ]
            ]);
            return;
        }
        
        // Parse response
        $responseData = json_decode($response, true);
        
        // Handle successful token generation
        if ($httpCode === 200 && isset($responseData['access_token'])) {
            // Store token in session
            $_SESSION['smart_access_token'] = $responseData['access_token'];
            $_SESSION['smart_token_expires'] = time() + ($responseData['expires_in'] ?? 3600);
            $_SESSION['smart_provider_key'] = $settings['provider_key'];
            
            echo json_encode([
                'success' => true,
                'message' => 'Successfully connected to SMART Health Systems API',
                'details' => [
                    'environment' => $settings['environment'],
                    'provider_key' => $settings['provider_key'],
                    'token_type' => $responseData['token_type'] ?? 'bearer',
                    'expires_in' => $responseData['expires_in'] ?? 3600,
                    'token_preview' => substr($responseData['access_token'], 0, 20) . '...',
                    'api_version' => 'v1',
                    'endpoint_url' => $tokenUrl,
                    'http_code' => $httpCode,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);
            
        // Handle HTTP errors
        } elseif ($httpCode === 401) {
            echo json_encode([
                'success' => false,
                'message' => 'Authentication failed: Invalid credentials',
                'details' => [
                    'http_code' => $httpCode,
                    'error' => 'Unauthorized',
                    'provider_key' => $settings['provider_key'],
                    'username' => $settings['username'],
                    'endpoint' => $tokenUrl,
                    'suggestion' => 'Please verify your Provider Key, Username, and Password are correct. Check if you\'re using SKSP_3194 (not SKSP_6122).'
                ]
            ]);
            
        } elseif ($httpCode === 404) {
            echo json_encode([
                'success' => false,
                'message' => 'API endpoint not found',
                'details' => [
                    'http_code' => $httpCode,
                    'endpoint' => $tokenUrl,
                    'suggestion' => 'Verify the API URL is correct. Sandbox should be: https://data.smartapplicationsgroup.com/providerapi-dev'
                ]
            ]);
            
        } elseif ($httpCode === 0) {
            echo json_encode([
                'success' => false,
                'message' => 'Unable to connect to SMART API server',
                'details' => [
                    'http_code' => $httpCode,
                    'error' => 'Connection timeout or DNS failure',
                    'suggestion' => 'Check your internet connection and verify the API URL. The server might be down or unreachable from your location.'
                ]
            ]);
            
        } else {
            // Other HTTP errors
            echo json_encode([
                'success' => false,
                'message' => 'Unexpected API response: HTTP ' . $httpCode,
                'details' => [
                    'http_code' => $httpCode,
                    'response' => $responseData ?? substr($response, 0, 500),
                    'endpoint' => $tokenUrl,
                    'suggestion' => 'Check SMART API documentation or contact support.'
                ]
            ]);
        }
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Connection test failed: ' . $e->getMessage(),
            'details' => [
                'error_type' => 'EXCEPTION',
                'error_message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]
        ]);
    }
}

function getCurlErrorSuggestion($errno) {
    $suggestions = [
        6 => 'Could not resolve host. Check your DNS settings and verify the API URL.',
        7 => 'Failed to connect to host. Check if the server is running and accessible.',
        28 => 'Connection timeout. The server took too long to respond.',
        35 => 'SSL/TLS handshake failed. Check SSL certificates.',
        51 => 'SSL certificate problem. The server\'s SSL certificate is not trusted.',
        52 => 'Empty response from server.',
        56 => 'Connection reset by peer. Network connection was lost.',
        60 => 'SSL certificate problem: unable to get local issuer certificate.'
    ];
    
    return $suggestions[$errno] ?? 'Connection error occurred. Error code: ' . $errno;
}
?>