<?php
/**
 * Comprehensive eTIMS API Test
 * Matches the Postman collection format exactly
 * File: test_etims_comprehensive.php
 */

$config = [
    'base_url' => 'http://62.169.23.132:4122',
    'api_key' => 'etims-fc-2025-secure-api-key-9ffhksorghjlys',
    'business_pin' => 'P052077586R',
    'branch_id' => '00'
];

?>
<!DOCTYPE html>
<html>
<head>
    <title>eTIMS API Comprehensive Test</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; }
        .test-card { background: white; padding: 20px; margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .test-card h3 { margin-top: 0; color: #333; border-bottom: 2px solid #4CAF50; padding-bottom: 10px; }
        .success { color: #4CAF50; font-weight: bold; }
        .error { color: #f44336; font-weight: bold; }
        .warning { color: #ff9800; font-weight: bold; }
        pre { background: #f9f9f9; padding: 15px; border-radius: 4px; overflow-x: auto; border-left: 4px solid #4CAF50; }
        .btn { padding: 10px 20px; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }
        .btn:hover { background: #45a049; }
        .btn-secondary { background: #2196F3; }
        .btn-secondary:hover { background: #0b7dda; }
        .status-badge { padding: 5px 10px; border-radius: 4px; display: inline-block; margin-left: 10px; }
        .status-online { background: #4CAF50; color: white; }
        .status-offline { background: #f44336; color: white; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🧪 eTIMS API Comprehensive Test Suite</h1>
        <p><strong>Base URL:</strong> <?php echo $config['base_url']; ?></p>
        <p><strong>Business PIN:</strong> <?php echo $config['business_pin']; ?></p>
        
        <?php
        // Test 1: Health Check
        echo '<div class="test-card">';
        echo '<h3>Test 1: Health Check</h3>';
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $config['base_url'] . '/health',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => false
        ]);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            echo '<p class="error">❌ FAILED: ' . $error . '</p>';
            echo '<p class="warning">⚠️ eTIMS sandbox is currently offline. Enable Mock Mode to continue development.</p>';
        } elseif ($http_code == 200) {
            echo '<p class="success">✅ PASSED <span class="status-badge status-online">API Online</span></p>';
            echo '<pre>' . json_encode(json_decode($response), JSON_PRETTY_PRINT) . '</pre>';
        } else {
            echo '<p class="error">❌ FAILED: HTTP ' . $http_code . '</p>';
        }
        echo '</div>';
        
        // Test 2: Register Items (only if health check passed)
        if (empty($error) && $http_code == 200) {
            echo '<div class="test-card">';
            echo '<h3>Test 2: Register Items</h3>';
            
            $data = [
                'businessPin' => $config['business_pin'],
                'branchId' => $config['branch_id'],
                'Items' => 2,
                'ItemsList' => [
                    [
                        'itemName' => 'ENT Consultation',
                        'ClassCode' => '50101502',
                        'itemCd' => 'ENT-TEST-001',
                        'ItemType' => '2',
                        'UnitOfQuantity' => 'U',
                        'PackagingUnit' => 'NT',
                        'SellingPrice' => 3000.00,
                        'TaxationType' => 'B',
                        'OpeningStock' => 0
                    ],
                    [
                        'itemName' => 'Audiometry Test',
                        'ClassCode' => '51101500',
                        'itemCd' => 'ENT-TEST-002',
                        'ItemType' => '2',
                        'UnitOfQuantity' => 'U',
                        'PackagingUnit' => 'NT',
                        'SellingPrice' => 2000.00,
                        'TaxationType' => 'B',
                        'OpeningStock' => 0
                    ]
                ]
            ];
            
            echo '<p><strong>Request:</strong></p>';
            echo '<pre>' . json_encode($data, JSON_PRETTY_PRINT) . '</pre>';
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $config['base_url'] . '/api/items/register-json',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'X-API-Key: ' . $config['api_key']
                ],
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => false
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            echo '<p><strong>Response:</strong></p>';
            if ($error) {
                echo '<p class="error">❌ FAILED: ' . $error . '</p>';
            } elseif ($http_code == 200) {
                echo '<p class="success">✅ PASSED</p>';
                echo '<pre>' . json_encode(json_decode($response), JSON_PRETTY_PRINT) . '</pre>';
            } else {
                echo '<p class="error">❌ FAILED: HTTP ' . $http_code . '</p>';
                echo '<pre>' . htmlspecialchars($response) . '</pre>';
            }
            echo '</div>';
            
            // Test 3: Submit Sales Invoice
            echo '<div class="test-card">';
            echo '<h3>Test 3: Submit Sales Invoice</h3>';
            
            $invoice_number = rand(5001, 9999);
            $data = [
                'businessPin' => $config['business_pin'],
                'branchId' => $config['branch_id'],
                'invoiceNumber' => $invoice_number,
                'traderInvoiceNo' => 'TRD-' . $invoice_number,
                'customer' => [
                    'name' => 'Test Patient',
                    'pin' => 'A001234567X',
                    'mobile' => '254712345678',
                    'address' => 'Nairobi'
                ],
                'items' => [
                    [
                        'itemCode' => 'ENT-TEST-001',
                        'itemClassCode' => '50101502',
                        'itemName' => 'ENT Consultation',
                        'quantity' => 1,
                        'price' => 3240.00,
                        'taxType' => 'B'
                    ]
                ],
                'paymentInfo' => [
                    'amountPaid' => 3240.00,
                    'changeGiven' => 0.00,
                    'paymentModes' => [
                        [
                            'mode' => 'Cash',
                            'amount' => 3240.00
                        ]
                    ]
                ],
                'remark' => 'Tax Invoice'
            ];
            
            echo '<p><strong>Request:</strong></p>';
            echo '<pre>' . json_encode($data, JSON_PRETTY_PRINT) . '</pre>';
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $config['base_url'] . '/api/invoice/process',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => json_encode($data),
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'X-API-Key: ' . $config['api_key']
                ],
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => false
            ]);
            
            $response = curl_exec($ch);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);
            
            echo '<p><strong>Response:</strong></p>';
            if ($error) {
                echo '<p class="error">❌ FAILED: ' . $error . '</p>';
            } elseif ($http_code == 200) {
                echo '<p class="success">✅ PASSED</p>';
                $result = json_decode($response, true);
                echo '<pre>' . json_encode($result, JSON_PRETTY_PRINT) . '</pre>';
                
                if (isset($result['data']['receiptSignature'])) {
                    echo '<div style="background: #e8f5e9; padding: 15px; border-radius: 4px; margin-top: 10px;">';
                    echo '<h4>📜 Receipt Details:</h4>';
                    echo '<p><strong>Invoice Number:</strong> ' . $result['data']['invoiceNumber'] . '</p>';
                    echo '<p><strong>Receipt Signature:</strong> ' . substr($result['data']['receiptSignature'], 0, 50) . '...</p>';
                    echo '<p><strong>CU Serial:</strong> ' . $result['data']['cuSerial'] . '</p>';
                    echo '</div>';
                }
            } else {
                echo '<p class="error">❌ FAILED: HTTP ' . $http_code . '</p>';
                echo '<pre>' . htmlspecialchars($response) . '</pre>';
            }
            echo '</div>';
            
            // Test 4: Submit Credit Note
            if (isset($invoice_number)) {
                echo '<div class="test-card">';
                echo '<h3>Test 4: Submit Credit Note</h3>';
                
                $credit_note_number = $invoice_number + 1;
                $data = [
                    'businessPin' => $config['business_pin'],
                    'branchId' => $config['branch_id'],
                    'originalInvoiceNumber' => $invoice_number,
                    'creditNoteNumber' => $credit_note_number,
                    'traderInvoiceNo' => 'CN-' . $credit_note_number,
                    'customer' => [
                        'name' => 'Test Patient',
                        'pin' => 'A001234567X',
                        'mobile' => '254712345678',
                        'address' => 'Nairobi'
                    ],
                    'items' => [
                        [
                            'itemCode' => 'ENT-TEST-001',
                            'itemClassCode' => '50101502',
                            'itemName' => 'ENT Consultation',
                            'quantity' => 1,
                            'price' => 3240.00,
                            'taxType' => 'B'
                        ]
                    ],
                    'reason' => 'Refund - Testing'
                ];
                
                echo '<p><strong>Request:</strong></p>';
                echo '<pre>' . json_encode($data, JSON_PRETTY_PRINT) . '</pre>';
                
                $ch = curl_init();
                curl_setopt_array($ch, [
                    CURLOPT_URL => $config['base_url'] . '/api/credit-note/process',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POST => true,
                    CURLOPT_POSTFIELDS => json_encode($data),
                    CURLOPT_HTTPHEADER => [
                        'Content-Type: application/json',
                        'X-API-Key: ' . $config['api_key']
                    ],
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_SSL_VERIFYPEER => false
                ]);
                
                $response = curl_exec($ch);
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $error = curl_error($ch);
                curl_close($ch);
                
                echo '<p><strong>Response:</strong></p>';
                if ($error) {
                    echo '<p class="error">❌ FAILED: ' . $error . '</p>';
                } elseif ($http_code == 200) {
                    echo '<p class="success">✅ PASSED</p>';
                    echo '<pre>' . json_encode(json_decode($response), JSON_PRETTY_PRINT) . '</pre>';
                } else {
                    echo '<p class="error">❌ FAILED: HTTP ' . $http_code . '</p>';
                    echo '<pre>' . htmlspecialchars($response) . '</pre>';
                }
                echo '</div>';
            }
        }
        
        // Summary
        echo '<div class="test-card" style="background: #e3f2fd;">';
        echo '<h3>📊 Test Summary</h3>';
        if (empty($error) && $http_code == 200) {
            echo '<p class="success">✅ eTIMS sandbox is operational!</p>';
            echo '<p>You can now integrate eTIMS into your ENT Hospital Management System.</p>';
            echo '<p><strong>Next Steps:</strong></p>';
            echo '<ul>';
            echo '<li>Go to System Settings → eTIMS Integration</li>';
            echo '<li>Configure your credentials</li>';
            echo '<li>Register your actual services</li>';
            echo '<li>Test with real invoices</li>';
            echo '</ul>';
        } else {
            echo '<p class="error">❌ eTIMS sandbox is currently unavailable</p>';
            echo '<p><strong>Solution:</strong></p>';
            echo '<ol>';
            echo '<li>Go to System Settings → eTIMS Integration</li>';
            echo '<li>Enable <strong>Mock Mode</strong></li>';
            echo '<li>Continue development with simulated responses</li>';
            echo '<li>Disable Mock Mode before going to production</li>';
            echo '</ol>';
            echo '<button class="btn" onclick="location.href=\'system_settings.php\'">Go to Settings</button>';
        }
        echo '</div>';
        ?>
        
        <div class="test-card">
            <h3>🔗 Useful Links</h3>
            <button class="btn btn-secondary" onclick="window.open('http://62.169.23.132:4122/api-docs/', '_blank')">
                📚 View API Documentation (Swagger)
            </button>
            <button class="btn btn-secondary" onclick="location.href='system_settings.php'">
                ⚙️ System Settings
            </button>
            <button class="btn" onclick="location.reload()">
                🔄 Retry Tests
            </button>
        </div>
    </div>
</body>
</html>