<?php
/**
 * Advanced Government API Diagnostic Tool
 * Tests different header formats and request structures
 * 
 * Usage: Access via browser or POST with invoice_id parameter
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Database connection
$host = 'localhost';
$dbname = 'jopython24_posf';
$username = 'jopython24_posf';
$password = '@*^0l+]HXGklo79M';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die(json_encode(['error' => 'Database connection failed: ' . $e->getMessage()]));
}

$result = [
    'success' => true,
    'timestamp' => date('Y-m-d H:i:s'),
    'tests' => []
];

// Get invoice to test
$invoiceId = $_GET['invoice_id'] ?? $_POST['invoice_id'] ?? null;

if (!$invoiceId) {
    // Get most recent invoice with xml_base64
    $stmt = $pdo->query("SELECT id, invoice_number, seller_id, xml_base64 FROM invoices WHERE xml_base64 IS NOT NULL AND xml_base64 != '' ORDER BY created_at DESC LIMIT 1");
    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$invoice) {
        $result['error'] = 'No invoices with XML data found';
        $result['suggestion'] = 'Create an invoice first, then run this diagnostic';
        echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit();
    }
    $invoiceId = $invoice['id'];
} else {
    $stmt = $pdo->prepare("SELECT id, invoice_number, seller_id, xml_base64 FROM invoices WHERE id = ?");
    $stmt->execute([$invoiceId]);
    $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$invoice) {
        $result['error'] = 'Invoice not found';
        echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit();
    }
}

$result['invoice_info'] = [
    'id' => $invoice['id'],
    'invoice_number' => $invoice['invoice_number'],
    'seller_id' => $invoice['seller_id'],
    'xml_base64_length' => strlen($invoice['xml_base64'] ?? '')
];

// Get seller credentials
$stmt = $pdo->prepare("SELECT id, seller_name, client_id, secret_key, tax_number, income_number FROM sellers WHERE id = ?");
$stmt->execute([$invoice['seller_id']]);
$seller = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$seller) {
    $result['error'] = 'Seller not found for invoice';
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit();
}

$result['seller_info'] = [
    'id' => $seller['id'],
    'seller_name' => $seller['seller_name'],
    'tax_number' => $seller['tax_number'],
    'income_number' => $seller['income_number'],
    'client_id_preview' => substr($seller['client_id'], 0, 20) . '...',
    'client_id_length' => strlen($seller['client_id']),
    'secret_key_length' => strlen($seller['secret_key'])
];

$apiUrl = 'https://backend.jofotara.gov.jo/core/invoices/';
$xmlBase64 = $invoice['xml_base64'];

// Decode and check XML content
$decodedXml = base64_decode($xmlBase64);
$result['xml_analysis'] = [
    'decoded_length' => strlen($decodedXml),
    'starts_with' => substr($decodedXml, 0, 100),
    'contains_invoice_tag' => strpos($decodedXml, '<Invoice') !== false,
    'contains_seller_tax' => strpos($decodedXml, $seller['tax_number']) !== false
];

// Define different header format tests
$headerTests = [
    'Format 1: Client-Id/Secret-Key (Current)' => [
        'Client-Id' => $seller['client_id'],
        'Secret-Key' => $seller['secret_key']
    ],
    'Format 2: client-id/secret-key (lowercase)' => [
        'client-id' => $seller['client_id'],
        'secret-key' => $seller['secret_key']
    ],
    'Format 3: ClientId/SecretKey (camelCase)' => [
        'ClientId' => $seller['client_id'],
        'SecretKey' => $seller['secret_key']
    ],
    'Format 4: CLIENT-ID/SECRET-KEY (uppercase)' => [
        'CLIENT-ID' => $seller['client_id'],
        'SECRET-KEY' => $seller['secret_key']
    ],
    'Format 5: X-Client-Id/X-Secret-Key (X-prefix)' => [
        'X-Client-Id' => $seller['client_id'],
        'X-Secret-Key' => $seller['secret_key']
    ]
];

// Define different body format tests
$bodyTests = [
    'Body 1: {"invoice": "BASE64"}' => json_encode(['invoice' => $xmlBase64]),
    'Body 2: {"Invoice": "BASE64"}' => json_encode(['Invoice' => $xmlBase64]),
    'Body 3: {"xml": "BASE64"}' => json_encode(['xml' => $xmlBase64]),
    'Body 4: {"data": "BASE64"}' => json_encode(['data' => $xmlBase64]),
    'Body 5: {"invoiceData": "BASE64"}' => json_encode(['invoiceData' => $xmlBase64]),
    'Body 6: Raw BASE64 string' => $xmlBase64
];

// Function to test API call
function testApiCall($url, $headers, $body, $bodyFormat) {
    $ch = curl_init();
    
    $httpHeaders = [
        'Content-Type: application/json',
        'Accept: application/json'
    ];
    
    foreach ($headers as $key => $value) {
        $httpHeaders[] = "$key: $value";
    }
    
    // For raw base64, change content type
    if ($bodyFormat === 'Body 6: Raw BASE64 string') {
        $httpHeaders[0] = 'Content-Type: text/plain';
    }
    
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_HTTPHEADER => $httpHeaders,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_VERBOSE => false
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    $totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
    
    curl_close($ch);
    
    return [
        'http_code' => $httpCode,
        'response_length' => strlen($response),
        'response_preview' => substr($response, 0, 500),
        'response_json' => json_decode($response, true),
        'curl_error' => $error,
        'time_seconds' => round($totalTime, 2)
    ];
}

// Quick test mode - test only the first header format with first body format
$quickTest = isset($_GET['quick']) || isset($_POST['quick']);

if ($quickTest) {
    $result['mode'] = 'quick_test';
    
    // Test with most likely correct format based on documentation
    $testHeaders = [
        'Client-Id' => $seller['client_id'],
        'Secret-Key' => $seller['secret_key']
    ];
    $testBody = json_encode(['invoice' => $xmlBase64]);
    
    $result['quick_test_result'] = testApiCall($apiUrl, $testHeaders, $testBody, 'Body 1');
    
} else {
    $result['mode'] = 'full_test';
    $result['warning'] = 'Full test mode - testing multiple header and body formats. This may take a while.';
    
    // Test first header format with all body formats
    $firstHeaderFormat = 'Format 1: Client-Id/Secret-Key (Current)';
    $firstHeaders = $headerTests[$firstHeaderFormat];
    
    $result['header_format_used'] = $firstHeaderFormat;
    $result['body_format_tests'] = [];
    
    foreach ($bodyTests as $bodyName => $body) {
        $result['body_format_tests'][$bodyName] = testApiCall($apiUrl, $firstHeaders, $body, $bodyName);
        
        // If we get a success (200 or 201), note it
        $lastCode = $result['body_format_tests'][$bodyName]['http_code'];
        if ($lastCode === 200 || $lastCode === 201) {
            $result['success_found'] = [
                'header_format' => $firstHeaderFormat,
                'body_format' => $bodyName
            ];
            break;
        }
        
        // Small delay between requests
        usleep(500000); // 0.5 second
    }
    
    // If no success with body formats, test different header formats with first body
    if (!isset($result['success_found'])) {
        $result['header_format_tests'] = [];
        $firstBody = $bodyTests['Body 1: {"invoice": "BASE64"}'];
        
        foreach ($headerTests as $headerName => $headers) {
            if ($headerName === $firstHeaderFormat) continue; // Skip already tested
            
            $result['header_format_tests'][$headerName] = testApiCall($apiUrl, $headers, $firstBody, 'Body 1');
            
            $lastCode = $result['header_format_tests'][$headerName]['http_code'];
            if ($lastCode === 200 || $lastCode === 201) {
                $result['success_found'] = [
                    'header_format' => $headerName,
                    'body_format' => 'Body 1: {"invoice": "BASE64"}'
                ];
                break;
            }
            
            usleep(500000);
        }
    }
}

// Add recommendations based on results
$result['recommendations'] = [];

if (isset($result['success_found'])) {
    $result['recommendations'][] = "✅ SUCCESS! Use header format: " . $result['success_found']['header_format'];
    $result['recommendations'][] = "✅ SUCCESS! Use body format: " . $result['success_found']['body_format'];
} else {
    $result['recommendations'][] = "❌ All tested formats returned errors";
    $result['recommendations'][] = "Check if credentials are registered at jofotara.gov.jo";
    $result['recommendations'][] = "Verify XML structure matches government requirements";
    $result['recommendations'][] = "Contact government support if credentials are correct";
}

// Add debug info for 403 errors
$allCodes = [];
if (isset($result['body_format_tests'])) {
    foreach ($result['body_format_tests'] as $test) {
        $allCodes[] = $test['http_code'];
    }
}
if (isset($result['header_format_tests'])) {
    foreach ($result['header_format_tests'] as $test) {
        $allCodes[] = $test['http_code'];
    }
}

if (in_array(403, $allCodes)) {
    $result['http_403_analysis'] = [
        'meaning' => 'HTTP 403 Forbidden - Server understood request but refuses to authorize',
        'possible_causes' => [
            '1. Invalid or expired credentials (client_id/secret_key)',
            '2. Credentials not registered with government system',
            '3. Account suspended or inactive',
            '4. IP address not whitelisted (if applicable)',
            '5. Tax number mismatch between credentials and XML'
        ],
        'suggested_actions' => [
            '1. Verify credentials at https://portal.jofotara.gov.jo',
            '2. Check if seller account is active',
            '3. Ensure tax_number in sellers table matches registered number',
            '4. Try regenerating credentials from government portal'
        ]
    ];
}

echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
