<?php
/**
 * Test SMART API Connection
 * Quick connection test from system settings
 */
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();
}

try {
    // Get settings from POST (unsaved settings being tested)
    $environment = $_POST['smart_environment'] ?? 'development';
    $api_url = $_POST['smart_api_url'] ?? 'https://data.smartapplicationsgroup.com/providerapi-dev';
    $provider_key = $_POST['smart_provider_key'] ?? 'SKSP_3194';
    $username = $_POST['smart_username'] ?? 'ecare';
    $password = $_POST['smart_password'] ?? 'P@S5W00rd';
    $client_id = $_POST['smart_client_id'] ?? '';
    $client_secret = $_POST['smart_client_secret'] ?? '';
    $accept_language = $_POST['smart_accept_language'] ?? 'en';
    
    // Validate required fields
    if (empty($api_url) || empty($provider_key) || empty($username) || empty($password)) {
        echo json_encode([
            'success' => false,
            'message' => 'Missing required SMART API credentials. Please fill in all required fields.'
        ]);
        exit();
    }
    
    // Test token generation
    $token_url = rtrim($api_url, '/') . '/oauth/token';
    
    $ch = curl_init();
    
    // Prepare headers
    $headers = [
        'provider-key: ' . $provider_key,
        'accept-language: ' . $accept_language
    ];
    
    // Prepare POST data for OAuth token
    $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);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 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);
    }
    
    // Execute request
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    $curl_errno = curl_errno($ch);
    
    curl_close($ch);
    
    // Handle connection errors
    if ($curl_errno !== 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Connection failed: ' . $curl_error . ' (Error code: ' . $curl_errno . ')'
        ]);
        exit();
    }
    
    // Check if we got a response
    if (empty($response)) {
        echo json_encode([
            'success' => false,
            'message' => 'Empty response from SMART API server (HTTP ' . $http_code . ')'
        ]);
        exit();
    }
    
    // Try to decode JSON response
    $response_data = json_decode($response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid JSON response from server. HTTP Code: ' . $http_code . '. Response: ' . substr($response, 0, 200)
        ]);
        exit();
    }
    
    // Check HTTP status code
    if ($http_code === 200) {
        // Success - token generated
        $token_type = $response_data['token_type'] ?? 'bearer';
        $expires_in = $response_data['expires_in'] ?? 'unknown';
        $access_token = $response_data['access_token'] ?? '';
        
        if (!empty($access_token)) {
            echo json_encode([
                'success' => true,
                'message' => 'Connection successful! Access token generated.',
                'details' => [
                    'environment' => $environment,
                    'api_url' => $api_url,
                    'provider_key' => $provider_key,
                    'token_type' => $token_type,
                    'expires_in' => $expires_in . ' seconds',
                    'http_code' => $http_code
                ]
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Token generated but access_token is empty. Response: ' . json_encode($response_data)
            ]);
        }
    } elseif ($http_code === 401) {
        // Authentication failed
        $error_description = $response_data['error_description'] ?? $response_data['message'] ?? 'Invalid credentials';
        echo json_encode([
            'success' => false,
            'message' => 'Authentication failed: ' . $error_description . ' (HTTP 401)'
        ]);
    } elseif ($http_code === 400) {
        // Bad request
        $error_description = $response_data['error_description'] ?? $response_data['message'] ?? 'Bad request';
        echo json_encode([
            'success' => false,
            'message' => 'Bad request: ' . $error_description . ' (HTTP 400)'
        ]);
    } elseif ($http_code === 404) {
        // Not found
        echo json_encode([
            'success' => false,
            'message' => 'API endpoint not found. Please check the API URL. (HTTP 404)'
        ]);
    } elseif ($http_code === 500 || $http_code === 502 || $http_code === 503) {
        // Server error
        echo json_encode([
            'success' => false,
            'message' => 'SMART server error (HTTP ' . $http_code . '). The server may be temporarily unavailable.'
        ]);
    } else {
        // Other HTTP errors
        $error_message = $response_data['error_description'] ?? $response_data['message'] ?? 'Unknown error';
        echo json_encode([
            'success' => false,
            'message' => 'HTTP ' . $http_code . ': ' . $error_message
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Exception: ' . $e->getMessage()
    ]);
}
?>