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

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

// SMART API Configuration
define('SMART_BASE_URL', 'https://data.smartapplicationsgroup.com/providerapi-dev');
define('SMART_PROVIDER_KEY', 'SKSP_3194'); // Replace with your actual provider key
define('SMART_USERNAME', 'ecare'); // Replace with your actual username
define('SMART_PASSWORD', 'P@S5W00rd'); // Replace with your actual password

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'test_connection') {
        testSmartConnection();
    }
}

function testSmartConnection() {
    try {
        // Prepare the OAuth2 token request
        $tokenUrl = SMART_BASE_URL . '/oauth/token';
        
        $postData = [
            'grant_type' => 'password',
            'username' => SMART_USERNAME,
            'password' => SMART_PASSWORD
        ];
        
        // Initialize cURL
        $ch = curl_init($tokenUrl);
        
        // Set cURL options
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($postData),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_HTTPHEADER => [
                'provider-key: ' . SMART_PROVIDER_KEY,
                'accept-language: en'
            ],
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_USERPWD => SMART_USERNAME . ':' . SMART_PASSWORD,
            CURLOPT_TIMEOUT => 30
        ]);
        
        // Execute request
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        // Check for cURL errors
        if ($curlError) {
            echo json_encode([
                'success' => false,
                'message' => 'Connection failed: ' . $curlError,
                'details' => [
                    'error_type' => 'CURL_ERROR',
                    'error' => $curlError
                ]
            ]);
            return;
        }
        
        // Decode response
        $responseData = json_decode($response, true);
        
        // Check HTTP status code
        if ($httpCode === 200) {
            // Successful connection
            if (isset($responseData['access_token'])) {
                // Store token in session for potential use
                $_SESSION['smart_access_token'] = $responseData['access_token'];
                $_SESSION['smart_token_expires'] = time() + ($responseData['expires_in'] ?? 3600);
                
                echo json_encode([
                    'success' => true,
                    'message' => 'Successfully connected to SMART Health Systems API',
                    'details' => [
                        'http_code' => $httpCode,
                        'token_type' => $responseData['token_type'] ?? 'bearer',
                        'expires_in' => $responseData['expires_in'] ?? 'unknown',
                        'token_preview' => substr($responseData['access_token'], 0, 20) . '...',
                        'timestamp' => date('Y-m-d H:i:s')
                    ]
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Unexpected response format from API',
                    'details' => [
                        'http_code' => $httpCode,
                        'response' => $responseData
                    ]
                ]);
            }
        } elseif ($httpCode === 401) {
            echo json_encode([
                'success' => false,
                'message' => 'Authentication failed: Invalid credentials or provider key',
                'details' => [
                    'http_code' => $httpCode,
                    'error' => $responseData['error'] ?? 'Unauthorized',
                    'error_description' => $responseData['error_description'] ?? 'Invalid username, password, or provider key'
                ]
            ]);
        } elseif ($httpCode === 404) {
            echo json_encode([
                'success' => false,
                'message' => 'API endpoint not found',
                'details' => [
                    'http_code' => $httpCode,
                    'error' => 'The requested API endpoint does not exist',
                    'endpoint' => SMART_BASE_URL . '/oauth/token'
                ]
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'API request failed with HTTP code: ' . $httpCode,
                'details' => [
                    'http_code' => $httpCode,
                    'response' => $responseData,
                    'raw_response' => $response
                ]
            ]);
        }
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Connection test failed: ' . $e->getMessage(),
            'details' => [
                'error_type' => 'EXCEPTION',
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]
        ]);
    }
}
?>