<?php
/**
 * eTIMS Integration Test Connection
 * Tests connection to Kenya Revenue Authority eTIMS API
 * File: api/test_etims_connection.php
 */

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

// Check if user is authorized
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit();
}

// Get form data
$environment = $_POST['etims_environment'] ?? 'sandbox';
$tin = $_POST['etims_tin'] ?? '';
$device_serial = $_POST['etims_device_serial'] ?? '';
$api_key = $_POST['etims_api_key'] ?? '';
$branch_code = $_POST['etims_branch_code'] ?? '00';

// Validate required fields
if (empty($api_key)) {
    echo json_encode([
        'success' => false,
        'message' => 'API Key is required'
    ]);
    exit();
}

// Set API URL based on environment
if ($environment === 'sandbox') {
    // Try multiple possible sandbox URLs
    $possible_urls = [
        'http://62.169.23.132:4125/api/invoice/process',
        'https://sbx.etims.kra.go.ke/api',
        'https://sandbox.etims.kra.go.ke/api'
    ];
    $base_url = $possible_urls[0]; // Default to first URL
    
    // Use sandbox credentials if not provided
    if (empty($tin)) $tin = 'P051430004F';
    if (empty($api_key)) $api_key = 'etims-fc-2026-secure-api-key-9yrtrcy54s';
    if (empty($branch_code)) $branch_code = '00';
} else {
    // Production URL
    $base_url = 'https://etims.kra.go.ke/api';
}

try {
    // Test 1: Health Check Endpoint
    $health_url = $base_url . '/health';
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $health_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    if ($curl_error) {
        echo json_encode([
            'success' => false,
            'message' => 'eTIMS Sandbox Currently Unavailable',
            'details' => [
                'error' => $curl_error,
                'url' => $base_url,
                'note' => 'The eTIMS sandbox server appears to be offline. This is common with test environments.'
            ],
            'recommendation' => 'Enable Mock Mode in System Settings to continue development.'
        ]);
        exit();
    }
    
    if ($http_code !== 200) {
        echo json_encode([
            'success' => false,
            'message' => 'eTIMS Health Check Failed',
            'http_code' => $http_code
        ]);
        exit();
    }
    
    // Test 2: Try to register a test item
    $test_url = $base_url . '/api/items/register-json';
    
    $test_data = [
        'businessPin' => $tin,
        'branchId' => $branch_code,
        'Items' => 1,
        'ItemsList' => [
            [
                'itemName' => 'Test Item',
                'ClassCode' => '50101502',
                'itemCd' => 'TEST-001',
                'ItemType' => '2',
                'UnitOfQuantity' => 'U',
                'PackagingUnit' => 'NT',
                'SellingPrice' => 100.00,
                'TaxationType' => 'B',
                'OpeningStock' => 0
            ]
        ]
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $test_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($test_data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-API-Key: ' . $api_key
        ],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);
    
    // Check for cURL errors
    if ($curl_error) {
        echo json_encode([
            'success' => false,
            'message' => 'Connection failed: ' . $curl_error
        ]);
        exit();
    }
    
    // Check HTTP response code
    if ($http_code !== 200) {
        echo json_encode([
            'success' => false,
            'message' => 'HTTP Error ' . $http_code . ': Unable to connect to eTIMS API',
            'http_code' => $http_code
        ]);
        exit();
    }
    
    // Parse response
    $result = json_decode($response, true);
    
    if ($result === null) {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid JSON response from eTIMS API',
            'raw_response' => substr($response, 0, 500)
        ]);
        exit();
    }
    
    // Check eTIMS result
    if (isset($result['success']) && $result['success']) {
        // Success
        $details = [
            'environment' => $environment,
            'business_pin' => $tin,
            'branch_id' => $branch_code,
            'connection_status' => 'Connected',
            'health_check' => 'Passed'
        ];
        
        echo json_encode([
            'success' => true,
            'message' => 'eTIMS connection successful! API is responding.',
            'details' => $details,
            'result_message' => $result['message'] ?? 'Success'
        ]);
        
    } else {
        // eTIMS returned an error
        $error_message = $result['message'] ?? 'Unknown error occurred';
        
        echo json_encode([
            'success' => false,
            'message' => 'eTIMS Error: ' . $error_message,
            'error_details' => $result
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Exception: ' . $e->getMessage()
    ]);
}
?>