<?php
/**
 * Comprehensive Diagnostic Tool (JSON Version)
 * فوترة بلس - POS System
 * 
 * Upload to /posf/api/ and visit: https://24.jopython.work/posf/api/diagnose.php
 * Add ?format=html for HTML version
 */

// CRITICAL: Disable error display to ensure clean JSON output
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);

$format = $_GET['format'] ?? 'json';

if ($format === 'html') {
    outputHtmlDiagnostic();
    exit;
}

// JSON Output
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;
}

$results = [
    'timestamp' => date('Y-m-d H:i:s'),
    'server' => [
        'php_version' => PHP_VERSION,
        'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
        'document_root' => $_SERVER['DOCUMENT_ROOT'] ?? 'Unknown',
        'script_path' => __DIR__
    ],
    'checks' => []
];

// 1. PHP Version Check
$results['checks']['php_version'] = [
    'name' => 'PHP Version',
    'status' => version_compare(PHP_VERSION, '7.4', '>=') ? 'OK' : 'FAIL',
    'value' => PHP_VERSION,
    'required' => '7.4+',
    'message' => version_compare(PHP_VERSION, '7.4', '>=') 
        ? 'PHP version is compatible' 
        : 'PHP version too old, requires 7.4+'
];

// 2. CURL Extension Check
$results['checks']['curl'] = [
    'name' => 'CURL Extension',
    'status' => function_exists('curl_init') ? 'OK' : 'FAIL',
    'enabled' => function_exists('curl_init'),
    'message' => function_exists('curl_init') 
        ? 'CURL is enabled' 
        : 'CURL is DISABLED - Required for government API'
];

// 3. JSON Extension Check
$results['checks']['json'] = [
    'name' => 'JSON Extension',
    'status' => function_exists('json_encode') ? 'OK' : 'FAIL',
    'enabled' => function_exists('json_encode'),
    'message' => function_exists('json_encode') 
        ? 'JSON is enabled' 
        : 'JSON is DISABLED - Critical!'
];

// 4. PDO Extension Check
$results['checks']['pdo'] = [
    'name' => 'PDO Extension',
    'status' => class_exists('PDO') ? 'OK' : 'FAIL',
    'enabled' => class_exists('PDO'),
    'drivers' => class_exists('PDO') ? PDO::getAvailableDrivers() : [],
    'message' => class_exists('PDO') 
        ? 'PDO is enabled with drivers: ' . implode(', ', PDO::getAvailableDrivers())
        : 'PDO is DISABLED - Required for database'
];

// 5. API Files Existence Check
$apiFiles = [
    'db.php' => 'Database configuration',
    'auth.php' => 'Authentication handler',
    'auto-crud.php' => 'Universal CRUD engine',
    'government-invoice.php' => 'Government API endpoint',
    'upload.php' => 'File upload handler',
    'invoice-number.php' => 'Invoice number generator',
    'icv.php' => 'ICV counter endpoint',
    '.htaccess' => 'Apache configuration'
];

$results['checks']['files'] = [
    'name' => 'API Files',
    'status' => 'OK',
    'files' => []
];

foreach ($apiFiles as $file => $description) {
    $exists = file_exists(__DIR__ . '/' . $file);
    $readable = is_readable(__DIR__ . '/' . $file);
    $size = $exists ? filesize(__DIR__ . '/' . $file) : 0;
    
    $results['checks']['files']['files'][$file] = [
        'description' => $description,
        'exists' => $exists,
        'readable' => $readable,
        'size' => $size,
        'status' => ($exists && $readable) ? 'OK' : 'FAIL'
    ];
    
    if (!$exists || !$readable) {
        $results['checks']['files']['status'] = 'WARN';
    }
}

// 6. Database Connection Test
$results['checks']['database'] = [
    'name' => 'Database Connection',
    'status' => 'PENDING'
];

try {
    if (file_exists(__DIR__ . '/db.php')) {
        require_once __DIR__ . '/db.php';
        global $pdo;
        
        if ($pdo) {
            $stmt = $pdo->query("SELECT 1 as test");
            $row = $stmt->fetch();
            
            // Get table count
            $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
            
            $results['checks']['database'] = [
                'name' => 'Database Connection',
                'status' => 'OK',
                'connected' => true,
                'tables_count' => count($tables),
                'tables' => $tables,
                'message' => 'Database connected successfully with ' . count($tables) . ' tables'
            ];
        } else {
            $results['checks']['database'] = [
                'name' => 'Database Connection',
                'status' => 'FAIL',
                'connected' => false,
                'message' => 'PDO object not initialized'
            ];
        }
    } else {
        $results['checks']['database'] = [
            'name' => 'Database Connection',
            'status' => 'FAIL',
            'connected' => false,
            'message' => 'db.php file not found'
        ];
    }
} catch (Exception $e) {
    $results['checks']['database'] = [
        'name' => 'Database Connection',
        'status' => 'FAIL',
        'connected' => false,
        'error' => $e->getMessage(),
        'message' => 'Database connection failed: ' . $e->getMessage()
    ];
}

// 7. Government API Connectivity Test
$results['checks']['government_api'] = [
    'name' => 'Government API Connection',
    'status' => 'PENDING'
];

if (function_exists('curl_init')) {
    $ch = curl_init('https://backend.jofotara.gov.jo/core/invoices/');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_NOBODY => true, // HEAD request only
        CURLOPT_HEADER => true
    ]);
    
    $response = curl_exec($ch);
    $error = curl_error($ch);
    $errno = curl_errno($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $connectTime = curl_getinfo($ch, CURLINFO_CONNECT_TIME);
    $totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
    curl_close($ch);
    
    $isConnectable = ($httpCode > 0 || empty($error));
    
    $results['checks']['government_api'] = [
        'name' => 'Government API Connection',
        'status' => $isConnectable ? 'OK' : 'FAIL',
        'url' => 'https://backend.jofotara.gov.jo/core/invoices/',
        'http_code' => $httpCode,
        'connect_time' => round($connectTime, 3) . 's',
        'total_time' => round($totalTime, 3) . 's',
        'curl_error' => $error ?: null,
        'curl_errno' => $errno,
        'message' => $isConnectable 
            ? "Government API reachable (HTTP $httpCode in {$totalTime}s)"
            : "Cannot connect to government API: $error"
    ];
} else {
    $results['checks']['government_api'] = [
        'name' => 'Government API Connection',
        'status' => 'SKIP',
        'message' => 'CURL not available - cannot test'
    ];
}

// 8. SSL/TLS Check
$results['checks']['ssl'] = [
    'name' => 'SSL/TLS Support',
    'status' => 'PENDING'
];

if (function_exists('curl_version')) {
    $curlVersion = curl_version();
    $results['checks']['ssl'] = [
        'name' => 'SSL/TLS Support',
        'status' => !empty($curlVersion['ssl_version']) ? 'OK' : 'FAIL',
        'ssl_version' => $curlVersion['ssl_version'] ?? 'None',
        'libz_version' => $curlVersion['libz_version'] ?? 'None',
        'protocols' => $curlVersion['protocols'] ?? [],
        'message' => !empty($curlVersion['ssl_version']) 
            ? 'SSL supported: ' . $curlVersion['ssl_version']
            : 'SSL not available'
    ];
} else {
    $results['checks']['ssl'] = [
        'name' => 'SSL/TLS Support',
        'status' => 'SKIP',
        'message' => 'CURL not available'
    ];
}

// 9. Memory and Limits
$results['checks']['limits'] = [
    'name' => 'PHP Limits',
    'status' => 'OK',
    'memory_limit' => ini_get('memory_limit'),
    'max_execution_time' => ini_get('max_execution_time'),
    'post_max_size' => ini_get('post_max_size'),
    'upload_max_filesize' => ini_get('upload_max_filesize')
];

// Calculate overall status
$overallStatus = 'OK';
$failCount = 0;
$warnCount = 0;

foreach ($results['checks'] as $check) {
    if (isset($check['status'])) {
        if ($check['status'] === 'FAIL') {
            $failCount++;
            $overallStatus = 'FAIL';
        } elseif ($check['status'] === 'WARN') {
            $warnCount++;
            if ($overallStatus !== 'FAIL') {
                $overallStatus = 'WARN';
            }
        }
    }
}

$results['summary'] = [
    'overall_status' => $overallStatus,
    'total_checks' => count($results['checks']),
    'passed' => count($results['checks']) - $failCount - $warnCount,
    'warnings' => $warnCount,
    'failed' => $failCount,
    'message' => $overallStatus === 'OK' 
        ? '✅ All checks passed - System ready'
        : ($overallStatus === 'WARN' 
            ? '⚠️ Some warnings detected'
            : '❌ Critical issues found - Please fix before using')
];

echo json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
exit;

// HTML Output Function
function outputHtmlDiagnostic() {
    header('Content-Type: text/html; charset=utf-8');
    header('Access-Control-Allow-Origin: *');

    echo "<!DOCTYPE html><html dir='rtl'><head><meta charset='UTF-8'><title>Diagnostic Tool</title>";
    echo "<style>
    body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; direction: rtl; }
    .section { background: white; padding: 20px; margin: 20px 0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
    .success { color: green; font-weight: bold; }
    .error { color: red; font-weight: bold; }
    .warning { color: orange; font-weight: bold; }
    pre { background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 5px; overflow-x: auto; direction: ltr; text-align: left; }
    h2 { color: #333; border-bottom: 2px solid #007bff; padding-bottom: 10px; }
    table { width: 100%; border-collapse: collapse; }
    td, th { padding: 8px; border: 1px solid #ddd; text-align: right; }
    th { background: #f0f0f0; }
    </style></head><body>";

    echo "<h1>🔍 أداة تشخيص API - فوترة بلس</h1>";

    // Section 1: Server Info
    echo "<div class='section'>";
    echo "<h2>1️⃣ معلومات الخادم</h2>";
    echo "<table>";
    echo "<tr><th>PHP Version</th><td>" . phpversion() . "</td></tr>";
    echo "<tr><th>CURL Enabled</th><td>" . (function_exists('curl_init') ? "<span class='success'>✅ نعم</span>" : "<span class='error'>❌ لا</span>") . "</td></tr>";
    echo "<tr><th>JSON Enabled</th><td>" . (function_exists('json_encode') ? "<span class='success'>✅ نعم</span>" : "<span class='error'>❌ لا</span>") . "</td></tr>";
    echo "<tr><th>PDO Enabled</th><td>" . (class_exists('PDO') ? "<span class='success'>✅ نعم</span>" : "<span class='error'>❌ لا</span>") . "</td></tr>";
    echo "<tr><th>Current Directory</th><td>" . __DIR__ . "</td></tr>";
    echo "</table>";
    echo "</div>";

    // Section 2: File Existence Check
    echo "<div class='section'>";
    echo "<h2>2️⃣ فحص وجود الملفات</h2>";
    echo "<table>";
    $files = ['auto-crud.php', 'auth.php', 'db.php', 'upload.php', 'government-invoice.php', '.htaccess'];
    foreach ($files as $file) {
        $exists = file_exists(__DIR__ . '/' . $file);
        $size = $exists ? filesize(__DIR__ . '/' . $file) : 0;
        $status = $exists ? "<span class='success'>✅ موجود ({$size} bytes)</span>" : "<span class='error'>❌ غير موجود</span>";
        echo "<tr><td>{$file}</td><td>{$status}</td></tr>";
    }
    echo "</table>";
    echo "</div>";

    // Section 3: Database Connection Test
    echo "<div class='section'>";
    echo "<h2>3️⃣ اختبار قاعدة البيانات</h2>";

    if (file_exists(__DIR__ . '/db.php')) {
        try {
            require_once __DIR__ . '/db.php';
            global $pdo;
            
            if ($pdo) {
                $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
                echo "<p class='success'>✅ تم الاتصال بنجاح!</p>";
                echo "<p>عدد الجداول: " . count($tables) . "</p>";
                echo "<p>الجداول: " . implode(', ', $tables) . "</p>";
            } else {
                echo "<p class='error'>❌ PDO غير مهيأ</p>";
            }
        } catch (Exception $e) {
            echo "<p class='error'>❌ خطأ: " . htmlspecialchars($e->getMessage()) . "</p>";
        }
    } else {
        echo "<p class='error'>❌ ملف db.php غير موجود!</p>";
    }
    echo "</div>";

    // Section 4: Government API Test
    echo "<div class='section'>";
    echo "<h2>4️⃣ اختبار الاتصال بـ API الحكومي</h2>";

    if (function_exists('curl_init')) {
        $ch = curl_init('https://backend.jofotara.gov.jo/core/invoices/');
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_NOBODY => true
        ]);
        
        curl_exec($ch);
        $error = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $totalTime = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
        curl_close($ch);

        if ($httpCode > 0) {
            echo "<p class='success'>✅ الاتصال ناجح! (HTTP {$httpCode} في {$totalTime}s)</p>";
        } else {
            echo "<p class='error'>❌ فشل الاتصال: {$error}</p>";
        }
    } else {
        echo "<p class='error'>❌ CURL غير مفعل - لا يمكن اختبار API الحكومي</p>";
    }
    echo "</div>";

    // Section 5: SSL Info
    if (function_exists('curl_version')) {
        $curlVersion = curl_version();
        echo "<div class='section'>";
        echo "<h2>5️⃣ معلومات SSL</h2>";
        echo "<p>SSL Version: " . ($curlVersion['ssl_version'] ?? 'None') . "</p>";
        echo "</div>";
    }

    echo "<p style='text-align:center; color:#666; margin-top:30px;'>فوترة بلس - أداة التشخيص v2.0</p>";
    echo "<p style='text-align:center;'><a href='?format=json'>عرض كـ JSON</a></p>";
    echo "</body></html>";
}
?>
