<?php
// shamcash/server_check.php - V2 (The Doctor)

ini_set('display_errors', 1);
error_reporting(E_ALL);
header("Content-Type: text/html; charset=utf-8");

echo "<h2>🔍 Server & File Diagnostics</h2>";

// 1. فحص المجلد
$dir = __DIR__;
echo "<strong>Current Dir:</strong> $dir <br>";
if (is_writable($dir)) {
    echo "<span style='color:green'>✅ Directory is Writable (777 OK)</span><br>";
} else {
    echo "<span style='color:red'>❌ Directory NOT Writable! Please set Permissions to 777.</span><br>";
}

// 2. فحص ملف save_transactions.php
$target_file = $dir . '/save_transactions.php';
echo "<hr><h3>Testing 'save_transactions.php':</h3>";

if (!file_exists($target_file)) {
    echo "<span style='color:red'>❌ File not found!</span>";
} else {
    // محاولة فحص الكود بحثاً عن أخطاء نحوية (Syntax Errors)
    $content = file_get_contents($target_file);
    
    // فحص إذا كان المستخدم نسخ علامات Markdown بالخطأ
    if (strpos($content, '```') !== false) {
        echo "<span style='color:red'>❌ <b>CRITICAL ERROR FOUND:</b></span> Markdown tags (```) detected inside the PHP file!<br>";
        echo "👉 <b>Solution:</b> Open the file and remove the first/last lines containing ``` or ```php.<br>";
    } elseif (substr(trim($content), 0, 5) !== '<?php') {
        echo "<span style='color:red'>❌ <b>START ERROR:</b></span> File does not start with &lt;?php<br>";
        echo "Found instead: " . substr(trim($content), 0, 20) . "...<br>";
    } else {
        echo "<span style='color:green'>✅ File structure looks clean (No Markdown tags).</span><br>";
        
        // محاولة استدعاء الملف (سيظهر الخطأ إذا وجد)
        echo "<b>Attempting to include file...</b><br><br>";
        echo "<div style='background:#f0f0f0; padding:10px; border:1px solid #ccc;'>";
        
        // نحجز المخرجات لنرى إذا كان هناك خطأ
        ob_start();
        try {
            include $target_file;
        } catch (Throwable $e) {
            echo "<strong style='color:red'>Runtime Error:</strong> " . $e->getMessage();
        }
        $output = ob_get_clean();
        
        if (empty($output)) {
            echo "File included successfully (No output is good in this context).";
        } else {
            echo "<strong>Output/Error:</strong><br>" . $output;
        }
        echo "</div>";
    }
}
?>