<?php
// Comprehensive test file to verify PHP and webhook connectivity
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$results = [
    'success' => true,
    'timestamp' => date('c'),
    'tests' => []
];

// Test 1: PHP Version
$results['tests']['php'] = [
    'status' => 'ok',
    'version' => phpversion(),
    'server' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'
];

// Test 2: cURL Extension
$results['tests']['curl'] = [
    'status' => extension_loaded('curl') ? 'ok' : 'error',
    'message' => extension_loaded('curl') ? 'cURL extension loaded' : 'cURL extension NOT loaded - webhooks will fail!'
];

// Test 3: JSON Extension
$results['tests']['json'] = [
    'status' => extension_loaded('json') ? 'ok' : 'error',
    'message' => extension_loaded('json') ? 'JSON extension loaded' : 'JSON extension NOT loaded'
];

// Test 4: Test webhook connection
if (extension_loaded('curl')) {
    $webhookUrl = 'https://n8n.profice.de/webhook/d94ef798-3f43-46dd-8207-1e335e64518f';
    
    $testData = [
        'type' => 'connection_test',
        'timestamp' => date('c'),
        'source' => 'test.php'
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $webhookUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($testData),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    $errno = curl_errno($ch);
    curl_close($ch);
    
    $results['tests']['webhook'] = [
        'status' => ($httpCode >= 200 && $httpCode < 300) ? 'ok' : 'error',
        'http_code' => $httpCode,
        'url' => $webhookUrl,
        'error' => $error ?: null,
        'error_code' => $errno ?: null,
        'response_preview' => substr($response, 0, 200)
    ];
    
    if ($error) {
        $results['success'] = false;
    }
} else {
    $results['tests']['webhook'] = [
        'status' => 'skipped',
        'message' => 'cURL not available'
    ];
    $results['success'] = false;
}

// Test 5: File permissions
$results['tests']['permissions'] = [
    'status' => is_writable(dirname(__FILE__)) ? 'ok' : 'warning',
    'message' => is_writable(dirname(__FILE__)) ? 'Directory writable' : 'Directory not writable (may affect logging)'
];

echo json_encode($results, JSON_PRETTY_PRINT);
